feat(agentcore): expand Bedrock AgentCore control-plane coverage (#3317)

* feat(agentcore): emulate CreateBrowser

* feat(agentcore): emulate GetBrowser

* feat(agentcore): emulate ListBrowsers

* feat(agentcore): emulate DeleteBrowser

* feat(agentcore): emulate CreateBrowserProfile

* feat(agentcore): emulate GetBrowserProfile

* feat(agentcore): emulate ListBrowserProfiles

* feat(agentcore): emulate DeleteBrowserProfile

* feat(agentcore): emulate CreateCodeInterpreter

* feat(agentcore): emulate GetCodeInterpreter

* feat(agentcore): emulate ListCodeInterpreters

* feat(agentcore): emulate DeleteCodeInterpreter

* feat(agentcore): emulate CreateGatewayRule

* feat(agentcore): emulate GetGatewayRule

* feat(agentcore): emulate ListGatewayRules

* feat(agentcore): emulate UpdateGatewayRule

* feat(agentcore): emulate DeleteGatewayRule

* feat(agentcore): emulate CreateApiKeyCredentialProvider

* feat(agentcore): emulate GetApiKeyCredentialProvider

* feat(agentcore): emulate ListApiKeyCredentialProviders

* feat(agentcore): emulate UpdateApiKeyCredentialProvider

* feat(agentcore): emulate DeleteApiKeyCredentialProvider

* feat(agentcore): emulate CreateOauth2CredentialProvider

* feat(agentcore): emulate GetOauth2CredentialProvider

* feat(agentcore): emulate ListOauth2CredentialProviders

* feat(agentcore): emulate UpdateOauth2CredentialProvider

* feat(agentcore): emulate DeleteOauth2CredentialProvider

* feat(agentcore): emulate GetResourcePolicy

* feat(agentcore): emulate PutResourcePolicy

* feat(agentcore): emulate DeleteResourcePolicy

* docs(agentcore): update expanded coverage

* fix(agentcore): align expanded control-plane contracts

* fix(agentcore): address PR review findings

* test(agentcore): cover persistent delete replay
This commit is contained in:
Franklin G. Mendoza authored and GitHub committed 2026-09-10 00:00:51 -05:00
1 parent 283890dce9
commit 483dfb4e1c
18 files changed
+2855 -47

No files matched your search

@@ -0,0 +1,171 @@
package com.floci.test;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.junit.jupiter.api.MethodOrderer;
import software.amazon.awssdk.services.bedrockagentcorecontrol.BedrockAgentCoreControlClient;
import software.amazon.awssdk.services.bedrockagentcorecontrol.model.CreateApiKeyCredentialProviderRequest;
import software.amazon.awssdk.services.bedrockagentcorecontrol.model.CreateApiKeyCredentialProviderResponse;
import software.amazon.awssdk.services.bedrockagentcorecontrol.model.CreateOauth2CredentialProviderRequest;
import software.amazon.awssdk.services.bedrockagentcorecontrol.model.CreateOauth2CredentialProviderResponse;
import software.amazon.awssdk.services.bedrockagentcorecontrol.model.CredentialProviderVendorType;
import software.amazon.awssdk.services.bedrockagentcorecontrol.model.Oauth2ProviderConfigInput;
import software.amazon.awssdk.services.bedrockagentcorecontrol.model.SecretSourceType;
import java.util.UUID;
import static org.assertj.core.api.Assertions.assertThat;
@DisplayName("Bedrock AgentCore credential providers")
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class BedrockAgentCoreCredentialProviderTest {
private static BedrockAgentCoreControlClient client;
private static String apiKeyProviderName;
private static String oauth2ProviderName;
@BeforeAll
static void setup() {
client = TestFixtures.bedrockAgentCoreControlClient();
apiKeyProviderName = "api_" + UUID.randomUUID().toString().replace("-", "").substring(0, 8);
oauth2ProviderName = "oauth_" + UUID.randomUUID().toString().replace("-", "").substring(0, 8);
}
@AfterAll
static void cleanup() {
if (client != null) {
client.close();
}
}
@Test
@Order(1)
void createApiKeyCredentialProvider() {
CreateApiKeyCredentialProviderResponse response = client.createApiKeyCredentialProvider(
CreateApiKeyCredentialProviderRequest.builder()
.name(apiKeyProviderName)
.apiKey("secret-value")
.apiKeySecretSource(SecretSourceType.MANAGED)
.build());
assertThat(response.name()).isEqualTo(apiKeyProviderName);
assertThat(response.apiKeySecretSourceAsString()).isEqualTo("MANAGED");
assertThat(response.credentialProviderArn()).contains(":acps:").contains("/apikeycredentialprovider/");
assertThat(response.apiKeySecretArn().secretArn()).contains(":secretsmanager:");
assertThat(response.apiKeySecretJsonKey()).isEqualTo("apiKey");
}
@Test
@Order(2)
void getApiKeyCredentialProvider() {
var response = client.getApiKeyCredentialProvider(builder -> builder.name(apiKeyProviderName));
assertThat(response.name()).isEqualTo(apiKeyProviderName);
assertThat(response.apiKeySecretSourceAsString()).isEqualTo("MANAGED");
assertThat(response.credentialProviderArn()).contains("/apikeycredentialprovider/");
assertThat(response.createdTime()).isNotNull();
assertThat(response.lastUpdatedTime()).isNotNull();
}
@Test
@Order(3)
void listApiKeyCredentialProviders() {
var response = client.listApiKeyCredentialProviders(builder -> builder.maxResults(100));
assertThat(response.credentialProviders())
.anyMatch(provider -> apiKeyProviderName.equals(provider.name()));
}
@Test
@Order(4)
void updateApiKeyCredentialProvider() {
var response = client.updateApiKeyCredentialProvider(builder -> builder
.name(apiKeyProviderName)
.apiKey("rotated-value")
.apiKeySecretSource(SecretSourceType.MANAGED));
assertThat(response.name()).isEqualTo(apiKeyProviderName);
assertThat(response.apiKeySecretSourceAsString()).isEqualTo("MANAGED");
assertThat(response.lastUpdatedTime()).isNotNull();
}
@Test
@Order(5)
void deleteApiKeyCredentialProvider() {
var response = client.deleteApiKeyCredentialProvider(builder -> builder.name(apiKeyProviderName));
assertThat(response.sdkHttpResponse().statusCode()).isEqualTo(204);
}
@Test
@Order(6)
void createOauth2CredentialProvider() {
CreateOauth2CredentialProviderResponse response = client.createOauth2CredentialProvider(
CreateOauth2CredentialProviderRequest.builder()
.name(oauth2ProviderName)
.credentialProviderVendor(CredentialProviderVendorType.GITHUB_OAUTH2)
.oauth2ProviderConfigInput(Oauth2ProviderConfigInput.fromGithubOauth2ProviderConfig(builder -> builder
.clientId("client-id")
.clientSecret("client-value")
.clientSecretSource(SecretSourceType.MANAGED)))
.build());
assertThat(response.name()).isEqualTo(oauth2ProviderName);
assertThat(response.credentialProviderArn()).contains("/oauth2credentialprovider/");
assertThat(response.clientSecretSourceAsString()).isEqualTo("MANAGED");
assertThat(response.statusAsString()).isEqualTo("READY");
assertThat(response.oauth2ProviderConfigOutput().githubOauth2ProviderConfig().clientId()).isEqualTo("client-id");
}
@Test
@Order(7)
void getOauth2CredentialProvider() {
var response = client.getOauth2CredentialProvider(builder -> builder.name(oauth2ProviderName));
assertThat(response.name()).isEqualTo(oauth2ProviderName);
assertThat(response.credentialProviderVendorAsString()).isEqualTo("GithubOauth2");
assertThat(response.statusAsString()).isEqualTo("READY");
assertThat(response.createdTime()).isNotNull();
assertThat(response.lastUpdatedTime()).isNotNull();
assertThat(response.oauth2ProviderConfigOutput().githubOauth2ProviderConfig().clientId()).isEqualTo("client-id");
}
@Test
@Order(8)
void listOauth2CredentialProviders() {
var response = client.listOauth2CredentialProviders(builder -> builder.maxResults(20));
assertThat(response.credentialProviders())
.anyMatch(provider -> oauth2ProviderName.equals(provider.name())
&& "GithubOauth2".equals(provider.credentialProviderVendorAsString()));
}
@Test
@Order(9)
void updateOauth2CredentialProvider() {
var response = client.updateOauth2CredentialProvider(builder -> builder
.name(oauth2ProviderName)
.credentialProviderVendor(CredentialProviderVendorType.GITHUB_OAUTH2)
.oauth2ProviderConfigInput(Oauth2ProviderConfigInput.fromGithubOauth2ProviderConfig(config -> config
.clientId("updated-client-id")
.clientSecret("updated-client-secret")
.clientSecretSource(SecretSourceType.MANAGED))));
assertThat(response.name()).isEqualTo(oauth2ProviderName);
assertThat(response.statusAsString()).isEqualTo("READY");
assertThat(response.credentialProviderVendorAsString()).isEqualTo("GithubOauth2");
assertThat(response.oauth2ProviderConfigOutput().githubOauth2ProviderConfig().clientId())
.isEqualTo("updated-client-id");
assertThat(response.lastUpdatedTime()).isNotNull();
}
@Test
@Order(10)
void deleteOauth2CredentialProvider() {
var response = client.deleteOauth2CredentialProvider(builder -> builder.name(oauth2ProviderName));
assertThat(response.sdkHttpResponse().statusCode()).isEqualTo(204);
}
}
@@ -0,0 +1,146 @@
package com.floci.test;
import org.jboss.logging.Logger;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import software.amazon.awssdk.services.bedrockagentcorecontrol.BedrockAgentCoreControlClient;
import software.amazon.awssdk.services.bedrockagentcorecontrol.model.*;
import java.util.UUID;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@DisplayName("Bedrock AgentCore gateway rules")
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class BedrockAgentCoreGatewayRuleTest {
private static final Logger LOG = Logger.getLogger(BedrockAgentCoreGatewayRuleTest.class);
private static final String ROLE_ARN = "arn:aws:iam::000000000000:role/gw";
private static BedrockAgentCoreControlClient client;
private static String gatewayId;
private static String ruleId;
@BeforeAll
static void setup() {
client = TestFixtures.bedrockAgentCoreControlClient();
String name = "gw" + UUID.randomUUID().toString().replace("-", "").substring(0, 8);
gatewayId = client.createGateway(CreateGatewayRequest.builder()
.name(name)
.protocolType(GatewayProtocolType.MCP)
.authorizerType(AuthorizerType.AWS_IAM)
.roleArn(ROLE_ARN)
.build()).gatewayId();
}
@AfterAll
static void cleanup() {
if (client != null) {
try {
client.deleteGateway(DeleteGatewayRequest.builder().gatewayIdentifier(gatewayId).build());
} catch (Exception e) {
LOG.warnf(e, "Failed to delete AgentCore gateway %s during test cleanup", gatewayId);
}
client.close();
}
}
@Test
@Order(1)
void createGatewayRule() {
Action action = Action.fromRouteToTarget(RouteToTargetAction.fromStaticRoute(
StaticRoute.builder().targetName("target").build()));
CreateGatewayRuleResponse response = client.createGatewayRule(CreateGatewayRuleRequest.builder()
.gatewayIdentifier(gatewayId)
.priority(1)
.actions(action)
.description("route")
.build());
ruleId = response.ruleId();
assertThat(ruleId).matches("[0-9a-f-]{36}");
assertThat(response.gatewayArn()).contains(":gateway/");
assertThat(response.statusAsString()).isEqualTo("ACTIVE");
assertThat(response.priority()).isEqualTo(1);
assertThat(response.actions()).hasSize(1);
}
@Test
@Order(2)
void getGatewayRule() {
GetGatewayRuleResponse response = client.getGatewayRule(GetGatewayRuleRequest.builder()
.gatewayIdentifier(gatewayId)
.ruleId(ruleId)
.build());
assertThat(response.ruleId()).isEqualTo(ruleId);
assertThat(response.priority()).isEqualTo(1);
assertThat(response.description()).isEqualTo("route");
assertThat(response.statusAsString()).isEqualTo("ACTIVE");
assertThat(response.actions()).hasSize(1);
}
@Test
@Order(3)
void listGatewayRules() {
ListGatewayRulesResponse response = client.listGatewayRules(ListGatewayRulesRequest.builder()
.gatewayIdentifier(gatewayId)
.maxResults(100)
.build());
assertThat(response.gatewayRules())
.anyMatch(rule -> ruleId.equals(rule.ruleId()));
}
@Test
@Order(4)
void updateGatewayRule() {
Action action = Action.fromRouteToTarget(RouteToTargetAction.fromStaticRoute(
StaticRoute.builder().targetName("updated-target").build()));
UpdateGatewayRuleResponse response = client.updateGatewayRule(UpdateGatewayRuleRequest.builder()
.gatewayIdentifier(gatewayId)
.ruleId(ruleId)
.priority(2)
.actions(action)
.description("updated route")
.build());
assertThat(response.ruleId()).isEqualTo(ruleId);
assertThat(response.priority()).isEqualTo(2);
assertThat(response.description()).isEqualTo("updated route");
assertThat(response.actions()).hasSize(1);
assertThat(response.statusAsString()).isEqualTo("ACTIVE");
assertThat(response.updatedAt()).isNotNull();
}
@Test
@Order(5)
void createGatewayRuleRejectsInvalidNestedAction() {
Action invalidAction = Action.fromRouteToTarget(RouteToTargetAction.fromStaticRoute(
StaticRoute.builder().build()));
assertThatThrownBy(() -> client.createGatewayRule(CreateGatewayRuleRequest.builder()
.gatewayIdentifier(gatewayId)
.priority(3)
.actions(invalidAction)
.build()))
.isInstanceOf(ValidationException.class);
}
@Test
@Order(6)
void deleteGatewayRule() {
DeleteGatewayRuleResponse response = client.deleteGatewayRule(DeleteGatewayRuleRequest.builder()
.gatewayIdentifier(gatewayId)
.ruleId(ruleId)
.build());
assertThat(response.ruleId()).isEqualTo(ruleId);
assertThat(response.statusAsString()).isEqualTo("DELETING");
}
}
@@ -0,0 +1,67 @@
package com.floci.test;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.services.bedrockagentcorecontrol.BedrockAgentCoreControlClient;
import software.amazon.awssdk.services.bedrockagentcorecontrol.model.DeleteResourcePolicyRequest;
import software.amazon.awssdk.services.bedrockagentcorecontrol.model.GetResourcePolicyRequest;
import software.amazon.awssdk.services.bedrockagentcorecontrol.model.PutResourcePolicyRequest;
import software.amazon.awssdk.services.bedrockagentcorecontrol.model.ResourceNotFoundException;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@DisplayName("Bedrock AgentCore resource policy")
class BedrockAgentCoreResourcePolicyTest {
private static final String RESOURCE_ARN =
"arn:aws:bedrock-agentcore:us-east-1:000000000000:gateway/example-1234567890";
@Test
void getMissingResourcePolicy() {
try (BedrockAgentCoreControlClient client = TestFixtures.bedrockAgentCoreControlClient()) {
assertThatThrownBy(() -> client.getResourcePolicy(GetResourcePolicyRequest.builder()
.resourceArn(RESOURCE_ARN)
.build()))
.isInstanceOf(ResourceNotFoundException.class);
}
}
@Test
void putAndGetResourcePolicy() {
try (BedrockAgentCoreControlClient client = TestFixtures.bedrockAgentCoreControlClient()) {
String policy = "{\"Version\":\"2012-10-17\",\"Statement\":[]}";
var put = client.putResourcePolicy(PutResourcePolicyRequest.builder()
.resourceArn(RESOURCE_ARN)
.policy(policy)
.build());
assertThat(put.policy()).isEqualTo(policy);
var get = client.getResourcePolicy(GetResourcePolicyRequest.builder()
.resourceArn(RESOURCE_ARN)
.build());
assertThat(get.policy()).isEqualTo(policy);
}
}
@Test
void deleteResourcePolicy() {
try (BedrockAgentCoreControlClient client = TestFixtures.bedrockAgentCoreControlClient()) {
String policy = "{\"Version\":\"2012-10-17\",\"Statement\":[]}";
client.putResourcePolicy(PutResourcePolicyRequest.builder()
.resourceArn(RESOURCE_ARN)
.policy(policy)
.build());
var deleted = client.deleteResourcePolicy(DeleteResourcePolicyRequest.builder()
.resourceArn(RESOURCE_ARN)
.build());
assertThat(deleted.sdkHttpResponse().statusCode()).isEqualTo(204);
assertThatThrownBy(() -> client.getResourcePolicy(GetResourcePolicyRequest.builder()
.resourceArn(RESOURCE_ARN)
.build()))
.isInstanceOf(ResourceNotFoundException.class);
}
}
}
@@ -0,0 +1,222 @@
package com.floci.test;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import software.amazon.awssdk.services.bedrockagentcorecontrol.BedrockAgentCoreControlClient;
import software.amazon.awssdk.services.bedrockagentcorecontrol.model.*;
import java.util.UUID;
import static org.assertj.core.api.Assertions.assertThat;
@DisplayName("Bedrock AgentCore tools")
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class BedrockAgentCoreToolsTest {
private static BedrockAgentCoreControlClient client;
private static String browserName;
private static String browserId;
private static String profileName;
private static String profileId;
private static String codeInterpreterName;
private static String codeInterpreterId;
@BeforeAll
static void setup() {
client = TestFixtures.bedrockAgentCoreControlClient();
browserName = "browser" + UUID.randomUUID().toString().replace("-", "").substring(0, 8);
profileName = "profile" + UUID.randomUUID().toString().replace("-", "").substring(0, 8);
codeInterpreterName = "code" + UUID.randomUUID().toString().replace("-", "").substring(0, 8);
}
@AfterAll
static void cleanup() {
if (client != null) {
client.close();
}
}
@Test
@Order(1)
void createBrowser() {
CreateBrowserResponse response = client.createBrowser(CreateBrowserRequest.builder()
.name(browserName)
.networkConfiguration(BrowserNetworkConfiguration.builder()
.networkMode(BrowserNetworkMode.PUBLIC)
.build())
.build());
browserId = response.browserId();
assertThat(browserId).startsWith(browserName + "-");
assertThat(response.browserArn()).contains(":bedrock-agentcore:").contains(":browser-custom/");
assertThat(response.statusAsString()).isEqualTo("READY");
assertThat(response.createdAt()).isNotNull();
}
@Test
@Order(2)
void getBrowser() {
GetBrowserResponse response = client.getBrowser(GetBrowserRequest.builder()
.browserId(browserId)
.build());
assertThat(response.browserId()).isEqualTo(browserId);
assertThat(response.name()).isEqualTo(browserName);
assertThat(response.browserArn()).contains(":browser-custom/");
assertThat(response.networkConfiguration().networkModeAsString()).isEqualTo("PUBLIC");
assertThat(response.statusAsString()).isEqualTo("READY");
}
@Test
@Order(3)
void listBrowsers() {
ListBrowsersResponse response = client.listBrowsers(ListBrowsersRequest.builder()
.type(ResourceType.CUSTOM)
.maxResults(100)
.build());
assertThat(response.browserSummaries())
.anyMatch(summary -> browserId.equals(summary.browserId()));
}
@Test
@Order(4)
void deleteBrowser() {
String clientToken = UUID.randomUUID().toString();
DeleteBrowserRequest request = DeleteBrowserRequest.builder()
.browserId(browserId)
.clientToken(clientToken)
.build();
DeleteBrowserResponse response = client.deleteBrowser(request);
DeleteBrowserResponse replay = client.deleteBrowser(request);
assertThat(response.browserId()).isEqualTo(browserId);
assertThat(response.statusAsString()).isEqualTo("DELETING");
assertThat(response.lastUpdatedAt()).isNotNull();
assertThat(replay.browserId()).isEqualTo(browserId);
assertThat(replay.statusAsString()).isEqualTo("DELETING");
}
@Test
@Order(5)
void createBrowserProfile() {
CreateBrowserProfileResponse response = client.createBrowserProfile(CreateBrowserProfileRequest.builder()
.name(profileName)
.description("profile")
.build());
profileId = response.profileId();
assertThat(profileId).startsWith(profileName + "-");
assertThat(response.profileArn()).contains(":browser-profile/");
assertThat(response.statusAsString()).isEqualTo("READY");
assertThat(response.createdAt()).isNotNull();
}
@Test
@Order(6)
void getBrowserProfile() {
GetBrowserProfileResponse response = client.getBrowserProfile(GetBrowserProfileRequest.builder()
.profileId(profileId)
.build());
assertThat(response.profileId()).isEqualTo(profileId);
assertThat(response.name()).isEqualTo(profileName);
assertThat(response.description()).isEqualTo("profile");
assertThat(response.statusAsString()).isEqualTo("READY");
}
@Test
@Order(7)
void listBrowserProfiles() {
ListBrowserProfilesResponse response = client.listBrowserProfiles(ListBrowserProfilesRequest.builder()
.name(profileName)
.maxResults(100)
.build());
assertThat(response.profileSummaries())
.anyMatch(summary -> profileId.equals(summary.profileId()));
}
@Test
@Order(8)
void deleteBrowserProfile() {
String clientToken = UUID.randomUUID().toString();
DeleteBrowserProfileRequest request = DeleteBrowserProfileRequest.builder()
.profileId(profileId)
.clientToken(clientToken)
.build();
DeleteBrowserProfileResponse response = client.deleteBrowserProfile(request);
DeleteBrowserProfileResponse replay = client.deleteBrowserProfile(request);
assertThat(response.profileId()).isEqualTo(profileId);
assertThat(response.statusAsString()).isEqualTo("DELETING");
assertThat(response.lastUpdatedAt()).isNotNull();
assertThat(replay.profileId()).isEqualTo(profileId);
assertThat(replay.statusAsString()).isEqualTo("DELETING");
}
@Test
@Order(9)
void createCodeInterpreter() {
CreateCodeInterpreterResponse response = client.createCodeInterpreter(CreateCodeInterpreterRequest.builder()
.name(codeInterpreterName)
.networkConfiguration(CodeInterpreterNetworkConfiguration.builder()
.networkMode(CodeInterpreterNetworkMode.PUBLIC)
.build())
.build());
codeInterpreterId = response.codeInterpreterId();
assertThat(codeInterpreterId).startsWith(codeInterpreterName + "-");
assertThat(response.codeInterpreterArn()).contains(":code-interpreter-custom/");
assertThat(response.statusAsString()).isEqualTo("READY");
assertThat(response.createdAt()).isNotNull();
}
@Test
@Order(10)
void getCodeInterpreter() {
GetCodeInterpreterResponse response = client.getCodeInterpreter(GetCodeInterpreterRequest.builder()
.codeInterpreterId(codeInterpreterId)
.build());
assertThat(response.codeInterpreterId()).isEqualTo(codeInterpreterId);
assertThat(response.name()).isEqualTo(codeInterpreterName);
assertThat(response.networkConfiguration().networkModeAsString()).isEqualTo("PUBLIC");
assertThat(response.statusAsString()).isEqualTo("READY");
}
@Test
@Order(11)
void listCodeInterpreters() {
ListCodeInterpretersResponse response = client.listCodeInterpreters(ListCodeInterpretersRequest.builder()
.type(ResourceType.CUSTOM)
.maxResults(100)
.build());
assertThat(response.codeInterpreterSummaries())
.anyMatch(summary -> codeInterpreterId.equals(summary.codeInterpreterId()));
}
@Test
@Order(12)
void deleteCodeInterpreter() {
String clientToken = UUID.randomUUID().toString();
DeleteCodeInterpreterRequest request = DeleteCodeInterpreterRequest.builder()
.codeInterpreterId(codeInterpreterId)
.clientToken(clientToken)
.build();
DeleteCodeInterpreterResponse response = client.deleteCodeInterpreter(request);
DeleteCodeInterpreterResponse replay = client.deleteCodeInterpreter(request);
assertThat(response.codeInterpreterId()).isEqualTo(codeInterpreterId);
assertThat(response.statusAsString()).isEqualTo("DELETING");
assertThat(response.lastUpdatedAt()).isNotNull();
assertThat(replay.codeInterpreterId()).isEqualTo(codeInterpreterId);
assertThat(replay.statusAsString()).isEqualTo("DELETING");
}
}
+36 -27
View File
@@ -1,6 +1,6 @@
# Design: Amazon Bedrock AgentCore emulation
Status: proposed. Tracked by the AgentCore epic and phase issues on this fork.
Status: implemented and actively expanded. Tracked by the AgentCore epic and follow-up coverage work on this fork.
## Goal
@@ -18,18 +18,22 @@ Two AWS services are involved:
| `bedrock-agentcore-control` | 2023-06-05 | `bedrock-agentcore` | REST JSON (restJson1) | stateful CRUD registry |
| `bedrock-agentcore` | 2024-02-28 | `bedrock-agentcore` | REST JSON (binary payload) | `InvokeAgentRuntime` canned-response stub |
## Scope (MVP)
## Implemented scope
- Phase 1 — Agent Runtime CRUD (`bedrock-agentcore-control`)
- Phase 2 — Agent Runtime Endpoints
- Phase 3 — `InvokeAgentRuntime` data-plane stub (`bedrock-agentcore`)
- Phase 4 — Tagging + Workload Identity
- Phase 5 (optional) — Gateway + Memory primitives
- Agent Runtime CRUD and versioning (`bedrock-agentcore-control`)
- Agent Runtime Endpoints
- `InvokeAgentRuntime` data-plane canned-response stub (`bedrock-agentcore`)
- Tagging + Workload Identity
- Gateway + Gateway Target + Gateway Rule primitives
- Memory primitives
- Browser + Browser Profile primitives
- Code Interpreter primitives
- API key + OAuth2 credential providers
- Resource policies
Out of scope for the MVP: real inference, streaming invoke semantics, gateway
rules, policy engine, registry, payment, browser, code interpreter, dataset,
evaluator, harness, token vault, credential providers, IAM enforcement. All are
reachable via the upgrade path below.
Still out of scope: real inference, streaming invoke semantics, policy engine,
registry, payment, dataset, evaluator, harness, the broader token-vault data plane,
and IAM enforcement. These remain candidates for future coverage expansion.
## Floci integration conventions
@@ -161,10 +165,10 @@ parent `gatewayArn`). Mutations return 202. `protocolType`: gateway `MCP`, targe
→ return `ACTIVE`. `clientToken` is a body field on Create/Update but a query param on Delete.
The Memory response shape has no `tags` field — tags surface only through `ListTagsForResource`.
## Upgrade path — extending beyond the MVP
## Upgrade path: extending coverage
`bedrock-agentcore-control` has ~140 operations; the MVP covers the runtime-centric subset. The rest
add incrementally without rework, because every operation reduces to the same Floci recipe.
The AgentCore control plane is much broader than the currently implemented subset. Additional
operations can be added incrementally without rework because they follow the same Floci recipe.
### Three wire-protocol styles coexist in this one service
Classify each new operation before writing the controller:
@@ -187,20 +191,24 @@ Always confirm the exact `Method + Path` on each operation's `API_<Op>.html` pag
4. Add unit + RestAssured integration tests; run `make docs-sync`.
### Full operation catalog & status
"Planned" = MVP issue set; "Future" = same recipe, not yet scheduled.
"Implemented" means the operation family has working Floci coverage. "Future" identifies remaining
families that can use the same protocol-first implementation recipe.
| Resource family | Operations | Style | Status |
|---|---|---|---|
| Agent Runtime | Create/Get/Update/Delete/List + ListVersions | A | Planned |
| Agent Runtime Endpoint | Create/Get/Update/Delete/List | A | Planned |
| InvokeAgentRuntime (data plane) | Invoke | A (binary) | Planned |
| Tagging | Tag/Untag/ListTagsForResource | A (`/tags/{arn}`) | Planned |
| Workload Identity | Create/Get/Update/Delete/List | B | Planned |
| Gateway + Gateway Target | Create/Get/Update/Delete/List (×2) | A | Planned |
| Memory | Create/Get/Update/Delete/List | C | Planned |
| Gateway Rule | Create/Get/Update/Delete/List | A | Future |
| Credential Providers (ApiKey/OAuth2/Payment) | Create/Get/Update/Delete/List | B | Future |
| Browser / Browser Profile / Code Interpreter | Create/Get/Delete/List | A | Future |
| Agent Runtime | Create/Get/Update/Delete/List + ListVersions | A | Implemented |
| Agent Runtime Endpoint | Create/Get/Update/Delete/List | A | Implemented |
| InvokeAgentRuntime (data plane) | Invoke | A (binary) | Implemented (canned-response stub) |
| Tagging | Tag/Untag/ListTagsForResource | A (`/tags/{arn}`) | Implemented |
| Workload Identity | Create/Get/Update/Delete/List | B | Implemented |
| Gateway + Gateway Target | Create/Get/Update/Delete/List (x2) | A | Implemented |
| Memory | Create/Get/Update/Delete/List | C | Implemented |
| Gateway Rule | Create/Get/Update/Delete/List | A | Implemented |
| API Key + OAuth2 Credential Providers | Create/Get/Update/Delete/List | B | Implemented |
| Browser / Browser Profile / Code Interpreter | Create/Get/Delete/List | A | Implemented |
| Resource Policy | Get/Put/Delete | A | Implemented |
| Payment Credential Providers | Create/Get/Update/Delete/List | B | Future |
| Policy / Policy Engine / Policy Generation | Create/Get/Update/Delete/List + Start/Summary | mixed | Future |
| Registry / Registry Record | Create/Get/Update/Delete/List + Submit | mixed | Future |
| Dataset / Dataset Version / Examples | Create/Get/Update/Delete/List + Add/Delete examples | mixed | Future |
@@ -208,6 +216,7 @@ Always confirm the exact `Method + Path` on each operation's `API_<Op>.html` pag
| Harness / Harness Endpoint | Create/Get/Update/Delete/List | A | Future |
| Configuration Bundle | Create/Get/Update/Delete/List (+ versions) | A | Future |
| Payment Manager / Connector | Create/Get/Update/Delete/List | mixed | Future |
| Token Vault / Resource Policy | Get/Put/Delete/SetCMK | B | Future |
| Broader Token Vault operations | Additional token/secret management operations | mixed | Future |
A future contributor picks any "Future" row, applies the recipe, and files a follow-up referencing the epic.
Future rows are candidates for follow-up coverage work using the same investigate, implement,
validate, review, and commit cycle.
+63 -18
View File
@@ -4,33 +4,78 @@
**Endpoint:** `http://localhost:4566/runtimes/...`
Emulates the Amazon Bedrock AgentCore **control plane** (`bedrock-agentcore-control`)
as a stateful runtime registry. No real agent execution — runtimes reach `READY`
immediately and hold metadata only. See
[the design note](../design/bedrock-agentcore.md) for scope and the roadmap covering
endpoints, the `InvokeAgentRuntime` data-plane stub, tagging, workload identity, and
gateway/memory primitives.
as a stateful local registry across runtimes, endpoints, gateways, memories, browser/code-interpreter
resources, credential providers, gateway rules, and resource policies. No real agent execution:
runtimes reach `READY` immediately and hold metadata only. See
[the design note](../design/bedrock-agentcore.md) for scope and protocol details.
## Supported Actions
<!-- floci:actions:start -->
| Action | Description |
|---|---|
| --- | --- |
| `CreateAgentRuntime` | Register an agent runtime; returns an id, versioned ARN, and workload identity |
| `GetAgentRuntime` | Get a runtime, optionally a specific `version` |
| `ListAgentRuntimes` | List runtimes (paginated) |
| `GetAgentRuntime` | Get a runtime, optionally a specific `version` |
| `UpdateAgentRuntime` | Update a runtime; appends a new immutable version |
| `ListAgentRuntimeVersions` | List a runtime's versions (paginated) |
| `DeleteAgentRuntime` | Delete a runtime |
| `CreateAgentRuntimeEndpoint` | Create a named endpoint (qualifier) targeting a version |
| `GetAgentRuntimeEndpoint` | Get an endpoint |
| `UpdateAgentRuntimeEndpoint` | Retarget an endpoint's version / update its description |
| `ListAgentRuntimeEndpoints` | List a runtime's endpoints (paginated) |
| `DeleteAgentRuntimeEndpoint` | Delete an endpoint |
| `InvokeAgentRuntime` *(data plane)* | Invoke a runtime; returns a fixed canned response |
| `TagResource` / `UntagResource` / `ListTagsForResource` | Tag runtimes, gateways, and memory resources via the shared `/tags/{arn}` route |
| `CreateWorkloadIdentity` / `GetWorkloadIdentity` / `UpdateWorkloadIdentity` / `DeleteWorkloadIdentity` / `ListWorkloadIdentities` | Manage workload identities (`POST /identities/<Op>`) |
| `CreateGateway` / `GetGateway` / `UpdateGateway` / `DeleteGateway` / `ListGateways` | Manage gateways (metadata only) |
| `CreateGatewayTarget` / `GetGatewayTarget` / `UpdateGatewayTarget` / `DeleteGatewayTarget` / `ListGatewayTargets` | Manage gateway targets |
| `CreateMemory` / `GetMemory` / `UpdateMemory` / `DeleteMemory` / `ListMemories` | Manage memory resources (metadata only) |
| `CreateAgentRuntimeEndpoint` | Creates a named runtime endpoint targeting an agent runtime version |
| `GetAgentRuntimeEndpoint` | Returns a runtime endpoint |
| `UpdateAgentRuntimeEndpoint` | Updates the target version or description of a runtime endpoint |
| `DeleteAgentRuntimeEndpoint` | Deletes a runtime endpoint |
| `ListAgentRuntimeEndpoints` | Lists runtime endpoints for an agent runtime |
| `CreateWorkloadIdentity` | Creates a workload identity |
| `GetWorkloadIdentity` | Returns a workload identity |
| `UpdateWorkloadIdentity` | Updates a workload identity |
| `DeleteWorkloadIdentity` | Deletes a workload identity |
| `ListWorkloadIdentities` | Lists workload identities |
| `CreateApiKeyCredentialProvider` | Creates an API key credential provider |
| `GetApiKeyCredentialProvider` | Returns an API key credential provider |
| `ListApiKeyCredentialProviders` | Lists API key credential providers |
| `UpdateApiKeyCredentialProvider` | Updates an API key credential provider |
| `DeleteApiKeyCredentialProvider` | Deletes an API key credential provider |
| `CreateOauth2CredentialProvider` | Creates an OAuth2 credential provider |
| `GetOauth2CredentialProvider` | Returns an OAuth2 credential provider |
| `ListOauth2CredentialProviders` | Lists OAuth2 credential providers |
| `UpdateOauth2CredentialProvider` | Updates an OAuth2 credential provider |
| `DeleteOauth2CredentialProvider` | Deletes an OAuth2 credential provider |
| `CreateGateway` | Creates a gateway |
| `GetGateway` | Returns a gateway |
| `UpdateGateway` | Updates a gateway |
| `DeleteGateway` | Deletes a gateway |
| `ListGateways` | Lists gateways |
| `CreateGatewayTarget` | Creates a target on a gateway |
| `GetGatewayTarget` | Returns a gateway target |
| `UpdateGatewayTarget` | Updates a gateway target |
| `DeleteGatewayTarget` | Deletes a gateway target |
| `ListGatewayTargets` | Lists targets on a gateway |
| `CreateMemory` | Creates a memory resource |
| `GetMemory` | Returns a memory resource |
| `UpdateMemory` | Updates a memory resource |
| `DeleteMemory` | Deletes a memory resource |
| `ListMemories` | Lists memory resources |
| `CreateBrowser` | Creates a custom browser |
| `GetCodeInterpreter` | Returns a custom or system code interpreter |
| `DeleteCodeInterpreter` | Deletes a custom code interpreter |
| `ListCodeInterpreters` | Lists custom and system code interpreters |
| `CreateCodeInterpreter` | Creates a custom code interpreter |
| `CreateBrowserProfile` | Creates a browser profile |
| `ListBrowserProfiles` | Lists browser profiles |
| `DeleteBrowserProfile` | Deletes a browser profile |
| `GetBrowserProfile` | Returns a browser profile |
| `GetBrowser` | Returns a custom or system browser |
| `DeleteBrowser` | Deletes a custom browser |
| `ListBrowsers` | Lists custom and system browsers |
| `CreateGatewayRule` | Creates a gateway rule |
| `GetGatewayRule` | Returns a gateway rule |
| `ListGatewayRules` | Lists rules on a gateway |
| `UpdateGatewayRule` | Updates a gateway rule |
| `DeleteGatewayRule` | Deletes a gateway rule |
| `GetResourcePolicy` | Returns the policy attached to an AgentCore resource |
| `PutResourcePolicy` | Creates or replaces a policy on an AgentCore resource |
| `DeleteResourcePolicy` | Deletes the policy attached to an AgentCore resource |
<!-- floci:actions:end -->
A `DEFAULT` endpoint is created automatically with each runtime, and each runtime
is associated with an auto-created, resolvable workload identity.
+1 -1
View File
@@ -85,7 +85,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac
| [AppConfigData](appconfig.md#data-plane) | `/configurationsessions`, `/configuration` | REST JSON | 2 |
| [AppSync](appsync.md) | `/v1/apis/...` | REST JSON | 33 |
| [Bedrock Runtime](bedrock-runtime.md) | `/model/{modelId}/converse`, `/model/{modelId}/invoke` | REST JSON | 2 (stub; streaming returns 501) |
| [Bedrock AgentCore Control](bedrock-agentcore.md) | `/runtimes/*`, `/gateways/*`, `/memories/*`, `/identities/*`, `/tags/{resourceArn}` | REST JSON | 31 (+ 3 tagging via shared `/tags/{arn}` route) |
| [Bedrock AgentCore Control](bedrock-agentcore.md) | `/runtimes/*`, `/gateways/*`, `/memories/*`, `/identities/*`, `/browsers*`, `/browser-profiles*`, `/code-interpreters*`, `/resourcepolicy/*`, `/tags/{resourceArn}` | REST JSON | 61 (+ 3 tagging via shared `/tags/{arn}` route) |
| [Bedrock AgentCore](bedrock-agentcore.md#data-plane-invokeagentruntime) | `/runtimes/{agentRuntimeArn}/invocations` | REST JSON (binary payload) | 1 (canned-response stub) |
| [EKS](eks.md) | `/clusters`, `/clusters/{name}`, `/tags/{resourceArn}` | REST JSON | 7 |
| [ELB v2](elb.md) | `POST /` with `Action=` param | Query | 34 |
@@ -18,8 +18,11 @@ 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.BedrockAgentCoreGatewayRuleController;
import io.github.hectorvent.floci.services.bedrockagentcorecontrol.BedrockAgentCoreIdentityController;
import io.github.hectorvent.floci.services.bedrockagentcorecontrol.BedrockAgentCoreMemoryController;
import io.github.hectorvent.floci.services.bedrockagentcorecontrol.BedrockAgentCoreResourcePolicyController;
import io.github.hectorvent.floci.services.bedrockagentcorecontrol.BedrockAgentCoreToolsController;
import io.github.hectorvent.floci.services.pipes.PipesController;
import io.github.hectorvent.floci.services.lambda.LambdaController;
import io.github.hectorvent.floci.services.lambdamicrovms.LambdaMicrovmsController;
@@ -343,7 +346,9 @@ public class ResolvedServiceCatalog {
protocols(ServiceProtocol.REST_JSON),
Set.of(), Set.of("bedrock-agentcore"), Set.of(),
Set.of(BedrockAgentCoreControlController.class, BedrockAgentCoreIdentityController.class,
BedrockAgentCoreGatewayController.class, BedrockAgentCoreMemoryController.class)),
BedrockAgentCoreGatewayController.class, BedrockAgentCoreMemoryController.class,
BedrockAgentCoreToolsController.class, BedrockAgentCoreGatewayRuleController.class,
BedrockAgentCoreResourcePolicyController.class)),
descriptor("bedrock-agentcore", "bedrock-agentcore",
config.services().bedrockAgentCore().enabled(), true,
null, null, 5000L, null, ServiceProtocol.REST_JSON,
@@ -0,0 +1,474 @@
package io.github.hectorvent.floci.services.bedrockagentcorecontrol;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.Pagination;
import io.github.hectorvent.floci.core.common.PaginatedResult;
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 jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.time.Instant;
import java.util.List;
import java.util.Map;
@ApplicationScoped
public class BedrockAgentCoreCredentialProviderService {
private final StorageBackend<String, ObjectNode> storage;
private final RegionResolver regionResolver;
@Inject
public BedrockAgentCoreCredentialProviderService(StorageFactory storageFactory,
RegionResolver regionResolver) {
this(storageFactory.create("bedrockagentcore", "bedrock-agentcore-credential-providers.json",
new TypeReference<Map<String, ObjectNode>>() {}), regionResolver);
}
BedrockAgentCoreCredentialProviderService(StorageBackend<String, ObjectNode> storage,
RegionResolver regionResolver) {
this.storage = storage;
this.regionResolver = regionResolver;
}
public ObjectNode createApiKey(ObjectNode request, String region) {
String name = requiredName(request);
String key = key("apikey", region, name);
if (storage.get(key).isPresent()) {
throw new AwsException("ConflictException", "API key credential provider already exists: " + name, 409);
}
String source = text(request, "apiKeySecretSource");
if (source == null) {
source = "MANAGED";
}
if (!source.equals("MANAGED") && !source.equals("EXTERNAL")) {
throw new AwsException("ValidationException", "apiKeySecretSource must be MANAGED or EXTERNAL", 400);
}
String apiKey = text(request, "apiKey");
if (apiKey != null && apiKey.length() > 65536) {
throw new AwsException("ValidationException", "apiKey exceeds maximum length of 65536", 400);
}
JsonNode secretConfig = request.get("apiKeySecretConfig");
if (source.equals("EXTERNAL")) {
if (secretConfig == null || !secretConfig.isObject()
|| !secretConfig.hasNonNull("secretId") || !secretConfig.hasNonNull("jsonKey")) {
throw new AwsException("ValidationException",
"apiKeySecretConfig with secretId and jsonKey is required for EXTERNAL source", 400);
}
String secretId = secretConfig.path("secretId").asText();
String jsonKey = secretConfig.path("jsonKey").asText();
if (secretId.length() < 1 || secretId.length() > 2048) {
throw new AwsException("ValidationException", "secretId must be between 1 and 2048 characters", 400);
}
if (jsonKey.length() < 1 || jsonKey.length() > 128) {
throw new AwsException("ValidationException", "jsonKey must be between 1 and 128 characters", 400);
}
}
validateTags(request.get("tags"));
Instant now = Instant.now();
ObjectNode item = JsonNodeFactory.instance.objectNode();
item.put("name", name);
item.put("credentialProviderArn", credentialProviderArn(region, name));
item.put("apiKeySecretSource", source);
if (source.equals("EXTERNAL")) {
String secretId = secretConfig.path("secretId").asText();
String jsonKey = secretConfig.path("jsonKey").asText();
item.putObject("apiKeySecretArn").put("secretArn", secretId);
item.put("apiKeySecretJsonKey", jsonKey);
} else {
item.putObject("apiKeySecretArn").put("secretArn", managedSecretArn(region, name));
item.put("apiKeySecretJsonKey", "apiKey");
}
item.put("createdTime", now.getEpochSecond());
item.put("lastUpdatedTime", now.getEpochSecond());
if (request.has("tags")) {
item.set("tags", request.get("tags").deepCopy());
}
storage.put(key, item);
return item.deepCopy();
}
public ObjectNode getApiKey(String name, String region) {
validateName(name);
return storage.get(key("apikey", region, name))
.map(ObjectNode::deepCopy)
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
"API key credential provider not found: " + name, 404));
}
public PaginatedResult<ObjectNode> listApiKeys(Integer maxResults, String nextToken, String region) {
List<ObjectNode> items = storage.scan(k -> k.startsWith(prefix("apikey", region))).stream()
.map(ObjectNode::deepCopy)
.toList();
return Pagination.paginate(items, node -> node.path("name").asText(),
maxResults, nextToken, 100, 100, "ValidationException");
}
public ObjectNode updateApiKey(ObjectNode request, String region) {
String name = requiredName(request);
ObjectNode item = getApiKey(name, region);
String apiKey = text(request, "apiKey");
if (apiKey != null && apiKey.length() > 65536) {
throw new AwsException("ValidationException", "apiKey exceeds maximum length of 65536", 400);
}
String source = text(request, "apiKeySecretSource");
JsonNode secretConfig = request.get("apiKeySecretConfig");
if (source != null) {
if (!source.equals("MANAGED") && !source.equals("EXTERNAL")) {
throw new AwsException("ValidationException", "apiKeySecretSource must be MANAGED or EXTERNAL", 400);
}
item.put("apiKeySecretSource", source);
} else {
source = item.path("apiKeySecretSource").asText("MANAGED");
}
if (source.equals("EXTERNAL")) {
if (secretConfig == null || !secretConfig.isObject()
|| !secretConfig.hasNonNull("secretId") || !secretConfig.hasNonNull("jsonKey")) {
throw new AwsException("ValidationException",
"apiKeySecretConfig with secretId and jsonKey is required for EXTERNAL source", 400);
}
}
if (secretConfig != null && secretConfig.isObject()) {
String secretId = secretConfig.path("secretId").asText();
String jsonKey = secretConfig.path("jsonKey").asText();
if (secretId.length() < 1 || secretId.length() > 2048) {
throw new AwsException("ValidationException", "secretId must be between 1 and 2048 characters", 400);
}
if (jsonKey.length() < 1 || jsonKey.length() > 128) {
throw new AwsException("ValidationException", "jsonKey must be between 1 and 128 characters", 400);
}
item.putObject("apiKeySecretArn").put("secretArn", secretId);
item.put("apiKeySecretJsonKey", jsonKey);
} else if (source.equals("MANAGED")) {
item.putObject("apiKeySecretArn").put("secretArn", managedSecretArn(region, name));
item.put("apiKeySecretJsonKey", "apiKey");
}
item.put("lastUpdatedTime", Instant.now().getEpochSecond());
storage.put(key("apikey", region, name), item);
return item.deepCopy();
}
public void deleteApiKey(String name, String region) {
getApiKey(name, region);
storage.delete(key("apikey", region, name));
}
public ObjectNode createOauth2(ObjectNode request, String region) {
String name = requiredName(request);
String key = key("oauth2", region, name);
if (storage.get(key).isPresent()) {
throw new AwsException("ConflictException", "OAuth2 credential provider already exists: " + name, 409);
}
String vendor = text(request, "credentialProviderVendor");
validateOauthVendor(vendor);
JsonNode configInput = request.get("oauth2ProviderConfigInput");
if (configInput == null || !configInput.isObject() || configInput.size() != 1) {
throw new AwsException("ValidationException",
"oauth2ProviderConfigInput must contain exactly one provider configuration", 400);
}
Map.Entry<String, JsonNode> configEntry = configInput.fields().next();
if (!configEntry.getKey().equals(expectedOauthConfigKey(vendor))) {
throw new AwsException("ValidationException",
"oauth2ProviderConfigInput does not match credentialProviderVendor", 400);
}
if (!configEntry.getValue().isObject()) {
throw new AwsException("ValidationException", "OAuth2 provider configuration must be an object", 400);
}
ObjectNode config = ((ObjectNode) configEntry.getValue()).deepCopy();
validateOauthProviderConfig(vendor, config);
String source = text(config, "clientSecretSource");
if (source == null) {
source = "MANAGED";
}
if (!source.equals("MANAGED") && !source.equals("EXTERNAL")) {
throw new AwsException("ValidationException", "clientSecretSource must be MANAGED or EXTERNAL", 400);
}
JsonNode secretConfig = config.get("clientSecretConfig");
if (source.equals("EXTERNAL")) {
validateSecretReference(secretConfig, "clientSecretConfig");
}
String clientSecret = text(config, "clientSecret");
if (clientSecret != null && clientSecret.length() > 2048) {
throw new AwsException("ValidationException", "clientSecret exceeds maximum length of 2048", 400);
}
validateTags(request.get("tags"));
Instant now = Instant.now();
ObjectNode item = JsonNodeFactory.instance.objectNode();
item.put("name", name);
item.put("credentialProviderArn", oauthCredentialProviderArn(region, name));
item.put("credentialProviderVendor", vendor);
item.put("callbackUrl", "https://bedrock-agentcore." + region + ".amazonaws.com/oauth2/callback");
item.put("clientSecretSource", source);
if (source.equals("EXTERNAL")) {
item.putObject("clientSecretArn").put("secretArn", secretConfig.path("secretId").asText());
item.put("clientSecretJsonKey", secretConfig.path("jsonKey").asText());
} else {
item.putObject("clientSecretArn").put("secretArn", managedOauthSecretArn(region, name));
item.put("clientSecretJsonKey", "clientSecret");
}
ObjectNode outputUnion = item.putObject("oauth2ProviderConfigOutput");
outputUnion.set(configEntry.getKey(), oauthOutputConfig(vendor, config));
item.put("status", "READY");
item.put("createdTime", now.getEpochSecond());
item.put("lastUpdatedTime", now.getEpochSecond());
if (request.has("tags")) {
item.set("tags", request.get("tags").deepCopy());
}
storage.put(key, item);
return item.deepCopy();
}
public ObjectNode getOauth2(String name, String region) {
validateName(name);
return storage.get(key("oauth2", region, name))
.map(ObjectNode::deepCopy)
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
"OAuth2 credential provider not found: " + name, 404));
}
public PaginatedResult<ObjectNode> listOauth2(Integer maxResults, String nextToken, String region) {
List<ObjectNode> items = storage.scan(k -> k.startsWith(prefix("oauth2", region))).stream()
.map(ObjectNode::deepCopy)
.toList();
return Pagination.paginate(items, node -> node.path("name").asText(),
maxResults, nextToken, 20, 20, "ValidationException");
}
public ObjectNode updateOauth2(ObjectNode request, String region) {
String name = requiredName(request);
ObjectNode item = getOauth2(name, region);
String vendor = text(request, "credentialProviderVendor");
validateOauthVendor(vendor);
JsonNode configInput = request.get("oauth2ProviderConfigInput");
if (configInput == null || !configInput.isObject() || configInput.size() != 1) {
throw new AwsException("ValidationException",
"oauth2ProviderConfigInput must contain exactly one provider configuration", 400);
}
Map.Entry<String, JsonNode> configEntry = configInput.fields().next();
if (!configEntry.getKey().equals(expectedOauthConfigKey(vendor)) || !configEntry.getValue().isObject()) {
throw new AwsException("ValidationException",
"oauth2ProviderConfigInput does not match credentialProviderVendor", 400);
}
ObjectNode config = ((ObjectNode) configEntry.getValue()).deepCopy();
validateOauthProviderConfig(vendor, config);
String source = text(config, "clientSecretSource");
if (source == null) {
source = item.path("clientSecretSource").asText("MANAGED");
}
if (!source.equals("MANAGED") && !source.equals("EXTERNAL")) {
throw new AwsException("ValidationException", "clientSecretSource must be MANAGED or EXTERNAL", 400);
}
JsonNode secretConfig = config.get("clientSecretConfig");
if (source.equals("EXTERNAL")) {
validateSecretReference(secretConfig, "clientSecretConfig");
}
String clientSecret = text(config, "clientSecret");
if (clientSecret != null && clientSecret.length() > 2048) {
throw new AwsException("ValidationException", "clientSecret exceeds maximum length of 2048", 400);
}
item.put("credentialProviderVendor", vendor);
item.put("clientSecretSource", source);
if (source.equals("EXTERNAL")) {
item.putObject("clientSecretArn").put("secretArn", secretConfig.path("secretId").asText());
item.put("clientSecretJsonKey", secretConfig.path("jsonKey").asText());
} else {
item.putObject("clientSecretArn").put("secretArn", managedOauthSecretArn(region, name));
item.put("clientSecretJsonKey", "clientSecret");
}
ObjectNode outputUnion = JsonNodeFactory.instance.objectNode();
outputUnion.set(configEntry.getKey(), oauthOutputConfig(vendor, config));
item.set("oauth2ProviderConfigOutput", outputUnion);
item.put("status", "READY");
item.put("lastUpdatedTime", Instant.now().getEpochSecond());
storage.put(key("oauth2", region, name), item);
return item.deepCopy();
}
public void deleteOauth2(String name, String region) {
getOauth2(name, region);
storage.delete(key("oauth2", region, name));
}
private String credentialProviderArn(String region, String name) {
return "arn:aws:acps:" + region + ":" + regionResolver.getAccountId()
+ ":token-vault/default/apikeycredentialprovider/" + name;
}
private String managedSecretArn(String region, String name) {
return "arn:aws:secretsmanager:" + region + ":" + regionResolver.getAccountId()
+ ":secret:agentcore-" + name;
}
private String oauthCredentialProviderArn(String region, String name) {
return "arn:aws:acps:" + region + ":" + regionResolver.getAccountId()
+ ":token-vault/default/oauth2credentialprovider/" + name;
}
private String managedOauthSecretArn(String region, String name) {
return "arn:aws:secretsmanager:" + region + ":" + regionResolver.getAccountId()
+ ":secret:agentcore-oauth2-" + name;
}
private static ObjectNode oauthOutputConfig(String vendor, ObjectNode config) {
ObjectNode output = JsonNodeFactory.instance.objectNode();
if (config.hasNonNull("clientId")) {
output.put("clientId", config.get("clientId").asText());
}
if ("CustomOauth2".equals(vendor)) {
if (config.has("oauthDiscovery")) {
output.set("oauthDiscovery", config.get("oauthDiscovery").deepCopy());
}
for (String field : List.of("clientAuthenticationMethod", "onBehalfOfTokenExchangeConfig",
"privateEndpoint", "privateEndpointOverrides", "privateKeyJwtConfig")) {
if (config.has(field)) {
output.set(field, config.get(field).deepCopy());
}
}
} else {
output.set("oauthDiscovery", syntheticOauthDiscovery(vendor));
}
return output;
}
private static ObjectNode syntheticOauthDiscovery(String vendor) {
ObjectNode discovery = JsonNodeFactory.instance.objectNode();
ObjectNode metadata = discovery.putObject("authorizationServerMetadata");
String slug = vendor.replace("Oauth2", "").toLowerCase();
metadata.put("issuer", "https://" + slug + ".oauth.local");
metadata.put("authorizationEndpoint", "https://" + slug + ".oauth.local/authorize");
metadata.put("tokenEndpoint", "https://" + slug + ".oauth.local/token");
return discovery;
}
private static void validateOauthVendor(String vendor) {
if (vendor == null || !java.util.Set.of(
"GoogleOauth2", "GithubOauth2", "SlackOauth2", "SalesforceOauth2", "MicrosoftOauth2",
"CustomOauth2", "AtlassianOauth2", "LinkedinOauth2", "XOauth2", "OktaOauth2",
"OneLoginOauth2", "PingOneOauth2", "FacebookOauth2", "YandexOauth2", "RedditOauth2",
"ZoomOauth2", "TwitchOauth2", "SpotifyOauth2", "DropboxOauth2", "NotionOauth2",
"HubspotOauth2", "CyberArkOauth2", "FusionAuthOauth2", "Auth0Oauth2", "CognitoOauth2")
.contains(vendor)) {
throw new AwsException("ValidationException", "credentialProviderVendor is invalid", 400);
}
}
private static String expectedOauthConfigKey(String vendor) {
return switch (vendor) {
case "GoogleOauth2" -> "googleOauth2ProviderConfig";
case "GithubOauth2" -> "githubOauth2ProviderConfig";
case "SlackOauth2" -> "slackOauth2ProviderConfig";
case "SalesforceOauth2" -> "salesforceOauth2ProviderConfig";
case "MicrosoftOauth2" -> "microsoftOauth2ProviderConfig";
case "CustomOauth2" -> "customOauth2ProviderConfig";
case "AtlassianOauth2" -> "atlassianOauth2ProviderConfig";
case "LinkedinOauth2" -> "linkedinOauth2ProviderConfig";
default -> "includedOauth2ProviderConfig";
};
}
private static void validateOauthProviderConfig(String vendor, ObjectNode config) {
if ("CustomOauth2".equals(vendor)) {
JsonNode discovery = config.get("oauthDiscovery");
if (discovery == null || !discovery.isObject() || discovery.size() != 1) {
throw new AwsException("ValidationException",
"custom OAuth2 configuration requires exactly one oauthDiscovery member", 400);
}
if (discovery.has("discoveryUrl")) {
String discoveryUrl = discovery.path("discoveryUrl").asText();
if (!discoveryUrl.matches(".+/\\.well-known/(openid-configuration|oauth-authorization-server)")) {
throw new AwsException("ValidationException", "oauthDiscovery.discoveryUrl is invalid", 400);
}
} else if (discovery.has("authorizationServerMetadata")) {
JsonNode metadata = discovery.get("authorizationServerMetadata");
if (metadata == null || !metadata.isObject()
|| !metadata.hasNonNull("issuer")
|| !metadata.hasNonNull("authorizationEndpoint")
|| !metadata.hasNonNull("tokenEndpoint")) {
throw new AwsException("ValidationException",
"authorizationServerMetadata requires issuer, authorizationEndpoint, and tokenEndpoint", 400);
}
} else {
throw new AwsException("ValidationException", "oauthDiscovery union member is invalid", 400);
}
} else {
String clientId = text(config, "clientId");
if (clientId == null || clientId.length() < 1 || clientId.length() > 256) {
throw new AwsException("ValidationException", "clientId must be between 1 and 256 characters", 400);
}
}
String clientId = text(config, "clientId");
if (clientId != null && clientId.length() > 256) {
throw new AwsException("ValidationException", "clientId must not exceed 256 characters", 400);
}
}
private static void validateSecretReference(JsonNode secretConfig, String fieldName) {
if (secretConfig == null || !secretConfig.isObject()
|| !secretConfig.hasNonNull("secretId") || !secretConfig.hasNonNull("jsonKey")) {
throw new AwsException("ValidationException",
fieldName + " with secretId and jsonKey is required", 400);
}
String secretId = secretConfig.path("secretId").asText();
String jsonKey = secretConfig.path("jsonKey").asText();
if (secretId.length() < 1 || secretId.length() > 2048) {
throw new AwsException("ValidationException", "secretId must be between 1 and 2048 characters", 400);
}
if (jsonKey.length() < 1 || jsonKey.length() > 128) {
throw new AwsException("ValidationException", "jsonKey must be between 1 and 128 characters", 400);
}
}
private static String requiredName(ObjectNode request) {
String name = text(request, "name");
validateName(name);
return name;
}
private static void validateName(String name) {
if (name == null || name.length() < 1 || name.length() > 128 || !name.matches("[a-zA-Z0-9\\-_]+")) {
throw new AwsException("ValidationException", "name must match [a-zA-Z0-9\\-_]+ and be 1-128 characters", 400);
}
}
private static void validateTags(JsonNode tags) {
if (tags == null || tags.isNull()) {
return;
}
if (!tags.isObject() || tags.size() > 50) {
throw new AwsException("ValidationException", "tags must be an object with at most 50 entries", 400);
}
tags.fields().forEachRemaining(entry -> {
String key = entry.getKey();
JsonNode rawValue = entry.getValue();
if (key.length() < 1 || key.length() > 128 || !key.matches("[a-zA-Z0-9\\s._:/=+@-]*")) {
throw new AwsException("ValidationException", "tag key does not satisfy AgentCore constraints", 400);
}
if (!rawValue.isTextual()) {
throw new AwsException("ValidationException", "tag value must be a string", 400);
}
String value = rawValue.asText();
if (value.length() > 256 || !value.matches("[a-zA-Z0-9\\s._:/=+@-]*")) {
throw new AwsException("ValidationException", "tag value does not satisfy AgentCore constraints", 400);
}
});
}
private static String text(JsonNode node, String field) {
JsonNode value = node.get(field);
return value == null || value.isNull() ? null : value.asText();
}
private static String key(String type, String region, String name) {
return prefix(type, region) + name;
}
private static String prefix(String type, String region) {
return "credential-provider:" + type + ":" + region + ":";
}
}
@@ -0,0 +1,156 @@
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.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsErrorResponse;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.Pagination;
import io.github.hectorvent.floci.core.common.RegionResolver;
import jakarta.inject.Inject;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.DELETE;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.PATCH;
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;
@Path("/gateways")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class BedrockAgentCoreGatewayRuleController {
private static final Logger LOG = Logger.getLogger(BedrockAgentCoreGatewayRuleController.class);
private final BedrockAgentCoreGatewayRuleService service;
private final RegionResolver regionResolver;
private final ObjectMapper objectMapper;
@Inject
public BedrockAgentCoreGatewayRuleController(BedrockAgentCoreGatewayRuleService service,
RegionResolver regionResolver,
ObjectMapper objectMapper) {
this.service = service;
this.regionResolver = regionResolver;
this.objectMapper = objectMapper;
}
@POST
@Path("/{gatewayIdentifier}/rules")
public Response createGatewayRule(@Context HttpHeaders headers,
@PathParam("gatewayIdentifier") String gatewayId,
String body) {
String region = regionResolver.resolveRegion(headers);
try {
ObjectNode rule = service.create(gatewayId, object(body), region);
ObjectNode response = rule.deepCopy();
response.remove("clientToken");
response.remove("updatedAt");
return Response.status(202).entity(response).build();
} catch (Exception e) {
return error(e, "creating gateway rule");
}
}
@GET
@Path("/{gatewayIdentifier}/rules/{ruleId}")
public Response getGatewayRule(@Context HttpHeaders headers,
@PathParam("gatewayIdentifier") String gatewayId,
@PathParam("ruleId") String ruleId) {
String region = regionResolver.resolveRegion(headers);
try {
ObjectNode response = service.get(gatewayId, ruleId, region).deepCopy();
response.remove("clientToken");
return Response.ok(response).build();
} catch (Exception e) {
return error(e, "getting gateway rule");
}
}
@GET
@Path("/{gatewayIdentifier}/rules")
public Response listGatewayRules(@Context HttpHeaders headers,
@PathParam("gatewayIdentifier") String gatewayId,
@QueryParam("maxResults") String maxResultsParam,
@QueryParam("nextToken") String nextToken) {
String region = regionResolver.resolveRegion(headers);
try {
Integer maxResults = Pagination.parseMaxResults(maxResultsParam, "ValidationException");
var result = service.list(gatewayId, maxResults, nextToken, region);
ObjectNode response = objectMapper.createObjectNode();
var rules = response.putArray("gatewayRules");
for (ObjectNode rule : result.items()) {
ObjectNode copy = rule.deepCopy();
copy.remove("clientToken");
rules.add(copy);
}
if (result.nextToken() != null) {
response.put("nextToken", result.nextToken());
}
return Response.ok(response).build();
} catch (Exception e) {
return error(e, "listing gateway rules");
}
}
@PATCH
@Path("/{gatewayIdentifier}/rules/{ruleId}")
public Response updateGatewayRule(@Context HttpHeaders headers,
@PathParam("gatewayIdentifier") String gatewayId,
@PathParam("ruleId") String ruleId,
String body) {
String region = regionResolver.resolveRegion(headers);
try {
ObjectNode response = service.update(gatewayId, ruleId, object(body), region);
response.remove("clientToken");
return Response.status(202).entity(response).build();
} catch (Exception e) {
return error(e, "updating gateway rule");
}
}
@DELETE
@Path("/{gatewayIdentifier}/rules/{ruleId}")
public Response deleteGatewayRule(@Context HttpHeaders headers,
@PathParam("gatewayIdentifier") String gatewayId,
@PathParam("ruleId") String ruleId) {
String region = regionResolver.resolveRegion(headers);
try {
return Response.status(202).entity(service.delete(gatewayId, ruleId, region)).build();
} catch (Exception e) {
return error(e, "deleting gateway rule");
}
}
private ObjectNode object(String body) throws Exception {
JsonNode request = objectMapper.readTree(body != null && !body.isBlank() ? body : "{}");
if (!request.isObject()) {
throw new AwsException("ValidationException", "request body must be a JSON object", 400);
}
return (ObjectNode) request;
}
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,328 @@
package io.github.hectorvent.floci.services.bedrockagentcorecontrol;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.Pagination;
import io.github.hectorvent.floci.core.common.PaginatedResult;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.UUID;
@ApplicationScoped
public class BedrockAgentCoreGatewayRuleService {
private final StorageBackend<String, ObjectNode> storage;
private final BedrockAgentCoreGatewayService gatewayService;
@Inject
public BedrockAgentCoreGatewayRuleService(StorageFactory storageFactory,
BedrockAgentCoreGatewayService gatewayService) {
this(storageFactory.create("bedrockagentcore", "bedrock-agentcore-gateway-rules.json",
new TypeReference<Map<String, ObjectNode>>() {}), gatewayService);
}
BedrockAgentCoreGatewayRuleService(StorageBackend<String, ObjectNode> storage,
BedrockAgentCoreGatewayService gatewayService) {
this.storage = storage;
this.gatewayService = gatewayService;
}
public ObjectNode create(String gatewayId, ObjectNode request, String region) {
var gateway = gatewayService.get(gatewayId, region);
String clientToken = request.hasNonNull("clientToken") ? request.get("clientToken").asText() : null;
if (clientToken != null) {
if (clientToken.length() < 33 || clientToken.length() > 256
|| !clientToken.matches("[a-zA-Z0-9](-*[a-zA-Z0-9]){0,256}")) {
throw new AwsException("ValidationException",
"clientToken does not satisfy length or pattern constraints", 400);
}
ObjectNode existing = storage.scan(k -> k.startsWith(prefix(region, gatewayId))).stream()
.filter(rule -> clientToken.equals(rule.path("clientToken").asText(null)))
.findFirst()
.orElse(null);
if (existing != null) {
return existing.deepCopy();
}
}
JsonNode actions = request.get("actions");
if (actions == null || !actions.isArray() || actions.isEmpty() || actions.size() > 2) {
throw new AwsException("ValidationException", "actions must contain between 1 and 2 items", 400);
}
validateActions(actions);
if (!request.hasNonNull("priority") || !request.get("priority").canConvertToInt()) {
throw new AwsException("ValidationException", "priority is required", 400);
}
int priority = request.get("priority").asInt();
if (priority < 1 || priority > 1_000_000) {
throw new AwsException("ValidationException", "priority must be between 1 and 1000000", 400);
}
JsonNode conditions = request.get("conditions");
if (conditions != null && (!conditions.isArray() || conditions.size() > 2)) {
throw new AwsException("ValidationException", "conditions must contain at most 2 items", 400);
}
if (conditions != null) {
validateConditions(conditions);
}
String ruleId = UUID.randomUUID().toString();
Instant now = Instant.now();
ObjectNode rule = request.deepCopy();
rule.put("ruleId", ruleId);
rule.put("gatewayArn", gatewayService.gatewayArn(gateway, region));
rule.put("status", "ACTIVE");
rule.put("createdAt", now.toString());
rule.put("updatedAt", now.toString());
storage.put(key(region, gatewayId, ruleId), rule);
return rule.deepCopy();
}
public ObjectNode get(String gatewayId, String ruleId, String region) {
gatewayService.get(gatewayId, region);
if (ruleId == null || !ruleId.matches("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")) {
throw new AwsException("ValidationException", "ruleId does not satisfy the required UUID pattern", 400);
}
return storage.get(key(region, gatewayId, ruleId))
.map(ObjectNode::deepCopy)
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
"Gateway rule not found: " + ruleId, 404));
}
public PaginatedResult<ObjectNode> list(String gatewayId, Integer maxResults,
String nextToken, String region) {
gatewayService.get(gatewayId, region);
List<ObjectNode> rules = storage.scan(k -> k.startsWith(prefix(region, gatewayId))).stream()
.map(ObjectNode::deepCopy)
.toList();
return Pagination.paginate(rules, node -> node.path("ruleId").asText(),
maxResults, nextToken, 100, 100, "ValidationException");
}
public ObjectNode update(String gatewayId, String ruleId, ObjectNode request, String region) {
ObjectNode rule = get(gatewayId, ruleId, region);
if (request.has("actions")) {
JsonNode actions = request.get("actions");
if (actions == null || !actions.isArray() || actions.isEmpty() || actions.size() > 2) {
throw new AwsException("ValidationException", "actions must contain between 1 and 2 items", 400);
}
validateActions(actions);
rule.set("actions", actions.deepCopy());
}
if (request.has("conditions")) {
JsonNode conditions = request.get("conditions");
if (conditions == null || !conditions.isArray() || conditions.size() > 2) {
throw new AwsException("ValidationException", "conditions must contain at most 2 items", 400);
}
validateConditions(conditions);
rule.set("conditions", conditions.deepCopy());
}
if (request.hasNonNull("description")) {
String description = request.get("description").asText();
if (description.length() < 1 || description.length() > 256) {
throw new AwsException("ValidationException", "description must be between 1 and 256 characters", 400);
}
rule.put("description", description);
}
if (request.has("priority")) {
if (!request.hasNonNull("priority") || !request.get("priority").canConvertToInt()) {
throw new AwsException("ValidationException", "priority must be an integer", 400);
}
int priority = request.get("priority").asInt();
if (priority < 1 || priority > 1_000_000) {
throw new AwsException("ValidationException", "priority must be between 1 and 1000000", 400);
}
rule.put("priority", priority);
}
rule.put("status", "ACTIVE");
rule.put("updatedAt", Instant.now().toString());
storage.put(key(region, gatewayId, ruleId), rule);
return rule.deepCopy();
}
public ObjectNode delete(String gatewayId, String ruleId, String region) {
ObjectNode rule = get(gatewayId, ruleId, region);
storage.delete(key(region, gatewayId, ruleId));
ObjectNode response = rule.objectNode();
response.put("ruleId", ruleId);
response.put("status", "DELETING");
return response;
}
private static void validateActions(JsonNode actions) {
for (JsonNode action : actions) {
if (!action.isObject() || action.size() != 1) {
throw new AwsException("ValidationException", "each action must contain exactly one union member", 400);
}
if (action.has("routeToTarget")) {
validateRouteToTarget(action.get("routeToTarget"));
} else if (action.has("configurationBundle")) {
validateConfigurationBundleAction(action.get("configurationBundle"));
} else {
throw new AwsException("ValidationException", "action union member is invalid", 400);
}
}
}
private static void validateRouteToTarget(JsonNode route) {
if (route == null || !route.isObject() || route.size() != 1) {
throw new AwsException("ValidationException", "routeToTarget must contain exactly one union member", 400);
}
if (route.has("staticRoute")) {
String targetName = requiredText(route.get("staticRoute"), "targetName", "staticRoute.targetName");
if (!targetName.matches("([0-9a-zA-Z][-]?){1,100}")) {
throw new AwsException("ValidationException", "staticRoute.targetName is invalid", 400);
}
return;
}
if (route.has("weightedRoute")) {
validateTargetTrafficSplit(route.path("weightedRoute").get("trafficSplit"));
return;
}
throw new AwsException("ValidationException", "routeToTarget union member is invalid", 400);
}
private static void validateTargetTrafficSplit(JsonNode split) {
if (split == null || !split.isArray() || split.size() != 2) {
throw new AwsException("ValidationException", "weightedRoute.trafficSplit must contain exactly 2 items", 400);
}
for (JsonNode entry : split) {
String name = requiredText(entry, "name", "trafficSplit.name");
String targetName = requiredText(entry, "targetName", "trafficSplit.targetName");
if (!name.matches("[a-zA-Z0-9]([a-zA-Z0-9-]{0,62}[a-zA-Z0-9])?")) {
throw new AwsException("ValidationException", "trafficSplit.name is invalid", 400);
}
if (!targetName.matches("([0-9a-zA-Z][-]?){1,100}")) {
throw new AwsException("ValidationException", "trafficSplit.targetName is invalid", 400);
}
int weight = requiredInt(entry, "weight", "trafficSplit.weight");
if (weight < 1 || weight > 99) {
throw new AwsException("ValidationException", "trafficSplit.weight must be between 1 and 99", 400);
}
}
}
private static void validateConfigurationBundleAction(JsonNode action) {
if (action == null || !action.isObject() || action.size() != 1) {
throw new AwsException("ValidationException", "configurationBundle must contain exactly one union member", 400);
}
if (action.has("staticOverride")) {
validateBundleReference(action.get("staticOverride"), "staticOverride");
return;
}
if (action.has("weightedOverride")) {
JsonNode split = action.path("weightedOverride").get("trafficSplit");
if (split == null || !split.isArray() || split.size() != 2) {
throw new AwsException("ValidationException", "weightedOverride.trafficSplit must contain exactly 2 items", 400);
}
int total = 0;
for (JsonNode entry : split) {
String name = requiredText(entry, "name", "trafficSplit.name");
if (!name.matches("[a-zA-Z0-9]([a-zA-Z0-9-]{0,62}[a-zA-Z0-9])?")) {
throw new AwsException("ValidationException", "trafficSplit.name is invalid", 400);
}
int weight = requiredInt(entry, "weight", "trafficSplit.weight");
if (weight < 1 || weight > 99) {
throw new AwsException("ValidationException", "trafficSplit.weight must be between 1 and 99", 400);
}
validateBundleReference(entry.get("configurationBundle"), "trafficSplit.configurationBundle");
total += weight;
}
if (total != 100) {
throw new AwsException("ValidationException", "trafficSplit weights must sum to 100", 400);
}
return;
}
throw new AwsException("ValidationException", "configurationBundle union member is invalid", 400);
}
private static void validateBundleReference(JsonNode reference, String field) {
if (reference == null || !reference.isObject()) {
throw new AwsException("ValidationException", field + " is required", 400);
}
String arn = requiredText(reference, "bundleArn", field + ".bundleArn");
String version = requiredText(reference, "bundleVersion", field + ".bundleVersion");
if (!arn.matches("arn:aws[a-zA-Z-]*:bedrock-agentcore:[a-z0-9-]+:[0-9]{12}:configuration-bundle/[a-zA-Z][a-zA-Z0-9-_]{0,99}-[a-zA-Z0-9]{10}")) {
throw new AwsException("ValidationException", field + ".bundleArn is invalid", 400);
}
if (!version.matches("[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}")) {
throw new AwsException("ValidationException", field + ".bundleVersion is invalid", 400);
}
}
private static void validateConditions(JsonNode conditions) {
for (JsonNode condition : conditions) {
if (!condition.isObject() || condition.size() != 1) {
throw new AwsException("ValidationException", "each condition must contain exactly one union member", 400);
}
if (condition.has("matchPaths")) {
JsonNode anyOf = condition.path("matchPaths").get("anyOf");
if (anyOf == null || !anyOf.isArray() || anyOf.isEmpty() || anyOf.size() > 10) {
throw new AwsException("ValidationException", "matchPaths.anyOf must contain between 1 and 10 items", 400);
}
for (JsonNode path : anyOf) {
if (!path.isTextual() || path.asText().length() > 512
|| !path.asText().matches("/[\\w\\-.]+/\\*")) {
throw new AwsException("ValidationException", "matchPaths.anyOf contains an invalid path", 400);
}
}
} else if (condition.has("matchPrincipals")) {
validatePrincipals(condition.get("matchPrincipals"));
} else {
throw new AwsException("ValidationException", "condition union member is invalid", 400);
}
}
}
private static void validatePrincipals(JsonNode matchPrincipals) {
JsonNode anyOf = matchPrincipals == null ? null : matchPrincipals.get("anyOf");
if (anyOf == null || !anyOf.isArray() || anyOf.isEmpty() || anyOf.size() > 100) {
throw new AwsException("ValidationException", "matchPrincipals.anyOf must contain between 1 and 100 items", 400);
}
for (JsonNode entry : anyOf) {
if (!entry.isObject() || entry.size() != 1 || !entry.has("iamPrincipal")) {
throw new AwsException("ValidationException", "principal entry must contain iamPrincipal", 400);
}
JsonNode principal = entry.get("iamPrincipal");
String arn = requiredText(principal, "arn", "iamPrincipal.arn");
if (arn.length() > 2048 || !arn.matches("(arn:aws[a-zA-Z-]*:iam::(\\d{12}|\\*):(user|role)/[\\w+=,.@*?/-]+|arn:aws[a-zA-Z-]*:sts::(\\d{12}|\\*):assumed-role/[\\w+=,.@*?/-]+)")) {
throw new AwsException("ValidationException", "iamPrincipal.arn is invalid", 400);
}
if (principal.hasNonNull("operator")) {
String operator = principal.get("operator").asText();
if (!"StringEquals".equals(operator) && !"StringLike".equals(operator)) {
throw new AwsException("ValidationException", "iamPrincipal.operator is invalid", 400);
}
}
}
}
private static String requiredText(JsonNode node, String field, String displayName) {
JsonNode value = node == null ? null : node.get(field);
if (value == null || !value.isTextual() || value.asText().isEmpty()) {
throw new AwsException("ValidationException", displayName + " is required", 400);
}
return value.asText();
}
private static int requiredInt(JsonNode node, String field, String displayName) {
JsonNode value = node == null ? null : node.get(field);
if (value == null || !value.isIntegralNumber() || !value.canConvertToInt()) {
throw new AwsException("ValidationException", displayName + " is required", 400);
}
return value.asInt();
}
private static String key(String region, String gatewayId, String ruleId) {
return prefix(region, gatewayId) + ruleId;
}
private static String prefix(String region, String gatewayId) {
return "gateway-rule:" + region + ":" + gatewayId + ":";
}
}
@@ -37,14 +37,17 @@ public class BedrockAgentCoreIdentityController {
private static final Logger LOG = Logger.getLogger(BedrockAgentCoreIdentityController.class);
private final BedrockAgentCoreIdentityService service;
private final BedrockAgentCoreCredentialProviderService credentialProviderService;
private final RegionResolver regionResolver;
private final ObjectMapper objectMapper;
@Inject
public BedrockAgentCoreIdentityController(BedrockAgentCoreIdentityService service,
BedrockAgentCoreCredentialProviderService credentialProviderService,
RegionResolver regionResolver,
ObjectMapper objectMapper) {
this.service = service;
this.credentialProviderService = credentialProviderService;
this.regionResolver = regionResolver;
this.objectMapper = objectMapper;
}
@@ -128,6 +131,169 @@ public class BedrockAgentCoreIdentityController {
}
}
@POST
@Path("/CreateApiKeyCredentialProvider")
public Response createApiKeyCredentialProvider(@Context HttpHeaders headers, String body) {
String region = regionResolver.resolveRegion(headers);
try {
ObjectNode item = credentialProviderService.createApiKey(object(body), region);
ObjectNode out = item.deepCopy();
out.remove(List.of("createdTime", "lastUpdatedTime", "tags"));
return Response.status(201).entity(out).build();
} catch (Exception e) {
return error(e, "creating API key credential provider");
}
}
@POST
@Path("/GetApiKeyCredentialProvider")
public Response getApiKeyCredentialProvider(@Context HttpHeaders headers, String body) {
String region = regionResolver.resolveRegion(headers);
try {
ObjectNode req = object(body);
ObjectNode out = credentialProviderService.getApiKey(text(req, "name"), region);
out.remove("tags");
return Response.ok(out).build();
} catch (Exception e) {
return error(e, "getting API key credential provider");
}
}
@POST
@Path("/ListApiKeyCredentialProviders")
public Response listApiKeyCredentialProviders(@Context HttpHeaders headers, String body) {
String region = regionResolver.resolveRegion(headers);
try {
ObjectNode req = object(body);
Integer maxResults = req.hasNonNull("maxResults") ? req.get("maxResults").asInt() : null;
String nextToken = text(req, "nextToken");
PaginatedResult<ObjectNode> result = credentialProviderService.listApiKeys(maxResults, nextToken, region);
ObjectNode out = objectMapper.createObjectNode();
ArrayNode providers = out.putArray("credentialProviders");
for (ObjectNode item : result.items()) {
ObjectNode summary = providers.addObject();
summary.put("name", item.path("name").asText());
summary.put("credentialProviderArn", item.path("credentialProviderArn").asText());
summary.put("createdTime", item.path("createdTime").asLong());
summary.put("lastUpdatedTime", item.path("lastUpdatedTime").asLong());
}
if (result.nextToken() != null) {
out.put("nextToken", result.nextToken());
}
return Response.ok(out).build();
} catch (Exception e) {
return error(e, "listing API key credential providers");
}
}
@POST
@Path("/UpdateApiKeyCredentialProvider")
public Response updateApiKeyCredentialProvider(@Context HttpHeaders headers, String body) {
String region = regionResolver.resolveRegion(headers);
try {
ObjectNode out = credentialProviderService.updateApiKey(object(body), region);
out.remove("tags");
return Response.ok(out).build();
} catch (Exception e) {
return error(e, "updating API key credential provider");
}
}
@POST
@Path("/DeleteApiKeyCredentialProvider")
public Response deleteApiKeyCredentialProvider(@Context HttpHeaders headers, String body) {
String region = regionResolver.resolveRegion(headers);
try {
ObjectNode req = object(body);
credentialProviderService.deleteApiKey(text(req, "name"), region);
return Response.noContent().build();
} catch (Exception e) {
return error(e, "deleting API key credential provider");
}
}
@POST
@Path("/CreateOauth2CredentialProvider")
public Response createOauth2CredentialProvider(@Context HttpHeaders headers, String body) {
String region = regionResolver.resolveRegion(headers);
try {
ObjectNode item = credentialProviderService.createOauth2(object(body), region);
ObjectNode out = item.deepCopy();
out.remove(List.of("createdTime", "lastUpdatedTime", "credentialProviderVendor", "tags"));
return Response.status(201).entity(out).build();
} catch (Exception e) {
return error(e, "creating OAuth2 credential provider");
}
}
@POST
@Path("/GetOauth2CredentialProvider")
public Response getOauth2CredentialProvider(@Context HttpHeaders headers, String body) {
String region = regionResolver.resolveRegion(headers);
try {
ObjectNode req = object(body);
ObjectNode out = credentialProviderService.getOauth2(text(req, "name"), region);
out.remove("tags");
return Response.ok(out).build();
} catch (Exception e) {
return error(e, "getting OAuth2 credential provider");
}
}
@POST
@Path("/ListOauth2CredentialProviders")
public Response listOauth2CredentialProviders(@Context HttpHeaders headers, String body) {
String region = regionResolver.resolveRegion(headers);
try {
ObjectNode req = object(body);
Integer maxResults = req.hasNonNull("maxResults") ? req.get("maxResults").asInt() : null;
String nextToken = text(req, "nextToken");
PaginatedResult<ObjectNode> result = credentialProviderService.listOauth2(maxResults, nextToken, region);
ObjectNode out = objectMapper.createObjectNode();
ArrayNode providers = out.putArray("credentialProviders");
for (ObjectNode item : result.items()) {
ObjectNode summary = providers.addObject();
summary.put("name", item.path("name").asText());
summary.put("credentialProviderArn", item.path("credentialProviderArn").asText());
summary.put("credentialProviderVendor", item.path("credentialProviderVendor").asText());
summary.put("createdTime", item.path("createdTime").asLong());
summary.put("lastUpdatedTime", item.path("lastUpdatedTime").asLong());
}
if (result.nextToken() != null) {
out.put("nextToken", result.nextToken());
}
return Response.ok(out).build();
} catch (Exception e) {
return error(e, "listing OAuth2 credential providers");
}
}
@POST
@Path("/UpdateOauth2CredentialProvider")
public Response updateOauth2CredentialProvider(@Context HttpHeaders headers, String body) {
String region = regionResolver.resolveRegion(headers);
try {
ObjectNode out = credentialProviderService.updateOauth2(object(body), region);
out.remove("tags");
return Response.ok(out).build();
} catch (Exception e) {
return error(e, "updating OAuth2 credential provider");
}
}
@POST
@Path("/DeleteOauth2CredentialProvider")
public Response deleteOauth2CredentialProvider(@Context HttpHeaders headers, String body) {
String region = regionResolver.resolveRegion(headers);
try {
ObjectNode req = object(body);
credentialProviderService.deleteOauth2(text(req, "name"), region);
return Response.noContent().build();
} catch (Exception e) {
return error(e, "deleting OAuth2 credential provider");
}
}
private ObjectNode identityNode(WorkloadIdentity identity, boolean full) {
ObjectNode node = objectMapper.createObjectNode();
node.put("name", identity.getName());
@@ -151,6 +317,14 @@ public class BedrockAgentCoreIdentityController {
}
}
private ObjectNode object(String body) throws Exception {
JsonNode request = objectMapper.readTree(body != null && !body.isBlank() ? body : "{}");
if (!request.isObject()) {
throw new AwsException("ValidationException", "request body must be a JSON object", 400);
}
return (ObjectNode) request;
}
private static String text(JsonNode node, String field) {
JsonNode v = node.get(field);
return (v == null || v.isNull()) ? null : v.asText();
@@ -0,0 +1,91 @@
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.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsErrorResponse;
import io.github.hectorvent.floci.core.common.AwsException;
import jakarta.inject.Inject;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.DELETE;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.PUT;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import org.jboss.logging.Logger;
@Path("/resourcepolicy")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class BedrockAgentCoreResourcePolicyController {
private static final Logger LOG = Logger.getLogger(BedrockAgentCoreResourcePolicyController.class);
private final BedrockAgentCoreResourcePolicyService service;
private final ObjectMapper objectMapper;
@Inject
public BedrockAgentCoreResourcePolicyController(BedrockAgentCoreResourcePolicyService service,
ObjectMapper objectMapper) {
this.service = service;
this.objectMapper = objectMapper;
}
@GET
@Path("/{resourceArn:.+}")
public Response getResourcePolicy(@PathParam("resourceArn") String resourceArn) {
try {
ObjectNode out = objectMapper.createObjectNode();
out.put("policy", service.get(resourceArn));
return Response.ok(out).build();
} catch (Exception e) {
return error(e, "getting resource policy");
}
}
@PUT
@Path("/{resourceArn:.+}")
public Response putResourcePolicy(@PathParam("resourceArn") String resourceArn, String body) {
try {
JsonNode request = objectMapper.readTree(body != null && !body.isBlank() ? body : "{}");
if (!request.isObject() || !request.hasNonNull("policy")) {
throw new AwsException("ValidationException", "policy is required", 400);
}
ObjectNode out = objectMapper.createObjectNode();
out.put("policy", service.put(resourceArn, request.get("policy").asText()));
return Response.status(201).entity(out).build();
} catch (Exception e) {
return error(e, "putting resource policy");
}
}
@DELETE
@Path("/{resourceArn:.+}")
public Response deleteResourcePolicy(@PathParam("resourceArn") String resourceArn) {
try {
service.delete(resourceArn);
return Response.noContent().build();
} catch (Exception e) {
return error(e, "deleting resource policy");
}
}
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,55 @@
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.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.util.Map;
@ApplicationScoped
public class BedrockAgentCoreResourcePolicyService {
private final StorageBackend<String, String> storage;
@Inject
public BedrockAgentCoreResourcePolicyService(StorageFactory storageFactory) {
this(storageFactory.create("bedrockagentcore", "bedrock-agentcore-resource-policies.json",
new TypeReference<Map<String, String>>() {}));
}
BedrockAgentCoreResourcePolicyService(StorageBackend<String, String> storage) {
this.storage = storage;
}
public String get(String resourceArn) {
validateResourceArn(resourceArn);
return storage.get(resourceArn)
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
"Resource policy not found for: " + resourceArn, 404));
}
public String put(String resourceArn, String policy) {
validateResourceArn(resourceArn);
if (policy == null || policy.length() < 1 || policy.length() > 20480) {
throw new AwsException("ValidationException",
"policy must be between 1 and 20480 characters", 400);
}
storage.put(resourceArn, policy);
return policy;
}
public void delete(String resourceArn) {
get(resourceArn);
storage.delete(resourceArn);
}
private static void validateResourceArn(String resourceArn) {
if (resourceArn == null || resourceArn.length() < 20 || resourceArn.length() > 1011) {
throw new AwsException("ValidationException",
"resourceArn must be between 20 and 1011 characters", 400);
}
}
}
@@ -0,0 +1,326 @@
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.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsErrorResponse;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.Pagination;
import io.github.hectorvent.floci.core.common.RegionResolver;
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;
@Path("/")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class BedrockAgentCoreToolsController {
private static final Logger LOG = Logger.getLogger(BedrockAgentCoreToolsController.class);
private final BedrockAgentCoreToolsService service;
private final RegionResolver regionResolver;
private final ObjectMapper objectMapper;
@Inject
public BedrockAgentCoreToolsController(BedrockAgentCoreToolsService service,
RegionResolver regionResolver,
ObjectMapper objectMapper) {
this.service = service;
this.regionResolver = regionResolver;
this.objectMapper = objectMapper;
}
@PUT
@Path("/browsers")
public Response createBrowser(@Context HttpHeaders headers, String body) {
String region = regionResolver.resolveRegion(headers);
try {
ObjectNode request = object(body);
ObjectNode browser = service.createBrowser(request, region);
ObjectNode response = objectMapper.createObjectNode();
response.put("browserArn", browser.path("browserArn").asText());
response.put("browserId", browser.path("browserId").asText());
response.put("createdAt", browser.path("createdAt").asText());
response.put("status", browser.path("status").asText());
return Response.status(202).entity(response).build();
} catch (Exception e) {
return error(e, "creating browser");
}
}
@GET
@Path("/code-interpreters/{codeInterpreterId}")
public Response getCodeInterpreter(@Context HttpHeaders headers,
@PathParam("codeInterpreterId") String codeInterpreterId) {
String region = regionResolver.resolveRegion(headers);
try {
ObjectNode interpreter = service.getCodeInterpreter(codeInterpreterId, region).deepCopy();
interpreter.remove("clientToken");
interpreter.remove("tags");
return Response.ok(interpreter).build();
} catch (Exception e) {
return error(e, "getting code interpreter");
}
}
@DELETE
@Path("/code-interpreters/{codeInterpreterId}")
public Response deleteCodeInterpreter(@Context HttpHeaders headers,
@PathParam("codeInterpreterId") String codeInterpreterId,
@QueryParam("clientToken") String clientToken) {
String region = regionResolver.resolveRegion(headers);
try {
ObjectNode interpreter = service.deleteCodeInterpreter(codeInterpreterId, clientToken, region);
ObjectNode response = objectMapper.createObjectNode();
copyText(interpreter, response, "codeInterpreterId");
copyText(interpreter, response, "lastUpdatedAt");
copyText(interpreter, response, "status");
return Response.status(202).entity(response).build();
} catch (Exception e) {
return error(e, "deleting code interpreter");
}
}
@POST
@Path("/code-interpreters")
public Response listCodeInterpreters(@Context HttpHeaders headers,
@QueryParam("maxResults") String maxResultsParam,
@QueryParam("nextToken") String nextToken,
@QueryParam("type") String type) {
String region = regionResolver.resolveRegion(headers);
try {
Integer maxResults = Pagination.parseMaxResults(maxResultsParam, "ValidationException");
var result = service.listCodeInterpreters(maxResults, nextToken, type, region);
ObjectNode response = objectMapper.createObjectNode();
var summaries = response.putArray("codeInterpreterSummaries");
for (ObjectNode interpreter : result.items()) {
ObjectNode summary = summaries.addObject();
copyText(interpreter, summary, "codeInterpreterArn");
copyText(interpreter, summary, "codeInterpreterId");
copyText(interpreter, summary, "createdAt");
copyText(interpreter, summary, "description");
copyText(interpreter, summary, "lastUpdatedAt");
copyText(interpreter, summary, "name");
copyText(interpreter, summary, "status");
}
if (result.nextToken() != null) {
response.put("nextToken", result.nextToken());
}
return Response.ok(response).build();
} catch (Exception e) {
return error(e, "listing code interpreters");
}
}
@PUT
@Path("/code-interpreters")
public Response createCodeInterpreter(@Context HttpHeaders headers, String body) {
String region = regionResolver.resolveRegion(headers);
try {
ObjectNode interpreter = service.createCodeInterpreter(object(body), region);
ObjectNode response = objectMapper.createObjectNode();
copyText(interpreter, response, "codeInterpreterArn");
copyText(interpreter, response, "codeInterpreterId");
copyText(interpreter, response, "createdAt");
copyText(interpreter, response, "status");
return Response.status(202).entity(response).build();
} catch (Exception e) {
return error(e, "creating code interpreter");
}
}
@PUT
@Path("/browser-profiles")
public Response createBrowserProfile(@Context HttpHeaders headers, String body) {
String region = regionResolver.resolveRegion(headers);
try {
ObjectNode profile = service.createBrowserProfile(object(body), region);
ObjectNode response = objectMapper.createObjectNode();
response.put("createdAt", profile.path("createdAt").asText());
response.put("profileArn", profile.path("profileArn").asText());
response.put("profileId", profile.path("profileId").asText());
response.put("status", profile.path("status").asText());
return Response.ok(response).build();
} catch (Exception e) {
return error(e, "creating browser profile");
}
}
@POST
@Path("/browser-profiles")
public Response listBrowserProfiles(@Context HttpHeaders headers,
@QueryParam("maxResults") String maxResultsParam,
@QueryParam("nextToken") String nextToken,
String body) {
String region = regionResolver.resolveRegion(headers);
try {
Integer maxResults = Pagination.parseMaxResults(maxResultsParam, "ValidationException");
ObjectNode request = object(body);
String name = request.hasNonNull("name") ? request.get("name").asText() : null;
var result = service.listBrowserProfiles(maxResults, nextToken, name, region);
ObjectNode response = objectMapper.createObjectNode();
var summaries = response.putArray("profileSummaries");
for (ObjectNode profile : result.items()) {
ObjectNode summary = summaries.addObject();
copyText(profile, summary, "createdAt");
copyText(profile, summary, "description");
copyText(profile, summary, "lastSavedAt");
copyText(profile, summary, "lastSavedBrowserId");
copyText(profile, summary, "lastSavedBrowserSessionId");
copyText(profile, summary, "lastUpdatedAt");
copyText(profile, summary, "name");
copyText(profile, summary, "profileArn");
copyText(profile, summary, "profileId");
copyText(profile, summary, "status");
}
if (result.nextToken() != null) {
response.put("nextToken", result.nextToken());
}
return Response.ok(response).build();
} catch (Exception e) {
return error(e, "listing browser profiles");
}
}
@DELETE
@Path("/browser-profiles/{profileId}")
public Response deleteBrowserProfile(@Context HttpHeaders headers,
@PathParam("profileId") String profileId,
@QueryParam("clientToken") String clientToken) {
String region = regionResolver.resolveRegion(headers);
try {
ObjectNode profile = service.deleteBrowserProfile(profileId, clientToken, region);
ObjectNode response = objectMapper.createObjectNode();
copyText(profile, response, "lastSavedAt");
copyText(profile, response, "lastUpdatedAt");
copyText(profile, response, "profileArn");
copyText(profile, response, "profileId");
copyText(profile, response, "status");
return Response.ok(response).build();
} catch (Exception e) {
return error(e, "deleting browser profile");
}
}
@GET
@Path("/browser-profiles/{profileId}")
public Response getBrowserProfile(@Context HttpHeaders headers, @PathParam("profileId") String profileId) {
String region = regionResolver.resolveRegion(headers);
try {
ObjectNode profile = service.getBrowserProfile(profileId, region).deepCopy();
profile.remove("clientToken");
profile.remove("tags");
return Response.ok(profile).build();
} catch (Exception e) {
return error(e, "getting browser profile");
}
}
@GET
@Path("/browsers/{browserId}")
public Response getBrowser(@Context HttpHeaders headers, @PathParam("browserId") String browserId) {
String region = regionResolver.resolveRegion(headers);
try {
ObjectNode browser = service.getBrowser(browserId, region);
ObjectNode response = browser.deepCopy();
response.remove("clientToken");
response.remove("tags");
return Response.ok(response).build();
} catch (Exception e) {
return error(e, "getting browser");
}
}
@DELETE
@Path("/browsers/{browserId}")
public Response deleteBrowser(@Context HttpHeaders headers,
@PathParam("browserId") String browserId,
@QueryParam("clientToken") String clientToken) {
String region = regionResolver.resolveRegion(headers);
try {
ObjectNode browser = service.deleteBrowser(browserId, clientToken, region);
ObjectNode response = objectMapper.createObjectNode();
response.put("browserId", browser.path("browserId").asText());
response.put("lastUpdatedAt", browser.path("lastUpdatedAt").asText());
response.put("status", browser.path("status").asText());
return Response.status(202).entity(response).build();
} catch (Exception e) {
return error(e, "deleting browser");
}
}
@POST
@Path("/browsers")
public Response listBrowsers(@Context HttpHeaders headers,
@QueryParam("maxResults") String maxResultsParam,
@QueryParam("nextToken") String nextToken,
@QueryParam("type") String type) {
String region = regionResolver.resolveRegion(headers);
try {
Integer maxResults = Pagination.parseMaxResults(maxResultsParam, "ValidationException");
var result = service.listBrowsers(maxResults, nextToken, type, region);
ObjectNode response = objectMapper.createObjectNode();
var summaries = response.putArray("browserSummaries");
for (ObjectNode browser : result.items()) {
ObjectNode summary = summaries.addObject();
copyText(browser, summary, "browserArn");
copyText(browser, summary, "browserId");
copyText(browser, summary, "createdAt");
copyText(browser, summary, "description");
copyText(browser, summary, "lastUpdatedAt");
copyText(browser, summary, "name");
copyText(browser, summary, "status");
}
if (result.nextToken() != null) {
response.put("nextToken", result.nextToken());
}
return Response.ok(response).build();
} catch (Exception e) {
return error(e, "listing browsers");
}
}
private static void copyText(ObjectNode source, ObjectNode target, String field) {
JsonNode value = source.get(field);
if (value != null && !value.isNull()) {
target.set(field, value.deepCopy());
}
}
private ObjectNode object(String body) throws Exception {
JsonNode request = objectMapper.readTree(body != null && !body.isBlank() ? body : "{}");
if (!request.isObject()) {
throw new AwsException("ValidationException", "request body must be a JSON object", 400);
}
return (ObjectNode) request;
}
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,485 @@
package io.github.hectorvent.floci.services.bedrockagentcorecontrol;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.Pagination;
import io.github.hectorvent.floci.core.common.PaginatedResult;
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 jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;
import java.util.regex.Pattern;
@ApplicationScoped
public class BedrockAgentCoreToolsService {
private static final Pattern TOOL_NAME = Pattern.compile("[a-zA-Z][a-zA-Z0-9_]{0,47}");
private static final String ALNUM = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
private final StorageBackend<String, ObjectNode> storage;
private final RegionResolver regionResolver;
@Inject
public BedrockAgentCoreToolsService(StorageFactory storageFactory, RegionResolver regionResolver) {
this(storageFactory.create("bedrockagentcore", "bedrock-agentcore-tools.json",
new TypeReference<Map<String, ObjectNode>>() {}), regionResolver);
}
BedrockAgentCoreToolsService(StorageBackend<String, ObjectNode> storage, RegionResolver regionResolver) {
this.storage = storage;
this.regionResolver = regionResolver;
}
public ObjectNode createBrowser(ObjectNode request, String region) {
String name = requiredText(request, "name");
if (!TOOL_NAME.matcher(name).matches()) {
throw new AwsException("ValidationException",
"name must match [a-zA-Z][a-zA-Z0-9_]{0,47}", 400);
}
JsonNode networkConfiguration = request.get("networkConfiguration");
if (networkConfiguration == null || !networkConfiguration.isObject()) {
throw new AwsException("ValidationException", "networkConfiguration is required", 400);
}
validateNetworkConfiguration(networkConfiguration, false);
validateCommonCreateFields(request, true);
String clientToken = optionalText(request, "clientToken");
if (clientToken != null) {
if (clientToken.length() < 33 || clientToken.length() > 256
|| !clientToken.matches("[a-zA-Z0-9](-*[a-zA-Z0-9]){0,256}")) {
throw new AwsException("ValidationException", "clientToken does not satisfy length or pattern constraints", 400);
}
ObjectNode existing = findByClientToken("browser", region, clientToken);
if (existing != null) {
return existing.deepCopy();
}
}
if (findByName("browser", region, name) != null) {
throw new AwsException("ConflictException", "Browser already exists: " + name, 409);
}
String id = name + "-" + random(10);
Instant now = Instant.now();
ObjectNode browser = request.deepCopy();
browser.put("browserId", id);
browser.put("browserArn", regionResolver.buildArn("bedrock-agentcore", region, "browser-custom/" + id));
browser.put("status", "READY");
browser.put("createdAt", now.toString());
browser.put("lastUpdatedAt", now.toString());
storage.put(key("browser", region, id), browser);
return browser.deepCopy();
}
public ObjectNode getBrowser(String browserId, String region) {
if ("aws.browser.v1".equals(browserId)) {
ObjectNode browser = com.fasterxml.jackson.databind.node.JsonNodeFactory.instance.objectNode();
browser.put("browserId", browserId);
browser.put("browserArn", regionResolver.buildArn("bedrock-agentcore", region, "browser/" + browserId));
browser.put("name", browserId);
browser.put("status", "READY");
browser.put("createdAt", "1970-01-01T00:00:00Z");
browser.put("lastUpdatedAt", "1970-01-01T00:00:00Z");
browser.putObject("networkConfiguration").put("networkMode", "PUBLIC");
return browser;
}
if (browserId == null || !browserId.matches("[a-zA-Z][a-zA-Z0-9_]{0,47}-[a-zA-Z0-9]{10}")) {
throw new AwsException("ValidationException", "browserId does not satisfy the required pattern", 400);
}
return storage.get(key("browser", region, browserId))
.map(ObjectNode::deepCopy)
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
"Browser not found: " + browserId, 404));
}
public ObjectNode createBrowserProfile(ObjectNode request, String region) {
String name = requiredText(request, "name");
if (!TOOL_NAME.matcher(name).matches()) {
throw new AwsException("ValidationException",
"name must match [a-zA-Z][a-zA-Z0-9_]{0,47}", 400);
}
validateDescription(request.get("description"));
validateTags(request.get("tags"));
String clientToken = optionalText(request, "clientToken");
if (clientToken != null) {
if (clientToken.length() < 33 || clientToken.length() > 256
|| !clientToken.matches("[a-zA-Z0-9](-*[a-zA-Z0-9]){0,256}")) {
throw new AwsException("ValidationException", "clientToken does not satisfy length or pattern constraints", 400);
}
ObjectNode existing = findByClientToken("browser-profile", region, clientToken);
if (existing != null) {
return existing.deepCopy();
}
}
if (findByName("browser-profile", region, name) != null) {
throw new AwsException("ConflictException", "Browser profile already exists: " + name, 409);
}
String id = name + "-" + random(10);
Instant now = Instant.now();
ObjectNode profile = request.deepCopy();
profile.put("profileId", id);
profile.put("profileArn", regionResolver.buildArn("bedrock-agentcore", region, "browser-profile/" + id));
profile.put("status", "READY");
profile.put("createdAt", now.toString());
profile.put("lastUpdatedAt", now.toString());
storage.put(key("browser-profile", region, id), profile);
return profile.deepCopy();
}
public ObjectNode createCodeInterpreter(ObjectNode request, String region) {
String name = requiredText(request, "name");
if (!TOOL_NAME.matcher(name).matches()) {
throw new AwsException("ValidationException",
"name must match [a-zA-Z][a-zA-Z0-9_]{0,47}", 400);
}
JsonNode networkConfiguration = request.get("networkConfiguration");
if (networkConfiguration == null || !networkConfiguration.isObject()) {
throw new AwsException("ValidationException", "networkConfiguration is required", 400);
}
validateNetworkConfiguration(networkConfiguration, true);
validateCommonCreateFields(request, false);
String clientToken = optionalText(request, "clientToken");
if (clientToken != null) {
if (clientToken.length() < 33 || clientToken.length() > 256
|| !clientToken.matches("[a-zA-Z0-9](-*[a-zA-Z0-9]){0,256}")) {
throw new AwsException("ValidationException", "clientToken does not satisfy length or pattern constraints", 400);
}
ObjectNode existing = findByClientToken("code-interpreter", region, clientToken);
if (existing != null) {
return existing.deepCopy();
}
}
if (findByName("code-interpreter", region, name) != null) {
throw new AwsException("ConflictException", "Code interpreter already exists: " + name, 409);
}
String id = name + "-" + random(10);
Instant now = Instant.now();
ObjectNode interpreter = request.deepCopy();
interpreter.put("codeInterpreterId", id);
interpreter.put("codeInterpreterArn", regionResolver.buildArn(
"bedrock-agentcore", region, "code-interpreter-custom/" + id));
interpreter.put("status", "READY");
interpreter.put("createdAt", now.toString());
interpreter.put("lastUpdatedAt", now.toString());
storage.put(key("code-interpreter", region, id), interpreter);
return interpreter.deepCopy();
}
public ObjectNode getCodeInterpreter(String codeInterpreterId, String region) {
if ("aws.codeinterpreter.v1".equals(codeInterpreterId)) {
ObjectNode interpreter = com.fasterxml.jackson.databind.node.JsonNodeFactory.instance.objectNode();
interpreter.put("codeInterpreterId", codeInterpreterId);
interpreter.put("codeInterpreterArn", "arn:aws:bedrock-agentcore:" + region
+ ":aws:code-interpreter/aws.codeinterpreter.v1");
interpreter.put("name", codeInterpreterId);
interpreter.put("status", "READY");
interpreter.put("createdAt", "1970-01-01T00:00:00Z");
interpreter.put("lastUpdatedAt", "1970-01-01T00:00:00Z");
interpreter.putObject("networkConfiguration").put("networkMode", "SANDBOX");
return interpreter;
}
if (codeInterpreterId == null
|| !codeInterpreterId.matches("[a-zA-Z][a-zA-Z0-9_]{0,47}-[a-zA-Z0-9]{10}")) {
throw new AwsException("ValidationException",
"codeInterpreterId does not satisfy the required pattern", 400);
}
return storage.get(key("code-interpreter", region, codeInterpreterId))
.map(ObjectNode::deepCopy)
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
"Code interpreter not found: " + codeInterpreterId, 404));
}
public PaginatedResult<ObjectNode> listCodeInterpreters(Integer maxResults, String nextToken,
String type, String region) {
if (type != null && !type.isBlank() && !"SYSTEM".equals(type) && !"CUSTOM".equals(type)) {
throw new AwsException("ValidationException", "type must be SYSTEM or CUSTOM", 400);
}
List<ObjectNode> interpreters = new ArrayList<>();
if (type == null || type.isBlank() || "SYSTEM".equals(type)) {
interpreters.add(getCodeInterpreter("aws.codeinterpreter.v1", region));
}
if (type == null || type.isBlank() || "CUSTOM".equals(type)) {
storage.scan(k -> k.startsWith(prefix("code-interpreter", region))).stream()
.map(ObjectNode::deepCopy)
.forEach(interpreters::add);
}
return Pagination.paginate(interpreters,
node -> node.path("codeInterpreterId").asText(), maxResults, nextToken,
100, 100, "ValidationException");
}
public ObjectNode deleteCodeInterpreter(String codeInterpreterId, String clientToken, String region) {
if ("aws.codeinterpreter.v1".equals(codeInterpreterId)) {
throw new AwsException("ValidationException", "System code interpreter cannot be deleted", 400);
}
if (clientToken != null && !clientToken.isBlank()
&& (clientToken.length() < 33 || clientToken.length() > 256
|| !clientToken.matches("[a-zA-Z0-9](-*[a-zA-Z0-9]){0,256}"))) {
throw new AwsException("ValidationException", "clientToken does not satisfy length or pattern constraints", 400);
}
String replayKey = deleteReplayKey("code-interpreter", region, codeInterpreterId, clientToken);
ObjectNode replay = replayKey == null ? null : storage.get(replayKey).map(ObjectNode::deepCopy).orElse(null);
if (replay != null) {
return replay.deepCopy();
}
ObjectNode interpreter = getCodeInterpreter(codeInterpreterId, region);
storage.delete(key("code-interpreter", region, codeInterpreterId));
interpreter.put("status", "DELETING");
interpreter.put("lastUpdatedAt", Instant.now().toString());
if (replayKey != null) {
storage.put(replayKey, interpreter.deepCopy());
}
return interpreter;
}
public ObjectNode getBrowserProfile(String profileId, String region) {
if (profileId == null || !profileId.matches("[a-zA-Z][a-zA-Z0-9_]{0,47}-[a-zA-Z0-9]{10}")) {
throw new AwsException("ValidationException", "profileId does not satisfy the required pattern", 400);
}
return storage.get(key("browser-profile", region, profileId))
.map(ObjectNode::deepCopy)
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
"Browser profile not found: " + profileId, 404));
}
public PaginatedResult<ObjectNode> listBrowserProfiles(Integer maxResults, String nextToken,
String name, String region) {
if (name != null && !name.isBlank() && !TOOL_NAME.matcher(name).matches()) {
throw new AwsException("ValidationException",
"name must match [a-zA-Z][a-zA-Z0-9_]{0,47}", 400);
}
List<ObjectNode> profiles = storage.scan(k -> k.startsWith(prefix("browser-profile", region))).stream()
.map(ObjectNode::deepCopy)
.filter(node -> name == null || name.isBlank() || name.equals(optionalText(node, "name")))
.toList();
return Pagination.paginate(profiles,
node -> node.path("profileId").asText(), maxResults, nextToken,
100, 100, "ValidationException");
}
public ObjectNode deleteBrowserProfile(String profileId, String clientToken, String region) {
if (clientToken != null && !clientToken.isBlank()
&& (clientToken.length() < 33 || clientToken.length() > 256
|| !clientToken.matches("[a-zA-Z0-9](-*[a-zA-Z0-9]){0,256}"))) {
throw new AwsException("ValidationException", "clientToken does not satisfy length or pattern constraints", 400);
}
String replayKey = deleteReplayKey("browser-profile", region, profileId, clientToken);
ObjectNode replay = replayKey == null ? null : storage.get(replayKey).map(ObjectNode::deepCopy).orElse(null);
if (replay != null) {
return replay.deepCopy();
}
ObjectNode profile = getBrowserProfile(profileId, region);
storage.delete(key("browser-profile", region, profileId));
profile.put("status", "DELETING");
profile.put("lastUpdatedAt", Instant.now().toString());
if (replayKey != null) {
storage.put(replayKey, profile.deepCopy());
}
return profile;
}
public ObjectNode deleteBrowser(String browserId, String clientToken, String region) {
if ("aws.browser.v1".equals(browserId)) {
throw new AwsException("ValidationException", "System browser cannot be deleted", 400);
}
if (clientToken != null && !clientToken.isBlank()
&& (clientToken.length() < 33 || clientToken.length() > 256
|| !clientToken.matches("[a-zA-Z0-9](-*[a-zA-Z0-9]){0,256}"))) {
throw new AwsException("ValidationException", "clientToken does not satisfy length or pattern constraints", 400);
}
String replayKey = deleteReplayKey("browser", region, browserId, clientToken);
ObjectNode replay = replayKey == null ? null : storage.get(replayKey).map(ObjectNode::deepCopy).orElse(null);
if (replay != null) {
return replay.deepCopy();
}
ObjectNode browser = getBrowser(browserId, region);
storage.delete(key("browser", region, browserId));
browser.put("status", "DELETING");
browser.put("lastUpdatedAt", Instant.now().toString());
if (replayKey != null) {
storage.put(replayKey, browser.deepCopy());
}
return browser;
}
public PaginatedResult<ObjectNode> listBrowsers(Integer maxResults, String nextToken, String type, String region) {
if (type != null && !type.isBlank() && !"SYSTEM".equals(type) && !"CUSTOM".equals(type)) {
throw new AwsException("ValidationException", "type must be SYSTEM or CUSTOM", 400);
}
List<ObjectNode> browsers = new ArrayList<>();
if (type == null || type.isBlank() || "SYSTEM".equals(type)) {
browsers.add(getBrowser("aws.browser.v1", region));
}
if (type == null || type.isBlank() || "CUSTOM".equals(type)) {
storage.scan(k -> k.startsWith(prefix("browser", region))).stream()
.map(ObjectNode::deepCopy)
.forEach(browsers::add);
}
return Pagination.paginate(browsers,
node -> node.path("browserId").asText(), maxResults, nextToken,
100, 100, "ValidationException");
}
private ObjectNode findByClientToken(String family, String region, String clientToken) {
return storage.scan(k -> k.startsWith(prefix(family, region))).stream()
.filter(node -> clientToken.equals(optionalText(node, "clientToken")))
.findFirst()
.map(ObjectNode::deepCopy)
.orElse(null);
}
private ObjectNode findByName(String family, String region, String name) {
return storage.scan(k -> k.startsWith(prefix(family, region))).stream()
.filter(node -> name.equals(optionalText(node, "name")))
.findFirst()
.map(ObjectNode::deepCopy)
.orElse(null);
}
private static void validateCommonCreateFields(ObjectNode request, boolean browser) {
validateDescription(request.get("description"));
validateTags(request.get("tags"));
JsonNode executionRoleArn = request.get("executionRoleArn");
if (executionRoleArn != null && !executionRoleArn.isNull()) {
if (!executionRoleArn.isTextual()) {
throw new AwsException("ValidationException", "executionRoleArn must be a string", 400);
}
String arn = executionRoleArn.asText();
if (arn.length() < 1 || arn.length() > 2048
|| !arn.matches("arn:aws(-[^:]+)?:iam::([0-9]{12})?:role/.+")) {
throw new AwsException("ValidationException", "executionRoleArn is invalid", 400);
}
}
validateArray(request.get("certificates"), "certificates", 1, 200);
validateArray(request.get("filesystemConfigurations"), "filesystemConfigurations", 0, 10);
if (browser) {
validateArray(request.get("enterprisePolicies"), "enterprisePolicies", 0, 100);
}
}
private static void validateDescription(JsonNode description) {
if (description == null || description.isNull()) {
return;
}
if (!description.isTextual() || description.asText().length() < 1
|| description.asText().length() > 4096) {
throw new AwsException("ValidationException", "description must be between 1 and 4096 characters", 400);
}
}
private static void validateArray(JsonNode value, String field, int min, int max) {
if (value == null || value.isNull()) {
return;
}
if (!value.isArray() || value.size() < min || value.size() > max) {
throw new AwsException("ValidationException",
field + " must contain between " + min + " and " + max + " items", 400);
}
}
private static void validateTags(JsonNode tags) {
if (tags == null || tags.isNull()) {
return;
}
if (!tags.isObject() || tags.size() > 50) {
throw new AwsException("ValidationException", "tags must be an object with at most 50 entries", 400);
}
tags.fields().forEachRemaining(entry -> {
String key = entry.getKey();
JsonNode rawValue = entry.getValue();
if (key.length() < 1 || key.length() > 128 || !key.matches("[a-zA-Z0-9\\s._:/=+@-]*")) {
throw new AwsException("ValidationException", "tag key does not satisfy AgentCore constraints", 400);
}
if (!rawValue.isTextual()) {
throw new AwsException("ValidationException", "tag value must be a string", 400);
}
String value = rawValue.asText();
if (value.length() > 256 || !value.matches("[a-zA-Z0-9\\s._:/=+@-]*")) {
throw new AwsException("ValidationException", "tag value does not satisfy AgentCore constraints", 400);
}
});
}
private static void validateNetworkConfiguration(JsonNode networkConfiguration, boolean codeInterpreter) {
JsonNode modeNode = networkConfiguration.get("networkMode");
if (modeNode == null || !modeNode.isTextual() || modeNode.asText().isBlank()) {
throw new AwsException("ValidationException", "networkConfiguration.networkMode is required", 400);
}
String mode = modeNode.asText();
boolean valid = codeInterpreter
? "PUBLIC".equals(mode) || "SANDBOX".equals(mode) || "VPC".equals(mode)
: "PUBLIC".equals(mode) || "VPC".equals(mode);
if (!valid) {
throw new AwsException("ValidationException", codeInterpreter
? "networkMode must be PUBLIC, SANDBOX, or VPC"
: "networkMode must be PUBLIC or VPC", 400);
}
JsonNode vpcConfig = networkConfiguration.get("vpcConfig");
if ("VPC".equals(mode) && (vpcConfig == null || !vpcConfig.isObject())) {
throw new AwsException("ValidationException", "vpcConfig is required when networkMode is VPC", 400);
}
if (vpcConfig == null || vpcConfig.isNull()) {
return;
}
if (!vpcConfig.isObject()) {
throw new AwsException("ValidationException", "vpcConfig must be an object", 400);
}
validateVpcIds(vpcConfig.get("securityGroups"), "securityGroups", "sg-[0-9a-zA-Z]{8,17}");
validateVpcIds(vpcConfig.get("subnets"), "subnets", "subnet-[0-9a-zA-Z]{8,17}");
}
private static void validateVpcIds(JsonNode value, String field, String pattern) {
if (value == null || !value.isArray() || value.isEmpty() || value.size() > 16) {
throw new AwsException("ValidationException", field + " must contain between 1 and 16 items", 400);
}
for (JsonNode item : value) {
if (!item.isTextual() || !item.asText().matches(pattern)) {
throw new AwsException("ValidationException", field + " contains an invalid identifier", 400);
}
}
}
private String deleteReplayKey(String family, String region, String id, String clientToken) {
if (clientToken == null || clientToken.isBlank()) {
return null;
}
return "delete-replay:" + family + ":" + regionResolver.getAccountId() + ":"
+ region + ":" + id + ":" + clientToken;
}
private static String requiredText(ObjectNode request, String field) {
String value = optionalText(request, field);
if (value == null || value.isBlank()) {
throw new AwsException("ValidationException", field + " is required", 400);
}
return value;
}
private static String optionalText(JsonNode request, String field) {
JsonNode value = request.get(field);
return value == null || value.isNull() ? null : value.asText();
}
private static String random(int length) {
StringBuilder value = new StringBuilder(length);
for (int i = 0; i < length; i++) {
value.append(ALNUM.charAt(ThreadLocalRandom.current().nextInt(ALNUM.length())));
}
return value.toString();
}
private static String key(String family, String region, String id) {
return prefix(family, region) + id;
}
private static String prefix(String family, String region) {
return family + ":" + region + ":";
}
}
@@ -115,4 +115,32 @@ class BedrockAgentCorePersistenceTest {
assertNotNull(loaded.getCreatedAt());
assertNotNull(loaded.getUpdatedAt());
}
@Test
void toolDeleteIdempotencySurvivesPersistentStorageRestart(@TempDir Path dir) {
Path file = dir.resolve("bedrock-agentcore-tools.json");
TypeReference<Map<String, ObjectNode>> ref = new TypeReference<>() {};
RegionResolver regionResolver = new RegionResolver(REGION, "000000000000");
PersistentStorage<String, ObjectNode> writer = new PersistentStorage<>(file, ref);
BedrockAgentCoreToolsService beforeRestart = new BedrockAgentCoreToolsService(writer, regionResolver);
ObjectNode request = mapper.createObjectNode();
request.put("name", "persistBrowser");
request.putObject("networkConfiguration").put("networkMode", "PUBLIC");
String browserId = beforeRestart.createBrowser(request, REGION).path("browserId").asText();
String clientToken = "persist-delete-browser-token-00000001";
ObjectNode firstDelete = beforeRestart.deleteBrowser(browserId, clientToken, REGION);
assertEquals("DELETING", firstDelete.path("status").asText());
writer.flush();
PersistentStorage<String, ObjectNode> reader = new PersistentStorage<>(file, ref);
reader.load();
BedrockAgentCoreToolsService afterRestart = new BedrockAgentCoreToolsService(reader, regionResolver);
ObjectNode replayedDelete = afterRestart.deleteBrowser(browserId, clientToken, REGION);
assertEquals("DELETING", replayedDelete.path("status").asText());
assertEquals(browserId, replayedDelete.path("browserId").asText());
}
}
+26
View File
@@ -30,6 +30,32 @@ services:
doc: docs/services/athena.md
sources:
- { path: src/main/java/io/github/hectorvent/floci/services/athena/AthenaJsonHandler.java, mode: switch }
- service: bedrock-agentcore-control
doc: docs/services/bedrock-agentcore.md
sources:
- { path: src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreControlController.java, mode: rest }
- { path: src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreIdentityController.java, mode: rest }
- { path: src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreGatewayController.java, mode: rest }
- { path: src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreMemoryController.java, mode: rest }
- { path: src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreToolsController.java, mode: rest }
- { path: src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreGatewayRuleController.java, mode: rest }
- { path: src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreResourcePolicyController.java, mode: rest }
rename_actions:
CreateEndpoint: CreateAgentRuntimeEndpoint
GetEndpoint: GetAgentRuntimeEndpoint
UpdateEndpoint: UpdateAgentRuntimeEndpoint
DeleteEndpoint: DeleteAgentRuntimeEndpoint
ListEndpoints: ListAgentRuntimeEndpoints
Create: CreateWorkloadIdentity
Get: GetWorkloadIdentity
Update: UpdateWorkloadIdentity
Delete: DeleteWorkloadIdentity
List: ListWorkloadIdentities
CreateTarget: CreateGatewayTarget
GetTarget: GetGatewayTarget
UpdateTarget: UpdateGatewayTarget
DeleteTarget: DeleteGatewayTarget
ListTargets: ListGatewayTargets
- service: cloudformation
doc: docs/services/cloudformation.md
sources: