feat(cloudformation): provision AWS::BedrockAgentCore::Runtime, RuntimeEndpoint and Memory (#5226)

* feat(cloudformation): provision AWS::BedrockAgentCore::Runtime, RuntimeEndpoint and Memory

The AgentCore control plane is emulated but had no CloudFormation provisioner,
so the three types fell through to the generic stub that exposes only Arn and
a template using Fn::GetAtt [Memory, MemoryArn] in an IAM policy failed the
stack. BedrockAgentCoreCfnProvisioner maps every template property the
services can store onto CreateAgentRuntime / CreateAgentRuntimeEndpoint /
CreateMemory, publishes Ref as the registry schema's primaryIdentifier and
Fn::GetAtt for every read-only property, updates in place when the
create-only properties are unchanged and replaces otherwise, and deletes on
stack teardown. Properties the emulated services have no model for are logged
once at warn and listed in the docs.

* fix(cloudformation): make AgentCore updates rollback-aware and authoritative

Reachable through CfnProvisionerFixture (two-service inference arm). In-place
updates snapshot the prior runtime, endpoint and memory configuration and tags,
restore them on rollback, and delete a created entity when a later step of the
same provision fails. The template is authoritative: UpdateAgentRuntime replaces
the full configuration as AWS's PUT does (omitted authorizer, protocol and
environment are cleared on the SDK path too), and the partial-update Memory and
Endpoint calls get a replace-omitted overload for the provisioner. Nested
AWS::NoValue members are omitted rather than stored blank, and the control
service validates networkMode and serverProtocol with the API's
ValidationException wording.

* fix(cloudformation): accept AGUI runtimes and share the guarded provision helper

The protocol check left out AGUI, which the AgentCore API and the Runtime
schema allow, so an AG-UI runtime was refused through the API and in a stack.

Ec2NetworkCfnProvisioner and BedrockAgentCoreCfnProvisioner carried the same
guarded helper; it now lives on CfnRollback, taking the provisioner's
in-place undo as a callback, and both use it.
This commit is contained in:
danielxoi authored and GitHub committed 2026-10-12 21:38:57 -04:00
1 parent 999ccde676
commit f50437efba
16 files changed
+1642 -83

No files matched your search

@@ -15,6 +15,7 @@ import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@@ -94,6 +95,77 @@ class BedrockAgentCoreControlServiceTest {
assertEquals("2", service.resolveVersion(updated, null).getVersion());
}
@Test
void updatePublishesExactlyTheConfigurationTheRequestCarries() {
ObjectNode authorizer = mapper.createObjectNode();
authorizer.putObject("customJWTAuthorizer").put("discoveryUrl", "A");
ObjectNode protocol = mapper.createObjectNode().put("serverProtocol", "MCP");
AgentRuntime rt = service.createAgentRuntime("myAgent", artifact(), network(),
"arn:aws:iam::000000000000:role/agent", "desc", Map.of("K", "v"), authorizer, protocol, null, REGION);
String id = rt.getAgentRuntimeId();
// A PUT with the optional members omitted: the new version carries none of them.
service.updateAgentRuntime(id, artifact(), network(),
"arn:aws:iam::000000000000:role/agent", null, null, null, null, REGION);
AgentRuntime fresh = service.getAgentRuntime(id, REGION);
AgentRuntimeVersion latest = service.resolveVersion(fresh, null);
assertNull(latest.getDescription());
assertNull(latest.getAuthorizerConfiguration());
assertNull(latest.getProtocolConfiguration());
assertTrue(latest.getEnvironmentVariables().isEmpty());
AgentRuntimeVersion first = service.resolveVersion(fresh, "1");
assertEquals("A", first.getAuthorizerConfiguration().path("customJWTAuthorizer").path("discoveryUrl").asText());
assertEquals("MCP", first.getProtocolConfiguration().path("serverProtocol").asText());
assertEquals(Map.of("K", "v"), first.getEnvironmentVariables());
}
@Test
void createAndUpdateRejectUnknownNetworkModeAndServerProtocol() {
ObjectNode privateNetwork = mapper.createObjectNode().put("networkMode", "PRIVATE");
AwsException badMode = assertThrows(AwsException.class, () -> service.createAgentRuntime("myAgent",
artifact(), privateNetwork, "arn:aws:iam::000000000000:role/agent", null, null, null, null, null, REGION));
assertEquals("ValidationException", badMode.getErrorCode());
assertEquals("1 validation error detected: Value 'PRIVATE' at 'networkConfiguration.networkMode' failed to "
+ "satisfy constraint: Member must satisfy enum value set: [PUBLIC, VPC]", badMode.getMessage());
AwsException noMode = assertThrows(AwsException.class, () -> service.createAgentRuntime("myAgent",
artifact(), mapper.createObjectNode(), "arn:aws:iam::000000000000:role/agent", null, null, null, null,
null, REGION));
assertEquals("networkConfiguration.networkMode is required", noMode.getMessage());
String id = create("myAgent").getAgentRuntimeId();
ObjectNode grpc = mapper.createObjectNode().put("serverProtocol", "GRPC");
AwsException badProtocol = assertThrows(AwsException.class, () -> service.updateAgentRuntime(id, artifact(),
network(), "arn:aws:iam::000000000000:role/agent", null, null, null, grpc, REGION));
assertEquals("1 validation error detected: Value 'GRPC' at 'protocolConfiguration.serverProtocol' failed to "
+ "satisfy constraint: Member must satisfy enum value set: [MCP, HTTP, A2A, AGUI]", badProtocol.getMessage());
assertEquals(1, service.getAgentRuntime(id, REGION).getLatestVersion(), "a rejected update publishes nothing");
}
@Test
void createAcceptsTheAguiServerProtocol() {
ObjectNode agui = mapper.createObjectNode().put("serverProtocol", "AGUI");
AgentRuntime rt = service.createAgentRuntime("aguiAgent", artifact(), network(),
"arn:aws:iam::000000000000:role/agent", null, null, null, agui, null, REGION);
assertEquals("AGUI", service.resolveVersion(rt, "1").getProtocolConfiguration().path("serverProtocol").asText());
}
@Test
void updateEndpointClearsAnOmittedDescriptionOnlyWhenReplacingOmitted() {
String id = create("myAgent").getAgentRuntimeId();
service.createEndpoint(id, "prod", "1", "prod ep", null, REGION);
service.updateEndpoint(id, "prod", null, null, REGION);
assertEquals("prod ep", service.getEndpoint(id, "prod", REGION).getDescription(),
"the API call leaves an omitted description alone");
service.updateEndpoint(id, "prod", null, null, true, REGION);
assertNull(service.getEndpoint(id, "prod", REGION).getDescription());
assertEquals("1", service.getEndpoint(id, "prod", REGION).getTargetVersion(),
"an omitted version keeps the endpoint on the version it serves");
}
@Test
void getUnknownThrows404() {
AwsException e = assertThrows(AwsException.class,
@@ -79,6 +79,18 @@ class BedrockAgentCoreMemoryServiceTest {
assertEquals("arn:aws:iam::000000000000:role/mem-role-2", after.getMemoryExecutionRoleArn());
}
@Test
void updateReplacingOmittedClearsNullDescriptionAndRole() {
Memory memory = create("replMemory");
service.update(memory.getMemoryId(), null, 45, null, true, REGION);
Memory after = service.get(memory.getMemoryId(), REGION);
assertEquals(45, after.getEventExpiryDuration());
assertNull(after.getDescription());
assertNull(after.getMemoryExecutionRoleArn());
assertEquals(KEY_ARN, after.getEncryptionKeyArn(), "the encryption key is not updatable, so it stays");
}
@Test
void updateRejectsOutOfRangeExpiry() {
Memory memory = create("badUpd");
@@ -47,7 +47,7 @@ class BedrockAgentCorePersistenceTest {
authorizer, null, null, REGION);
String id = created.getAgentRuntimeId();
svc.updateAgentRuntime(id, artifact, network,
"arn:aws:iam::000000000000:role/agent", "v2", null, authorizer, null, REGION);
"arn:aws:iam::000000000000:role/agent", "v2", Map.of("K", "V"), authorizer, null, REGION);
svc.createEndpoint(id, "prod", "1", "prod ep", null, REGION);
AgentRuntime before = svc.getAgentRuntime(id, REGION);
svc.tagByArn(REGION, svc.arn(before, "1", REGION), Map.of("env", "prod"));
@@ -12,6 +12,8 @@ import io.github.hectorvent.floci.services.appsync.AppSyncService;
import io.github.hectorvent.floci.services.autoscaling.AutoScalingService;
import io.github.hectorvent.floci.services.backup.BackupService;
import io.github.hectorvent.floci.services.batch.BatchService;
import io.github.hectorvent.floci.services.bedrockagentcorecontrol.BedrockAgentCoreControlService;
import io.github.hectorvent.floci.services.bedrockagentcorecontrol.BedrockAgentCoreMemoryService;
import io.github.hectorvent.floci.services.cloudformation.provisioners.AcmCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.ApiGatewayAccountCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.ApiGatewayApiKeyCfnProvisioner;
@@ -28,6 +30,7 @@ import io.github.hectorvent.floci.services.cloudformation.provisioners.AutoScali
import io.github.hectorvent.floci.services.cloudformation.provisioners.AutoScalingScalingPolicyCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.BackupVaultCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.BatchCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.BedrockAgentCoreCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CdkMetadataCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnDynamicReferences;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnResourceDispatcher;
@@ -235,6 +238,8 @@ final class CfnProvisionerFixture {
private RedshiftService redshiftService;
private RedshiftServerlessService redshiftServerlessService;
private CloudMapService cloudMapService;
private BedrockAgentCoreControlService bedrockAgentCoreControlService;
private BedrockAgentCoreMemoryService bedrockAgentCoreMemoryService;
private CloudFormationResourceRegistry resourceRegistry;
private boolean registryChosenByTest;
private CfnDynamicReferences dynamicReferences;
@@ -466,6 +471,10 @@ final class CfnProvisionerFixture {
if (cloudMapService != null) {
discovered.add(new CloudMapCfnProvisioner(cloudMapService));
}
if (bedrockAgentCoreControlService != null && bedrockAgentCoreMemoryService != null) {
discovered.add(new BedrockAgentCoreCfnProvisioner(bedrockAgentCoreControlService,
bedrockAgentCoreMemoryService));
}
return discovered;
}
@@ -754,6 +763,16 @@ final class CfnProvisionerFixture {
return this;
}
public Builder bedrockAgentCoreControl(BedrockAgentCoreControlService v) {
this.bedrockAgentCoreControlService = v;
return this;
}
public Builder bedrockAgentCoreMemory(BedrockAgentCoreMemoryService v) {
this.bedrockAgentCoreMemoryService = v;
return this;
}
public Builder registry(CloudFormationResourceRegistry v) {
this.resourceRegistry = v;
this.registryChosenByTest = true;
@@ -0,0 +1,387 @@
package io.github.hectorvent.floci.services.cloudformation;
import io.github.hectorvent.floci.core.common.XmlParser;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.ValidatableResponse;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.util.Map;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasKey;
import static org.hamcrest.Matchers.not;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* A stack with the three AgentCore control-plane types, wired the way a CDK app wires them: the
* runtime reads the memory id, the endpoint reads the runtime id, and an IAM policy scopes itself
* to the memory ARN through {@code Fn::GetAtt}, which fails the stack when it cannot resolve.
*
* <p>The second stack exercises the in-place update path: an update that changes every mutable
* property next to a resource that cannot be created is rolled back onto the entities, and a
* later update that drops optional properties clears them, because the template is the whole
* declared configuration.
*/
@QuarkusTest
class CloudFormationBedrockAgentCoreIntegrationTest {
private static final String CFN_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20261006/us-east-1/cloudformation/aws4_request";
private static final String IAM_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20261006/us-east-1/iam/aws4_request";
private static final String STACK = "cfn-bedrock-agentcore-integration";
private static final String ROLLBACK_STACK = "cfn-bedrock-agentcore-rollback";
private static final String CONTAINER_URI = "000000000000.dkr.ecr.us-east-1.amazonaws.com/cfn-agent:latest";
private static final String TEMPLATE = """
{
"Resources": {
"Role": {
"Type": "AWS::IAM::Role",
"Properties": {
"AssumeRolePolicyDocument": {
"Version": "2012-10-17",
"Statement": [{"Effect": "Allow",
"Principal": {"Service": "bedrock-agentcore.amazonaws.com"}, "Action": "sts:AssumeRole"}]
}
}
},
"Memory": {
"Type": "AWS::BedrockAgentCore::Memory",
"Properties": {
"Name": "%s",
"EventExpiryDuration": %d,
"Description": "agent memory",
"MemoryExecutionRoleArn": {"Fn::GetAtt": ["Role", "Arn"]},
"Tags": {"team": "agents"}
}
},
"MemoryPolicy": {
"Type": "AWS::IAM::Policy",
"Properties": {
"PolicyName": "memory-access",
"Roles": [{"Ref": "Role"}],
"PolicyDocument": {
"Version": "2012-10-17",
"Statement": [{"Effect": "Allow", "Action": ["bedrock-agentcore:CreateEvent"],
"Resource": {"Fn::GetAtt": ["Memory", "MemoryArn"]}}]
}
}
},
"Runtime": {
"Type": "AWS::BedrockAgentCore::Runtime",
"Properties": {
"AgentRuntimeName": "cfn_agent_runtime",
"AgentRuntimeArtifact": {"ContainerConfiguration": {"ContainerUri": "%s"}},
"RoleArn": {"Fn::GetAtt": ["Role", "Arn"]},
"NetworkConfiguration": {"NetworkMode": "PUBLIC"},
"ProtocolConfiguration": "HTTP",
"EnvironmentVariables": {"MEMORY_ID": {"Fn::GetAtt": ["Memory", "MemoryId"]}},
"Description": "%s",
"Tags": {"team": "agents"}
}
},
"Endpoint": {
"Type": "AWS::BedrockAgentCore::RuntimeEndpoint",
"Properties": {
"AgentRuntimeId": {"Fn::GetAtt": ["Runtime", "AgentRuntimeId"]},
"Name": "prod",
"Description": "production endpoint"
}
}
},
"Outputs": {
"RoleArn": {"Value": {"Fn::GetAtt": ["Role", "Arn"]}},
"RoleName": {"Value": {"Ref": "Role"}},
"MemoryRef": {"Value": {"Ref": "Memory"}},
"MemoryArn": {"Value": {"Fn::GetAtt": ["Memory", "MemoryArn"]}},
"MemoryId": {"Value": {"Fn::GetAtt": ["Memory", "MemoryId"]}},
"MemoryStatus": {"Value": {"Fn::GetAtt": ["Memory", "Status"]}},
"RuntimeRef": {"Value": {"Ref": "Runtime"}},
"RuntimeArn": {"Value": {"Fn::GetAtt": ["Runtime", "AgentRuntimeArn"]}},
"RuntimeId": {"Value": {"Fn::GetAtt": ["Runtime", "AgentRuntimeId"]}},
"RuntimeVersion": {"Value": {"Fn::GetAtt": ["Runtime", "AgentRuntimeVersion"]}},
"RuntimeStatus": {"Value": {"Fn::GetAtt": ["Runtime", "Status"]}},
"WorkloadIdentityArn": {"Value": {"Fn::GetAtt": ["Runtime", "WorkloadIdentityDetails.WorkloadIdentityArn"]}},
"EndpointRef": {"Value": {"Ref": "Endpoint"}},
"EndpointArn": {"Value": {"Fn::GetAtt": ["Endpoint", "AgentRuntimeEndpointArn"]}},
"EndpointId": {"Value": {"Fn::GetAtt": ["Endpoint", "Id"]}},
"EndpointRuntimeArn": {"Value": {"Fn::GetAtt": ["Endpoint", "AgentRuntimeArn"]}},
"EndpointTargetVersion": {"Value": {"Fn::GetAtt": ["Endpoint", "TargetVersion"]}},
"EndpointStatus": {"Value": {"Fn::GetAtt": ["Endpoint", "Status"]}}
}
}
""";
/**
* A memory, a runtime and an endpoint whose optional properties are all driven by the
* arguments: a null description leaves the property out of the template. {@code failing} adds a
* resource whose create is rejected, ordered after the endpoint so the update rolls back only
* once all three were updated.
*/
private static String rollbackTemplate(String memoryDescription, String runtimeDescription,
String endpointDescription, String tagValue, boolean failing) {
String failingResource = failing
? """
,
"Boom": {"Type": "AWS::SecretsManager::Secret", "DependsOn": "Endpoint",
"Properties": {"SecretString": "x",
"GenerateSecretString": {"SecretStringTemplate": "{}", "GenerateStringKey": "p"}}}"""
: "";
return """
{
"Resources": {
"Role": {
"Type": "AWS::IAM::Role",
"Properties": {
"AssumeRolePolicyDocument": {
"Version": "2012-10-17",
"Statement": [{"Effect": "Allow",
"Principal": {"Service": "bedrock-agentcore.amazonaws.com"}, "Action": "sts:AssumeRole"}]
}
}
},
"Memory": {
"Type": "AWS::BedrockAgentCore::Memory",
"Properties": {
"Name": "cfn_rollback_memory",
"EventExpiryDuration": 30%s,
"Tags": {"team": "%s"}
}
},
"Runtime": {
"Type": "AWS::BedrockAgentCore::Runtime",
"Properties": {
"AgentRuntimeName": "cfn_rollback_runtime",
"AgentRuntimeArtifact": {"ContainerConfiguration": {"ContainerUri": "%s"}},
"RoleArn": {"Fn::GetAtt": ["Role", "Arn"]}%s,
"Tags": {"team": "%s"}
}
},
"Endpoint": {
"Type": "AWS::BedrockAgentCore::RuntimeEndpoint",
"Properties": {
"AgentRuntimeId": {"Fn::GetAtt": ["Runtime", "AgentRuntimeId"]},
"Name": "prod"%s
}
}%s
},
"Outputs": {
"MemoryId": {"Value": {"Fn::GetAtt": ["Memory", "MemoryId"]}},
"MemoryArn": {"Value": {"Fn::GetAtt": ["Memory", "MemoryArn"]}},
"RuntimeId": {"Value": {"Fn::GetAtt": ["Runtime", "AgentRuntimeId"]}},
"RuntimeArn": {"Value": {"Fn::GetAtt": ["Runtime", "AgentRuntimeArn"]}}
}
}
""".formatted(descriptionProperty(memoryDescription), tagValue, CONTAINER_URI,
descriptionProperty(runtimeDescription), tagValue, descriptionProperty(endpointDescription),
failingResource);
}
private static String descriptionProperty(String description) {
return description == null ? "" : ",\n\"Description\": \"" + description + "\"";
}
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
void createUpdateReplaceAndDeleteAgentCoreResources() {
cloudFormation(STACK, "CreateStack", TEMPLATE.formatted("cfn_agent_memory", 30, CONTAINER_URI, "first"));
Map<String, String> outputs = outputs("CREATE_COMPLETE");
// Ref follows each registry schema's primaryIdentifier.
String memoryArn = outputs.get("MemoryArn");
String memoryId = outputs.get("MemoryId");
assertEquals(memoryArn, outputs.get("MemoryRef"));
assertEquals("arn:aws:bedrock-agentcore:us-east-1:000000000000:memory/" + memoryId, memoryArn);
assertEquals("ACTIVE", outputs.get("MemoryStatus"));
String runtimeId = outputs.get("RuntimeId");
String runtimeArn = outputs.get("RuntimeArn");
assertEquals(runtimeId, outputs.get("RuntimeRef"));
assertTrue(runtimeId.startsWith("cfn_agent_runtime-"), runtimeId);
assertTrue(runtimeArn.matches("arn:aws:bedrock-agentcore:us-east-1:000000000000:agent/[0-9a-f-]{36}:1"),
runtimeArn);
assertEquals("1", outputs.get("RuntimeVersion"));
assertEquals("READY", outputs.get("RuntimeStatus"));
assertTrue(outputs.get("WorkloadIdentityArn").contains(":workload-identity-directory/default/workload-identity/"),
outputs.get("WorkloadIdentityArn"));
String endpointArn = outputs.get("EndpointArn");
assertEquals(endpointArn, outputs.get("EndpointRef"));
assertTrue(endpointArn.startsWith("arn:aws:bedrock-agentcore:us-east-1:000000000000:agentEndpoint/"), endpointArn);
assertEquals(runtimeArn, outputs.get("EndpointRuntimeArn"));
assertEquals("1", outputs.get("EndpointTargetVersion"));
assertEquals("READY", outputs.get("EndpointStatus"));
// The resources exist with the template's properties, as the AgentCore API reports them.
describeMemory(memoryId)
.statusCode(200)
.body("memory.arn", equalTo(memoryArn))
.body("memory.name", equalTo("cfn_agent_memory"))
.body("memory.eventExpiryDuration", equalTo(30))
.body("memory.description", equalTo("agent memory"))
.body("memory.memoryExecutionRoleArn", equalTo(outputs.get("RoleArn")));
given().when().get("/tags/" + memoryArn).then().statusCode(200).body("tags.team", equalTo("agents"));
describeRuntime(runtimeId)
.statusCode(200)
.body("agentRuntimeArn", equalTo(runtimeArn))
.body("agentRuntimeName", equalTo("cfn_agent_runtime"))
.body("agentRuntimeVersion", equalTo("1"))
.body("roleArn", equalTo(outputs.get("RoleArn")))
.body("description", equalTo("first"))
.body("agentRuntimeArtifact.containerConfiguration.containerUri", equalTo(CONTAINER_URI))
.body("networkConfiguration.networkMode", equalTo("PUBLIC"))
.body("protocolConfiguration.serverProtocol", equalTo("HTTP"))
.body("environmentVariables.MEMORY_ID", equalTo(memoryId))
.body("workloadIdentityDetails.workloadIdentityArn", equalTo(outputs.get("WorkloadIdentityArn")));
given().when().get("/tags/" + runtimeArn).then().statusCode(200).body("tags.team", equalTo("agents"));
describeEndpoint(runtimeId, "prod")
.statusCode(200)
.body("agentRuntimeEndpointArn", equalTo(endpointArn))
.body("id", equalTo(outputs.get("EndpointId")))
.body("targetVersion", equalTo("1"))
.body("description", equalTo("production endpoint"));
// The policy scoped itself to the real memory ARN through Fn::GetAtt.
String storedPolicy = getRolePolicy(outputs.get("RoleName"), "memory-access");
assertTrue(storedPolicy.contains(memoryArn), "expected the memory ARN in the stored policy: " + storedPolicy);
// An update that keeps every create-only property changes the entities in place: the
// memory and runtime keep their ids, the runtime publishes a new version, and the
// untouched endpoint is left alone.
cloudFormation(STACK, "UpdateStack", TEMPLATE.formatted("cfn_agent_memory", 60, CONTAINER_URI, "second"));
Map<String, String> updated = outputs("UPDATE_COMPLETE");
assertEquals(memoryArn, updated.get("MemoryRef"));
assertEquals(runtimeId, updated.get("RuntimeRef"));
assertEquals(endpointArn, updated.get("EndpointRef"));
assertEquals("2", updated.get("RuntimeVersion"));
assertEquals("1", updated.get("EndpointTargetVersion"));
describeMemory(memoryId).statusCode(200).body("memory.eventExpiryDuration", equalTo(60));
describeRuntime(runtimeId).statusCode(200)
.body("agentRuntimeVersion", equalTo("2"))
.body("description", equalTo("second"));
describeEndpoint(runtimeId, "prod").statusCode(200).body("targetVersion", equalTo("1"));
// Renaming the memory replaces it: a new ARN, the runtime re-pointed at the new id, the
// policy re-scoped, and the displaced memory removed once the update commits.
cloudFormation(STACK, "UpdateStack", TEMPLATE.formatted("cfn_agent_memory_v2", 60, CONTAINER_URI, "second"));
Map<String, String> replaced = outputs("UPDATE_COMPLETE");
String replacementArn = replaced.get("MemoryRef");
assertNotEquals(memoryArn, replacementArn);
assertEquals(runtimeId, replaced.get("RuntimeRef"));
describeMemory(replaced.get("MemoryId")).statusCode(200).body("memory.name", equalTo("cfn_agent_memory_v2"));
describeMemory(memoryId).statusCode(404);
describeRuntime(runtimeId).statusCode(200)
.body("environmentVariables.MEMORY_ID", equalTo(replaced.get("MemoryId")));
assertTrue(getRolePolicy(outputs.get("RoleName"), "memory-access").contains(replacementArn));
cloudFormation(STACK, "DeleteStack", null);
CfnStackWaits.awaitStackDeleted(STACK);
describeMemory(replaced.get("MemoryId")).statusCode(404);
describeRuntime(runtimeId).statusCode(404);
}
@Test
void inPlaceChangesNextToAFailingResourceAreRolledBackAndOmittedPropertiesAreCleared() {
cloudFormation(ROLLBACK_STACK, "CreateStack",
rollbackTemplate("memory one", "runtime one", "endpoint one", "agents", false));
Map<String, String> outputs = outputs(ROLLBACK_STACK, "CREATE_COMPLETE");
String memoryId = outputs.get("MemoryId");
String memoryArn = outputs.get("MemoryArn");
String runtimeId = outputs.get("RuntimeId");
String runtimeArn = outputs.get("RuntimeArn");
// Every mutable property changes in place, then a sibling fails the update: the runtime
// is restored as a further version (as an UpdateAgentRuntime rollback is on AWS), and the
// memory, the endpoint and both tag sets carry what the stack last committed.
cloudFormation(ROLLBACK_STACK, "UpdateStack",
rollbackTemplate("memory two", "runtime two", "endpoint two", "ml", true));
Map<String, String> rolledBack = outputs(ROLLBACK_STACK, "UPDATE_ROLLBACK_COMPLETE");
assertEquals(runtimeId, rolledBack.get("RuntimeId"));
assertEquals(memoryArn, rolledBack.get("MemoryArn"));
describeRuntime(runtimeId).statusCode(200)
.body("agentRuntimeVersion", equalTo("3"))
.body("description", equalTo("runtime one"));
given().when().get("/tags/" + runtimeArn).then().statusCode(200).body("tags.team", equalTo("agents"));
describeMemory(memoryId).statusCode(200).body("memory.description", equalTo("memory one"));
given().when().get("/tags/" + memoryArn).then().statusCode(200).body("tags.team", equalTo("agents"));
describeEndpoint(runtimeId, "prod").statusCode(200).body("description", equalTo("endpoint one"));
// Dropping the descriptions from the template clears them: the template is the whole
// declared configuration, so an omitted property is not left over from the last update.
cloudFormation(ROLLBACK_STACK, "UpdateStack", rollbackTemplate(null, null, null, "agents", false));
outputs(ROLLBACK_STACK, "UPDATE_COMPLETE");
describeRuntime(runtimeId).statusCode(200)
.body("agentRuntimeVersion", equalTo("4"))
.body("$", not(hasKey("description")));
describeMemory(memoryId).statusCode(200).body("memory", not(hasKey("description")));
describeEndpoint(runtimeId, "prod").statusCode(200).body("$", not(hasKey("description")));
cloudFormation(ROLLBACK_STACK, "DeleteStack", null);
CfnStackWaits.awaitStackDeleted(ROLLBACK_STACK);
describeMemory(memoryId).statusCode(404);
describeRuntime(runtimeId).statusCode(404);
}
private static void cloudFormation(String stack, String action, String template) {
RequestSpecification request = given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", action)
.formParam("StackName", stack);
if (template != null) {
request.formParam("TemplateBody", template);
}
request.when().post("/").then().statusCode(200);
}
private static Map<String, String> outputs(String expectedStatus) {
return outputs(STACK, expectedStatus);
}
private static Map<String, String> outputs(String stack, String expectedStatus) {
CfnStackWaits.StackState state = CfnStackWaits.awaitTerminal(stack, CFN_AUTH);
assertEquals(expectedStatus, state.status(), state.reason());
String xml = given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "DescribeStacks")
.formParam("StackName", stack)
.when().post("/").then().statusCode(200).extract().asString();
return XmlParser.extractPairs(xml, "Outputs", "OutputKey", "OutputValue");
}
private static ValidatableResponse describeMemory(String memoryId) {
return given().when().get("/memories/" + memoryId + "/details").then();
}
private static ValidatableResponse describeRuntime(String runtimeId) {
return given().when().get("/runtimes/" + runtimeId + "/").then();
}
private static ValidatableResponse describeEndpoint(String runtimeId, String name) {
return given().when().get("/runtimes/" + runtimeId + "/runtime-endpoints/" + name + "/").then();
}
private static String getRolePolicy(String roleName, String policyName) {
return given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", IAM_AUTH)
.formParam("Action", "GetRolePolicy")
.formParam("RoleName", roleName)
.formParam("PolicyName", policyName)
.when().post("/").then().statusCode(200).extract().asString();
}
}
@@ -0,0 +1,287 @@
package io.github.hectorvent.floci.services.cloudformation.provisioners;
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.AwsException;
import io.github.hectorvent.floci.services.bedrockagentcorecontrol.BedrockAgentCoreControlService;
import io.github.hectorvent.floci.services.bedrockagentcorecontrol.BedrockAgentCoreMemoryService;
import io.github.hectorvent.floci.services.bedrockagentcorecontrol.model.AgentRuntime;
import io.github.hectorvent.floci.services.bedrockagentcorecontrol.model.AgentRuntimeEndpoint;
import io.github.hectorvent.floci.services.bedrockagentcorecontrol.model.Memory;
import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.time.Instant;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyMap;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* The AgentCore provisioner in isolation, with both services mocked and a real template engine so
* conditions and {@code AWS::NoValue} resolve the way they do in a stack.
*/
class BedrockAgentCoreCfnProvisionerTest {
private static final String REGION = "us-east-1";
private static final String RUNTIME_ID = "agent-abcdefghij";
private static final String RUNTIME_ARN = "arn:aws:bedrock-agentcore:us-east-1:000000000000:agent/uuid:1";
private static final String MEMORY_ID = "mem-abcdefghij";
private static final String MEMORY_ARN = "arn:aws:bedrock-agentcore:us-east-1:000000000000:memory/" + MEMORY_ID;
private static final String ROLE_ARN = "arn:aws:iam::000000000000:role/agent";
private final BedrockAgentCoreControlService runtimes = mock(BedrockAgentCoreControlService.class);
private final BedrockAgentCoreMemoryService memories = mock(BedrockAgentCoreMemoryService.class);
private final BedrockAgentCoreCfnProvisioner provisioner = new BedrockAgentCoreCfnProvisioner(runtimes, memories);
private final ObjectMapper mapper = new ObjectMapper();
/** A real engine (conditions and intrinsics resolve as in a stack) with no conditions defined. */
private ProvisionContext ctx(String priorPhysicalId) {
CloudFormationTemplateEngine engine = CloudFormationTemplateEngine.standalone("000000000000", REGION,
"my-stack", mapper, value -> value);
return new ProvisionContext(engine, REGION, "000000000000", "my-stack", priorPhysicalId);
}
private static StackResource resource(String type) {
StackResource r = new StackResource();
r.setLogicalId("Res");
r.setResourceType(type);
r.setAttributes(new HashMap<>());
return r;
}
private JsonNode json(String text) {
try {
return mapper.readTree(text);
} catch (Exception e) {
throw new IllegalArgumentException(e);
}
}
private AgentRuntime runtime(String description, Map<String, String> environment) {
AgentRuntime runtime = new AgentRuntime();
runtime.setAgentRuntimeId(RUNTIME_ID);
runtime.setAgentRuntimeName("agent");
runtime.setUuid("uuid");
runtime.setRoleArn(ROLE_ARN);
runtime.setDescription(description);
runtime.setStatus("READY");
runtime.setLatestVersion(1);
runtime.setCreatedAt(Instant.EPOCH);
runtime.setLastUpdatedAt(Instant.EPOCH);
runtime.setAgentRuntimeArtifact(json("{\"containerConfiguration\":{\"containerUri\":\"img:1\"}}"));
runtime.setNetworkConfiguration(json("{\"networkMode\":\"PUBLIC\"}"));
runtime.setEnvironmentVariables(new HashMap<>(environment));
runtime.setWorkloadIdentityArn("arn:wi");
return runtime;
}
private Memory memory(String description, String roleArn) {
Memory memory = new Memory();
memory.setMemoryId(MEMORY_ID);
memory.setName("mem");
memory.setStatus("ACTIVE");
memory.setDescription(description);
memory.setEventExpiryDuration(30);
memory.setMemoryExecutionRoleArn(roleArn);
memory.setCreatedAt(Instant.EPOCH);
memory.setUpdatedAt(Instant.EPOCH);
return memory;
}
private static ObjectNode runtimeProps(ObjectMapper mapper, String description, String tag) {
ObjectNode props = mapper.createObjectNode();
props.put("AgentRuntimeName", "agent");
props.put("RoleArn", ROLE_ARN);
props.putObject("AgentRuntimeArtifact").putObject("ContainerConfiguration").put("ContainerUri", "img:1");
props.putObject("NetworkConfiguration").put("NetworkMode", "PUBLIC");
if (description != null) {
props.put("Description", description);
}
props.putObject("Tags").put("team", tag);
return props;
}
@Test
void aFnIfSelectingNoValueInsideNetworkConfigurationIsOmitted() {
when(runtimes.createAgentRuntime(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()))
.thenReturn(runtime(null, Map.of()));
when(runtimes.arn(any(), any(), eq(REGION))).thenReturn(RUNTIME_ARN);
ObjectNode props = runtimeProps(mapper, null, "agents");
// No condition is defined, so Fn::If takes its else branch, as an undefined condition does.
props.set("NetworkConfiguration", json("""
{"NetworkMode": "PUBLIC",
"NetworkModeConfig": {"Fn::If": ["UseVpc", {"Subnets": ["subnet-1"]}, {"Ref": "AWS::NoValue"}]}}
"""));
provisioner.provision(resource("AWS::BedrockAgentCore::Runtime"), props, ctx(null));
ArgumentCaptor<JsonNode> network = ArgumentCaptor.forClass(JsonNode.class);
verify(runtimes).createAgentRuntime(eq("agent"), any(), network.capture(), eq(ROLE_ARN), isNull(), any(),
isNull(), isNull(), isNull(), eq(REGION));
assertEquals(json("{\"networkMode\":\"PUBLIC\"}"), network.getValue(),
"the NoValue member must be omitted, not resolved to an empty string");
}
@Test
void aFailedTaggingAfterCreateDeletesTheRuntimeBeforePropagating() {
when(runtimes.createAgentRuntime(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()))
.thenReturn(runtime(null, Map.of()));
when(runtimes.arn(any(), any(), eq(REGION))).thenReturn(RUNTIME_ARN);
doThrow(new AwsException("ThrottlingException", "slow down", 429))
.when(runtimes).tagByArn(eq(REGION), eq(RUNTIME_ARN), anyMap());
StackResource r = resource("AWS::BedrockAgentCore::Runtime");
AwsException failure = assertThrows(AwsException.class,
() -> provisioner.provision(r, runtimeProps(mapper, null, "agents"), ctx(null)));
assertEquals("ThrottlingException", failure.getErrorCode());
verify(runtimes).deleteAgentRuntime(RUNTIME_ID, null, REGION);
assertFalse(r.getAttributes().containsKey(CfnRollback.ROLLBACK_OWNED_ATTR),
"the undo succeeded, so the engine must not try to delete the runtime again");
}
@Test
void aFailedRuntimeLookupAfterCreateDeletesTheEndpoint() {
AgentRuntimeEndpoint endpoint = new AgentRuntimeEndpoint();
endpoint.setName("prod");
endpoint.setUuid("ep-uuid");
endpoint.setTargetVersion("1");
endpoint.setLiveVersion("1");
endpoint.setStatus("READY");
endpoint.setCreatedAt(Instant.EPOCH);
endpoint.setLastUpdatedAt(Instant.EPOCH);
when(runtimes.createEndpoint(RUNTIME_ID, "prod", null, null, null, REGION)).thenReturn(endpoint);
when(runtimes.endpointArn(endpoint, REGION)).thenReturn("arn:ep");
when(runtimes.getAgentRuntime(RUNTIME_ID, REGION))
.thenThrow(new AwsException("InternalServerException", "boom", 500));
ObjectNode props = mapper.createObjectNode();
props.put("AgentRuntimeId", RUNTIME_ID);
props.put("Name", "prod");
assertThrows(AwsException.class,
() -> provisioner.provision(resource("AWS::BedrockAgentCore::RuntimeEndpoint"), props, ctx(null)));
verify(runtimes).deleteEndpoint(RUNTIME_ID, "prod", null, REGION);
}
@Test
void rollbackUpdateRestoresAnInPlaceRuntimeChangeAsANewVersion() {
AgentRuntime prior = runtime("one", Map.of("K", "v"));
when(runtimes.getAgentRuntime(RUNTIME_ID, REGION)).thenReturn(prior);
when(runtimes.arn(any(), any(), eq(REGION))).thenReturn(RUNTIME_ARN);
when(runtimes.getTagsByArn(REGION, RUNTIME_ARN)).thenReturn(new HashMap<>(Map.of("team", "agents")));
when(runtimes.updateAgentRuntime(eq(RUNTIME_ID), any(), any(), any(), any(), any(), any(), any(), eq(REGION)))
.thenReturn(prior);
StackResource r = resource("AWS::BedrockAgentCore::Runtime");
r.setPhysicalId(RUNTIME_ID);
// The update drops the environment and the description's value changes; the tag changes too.
provisioner.provision(r, runtimeProps(mapper, "two", "ml"), ctx(RUNTIME_ID));
verify(runtimes).updateAgentRuntime(eq(RUNTIME_ID), any(), any(), eq(ROLE_ARN), eq("two"), eq(Map.of()),
isNull(), isNull(), eq(REGION));
assertTrue(r.getAttributes().containsKey(BedrockAgentCoreCfnProvisioner.IN_PLACE_PRIOR_ATTR));
assertTrue(provisioner.rollbackUpdate(r));
verify(runtimes).updateAgentRuntime(eq(RUNTIME_ID), eq(prior.getAgentRuntimeArtifact()),
eq(prior.getNetworkConfiguration()), eq(ROLE_ARN), eq("one"), eq(Map.of("K", "v")), isNull(), isNull(),
eq(REGION));
verify(runtimes).tagByArn(REGION, RUNTIME_ARN, Map.of("team", "agents"));
assertNull(r.getAttributes().get(BedrockAgentCoreCfnProvisioner.IN_PLACE_PRIOR_ATTR),
"a spent snapshot is removed so a later rollback does not restore stale state");
}
@Test
void anUnchangedRuntimeIsNeitherUpdatedNorSnapshotted() {
AgentRuntime prior = runtime("one", Map.of());
when(runtimes.getAgentRuntime(RUNTIME_ID, REGION)).thenReturn(prior);
when(runtimes.arn(any(), any(), eq(REGION))).thenReturn(RUNTIME_ARN);
when(runtimes.getTagsByArn(REGION, RUNTIME_ARN)).thenReturn(new HashMap<>(Map.of("team", "agents")));
StackResource r = resource("AWS::BedrockAgentCore::Runtime");
r.setPhysicalId(RUNTIME_ID);
provisioner.provision(r, runtimeProps(mapper, "one", "agents"), ctx(RUNTIME_ID));
verify(runtimes, never()).updateAgentRuntime(any(), any(), any(), any(), any(), any(), any(), any(), any());
assertFalse(r.getAttributes().containsKey(BedrockAgentCoreCfnProvisioner.IN_PLACE_PRIOR_ATTR));
assertEquals("1", r.getAttributes().get("AgentRuntimeVersion"));
}
@Test
void aFailedTagReconcileAfterAnInPlaceMemoryUpdateRestoresTheMemoryBeforePropagating() {
Memory prior = memory("one", ROLE_ARN);
when(memories.getByArn(REGION, MEMORY_ARN)).thenReturn(prior);
when(memories.get(MEMORY_ID, REGION)).thenReturn(prior);
when(memories.arn(any(), eq(REGION))).thenReturn(MEMORY_ARN);
when(memories.getTagsByArn(REGION, MEMORY_ARN)).thenReturn(new HashMap<>(Map.of("team", "agents")));
when(memories.update(eq(MEMORY_ID), any(), anyInt(), any(), anyBoolean(), eq(REGION))).thenReturn(prior);
doThrow(new AwsException("ThrottlingException", "slow down", 429))
.when(memories).untagByArn(eq(REGION), eq(MEMORY_ARN), eq(List.of("team")));
ObjectNode props = mapper.createObjectNode();
props.put("Name", "mem");
props.put("EventExpiryDuration", 45);
StackResource r = resource("AWS::BedrockAgentCore::Memory");
r.setPhysicalId(MEMORY_ARN);
assertThrows(AwsException.class, () -> provisioner.provision(r, props, ctx(MEMORY_ARN)));
// The template dropped the description and the role, so the update cleared them; the
// restore puts both back with the prior expiry, before the engine discards this attempt.
verify(memories).update(MEMORY_ID, null, 45, null, true, REGION);
verify(memories).update(MEMORY_ID, "one", 30, ROLE_ARN, true, REGION);
verify(memories).tagByArn(REGION, MEMORY_ARN, Map.of("team", "agents"));
assertFalse(r.getAttributes().containsKey(BedrockAgentCoreCfnProvisioner.IN_PLACE_PRIOR_ATTR));
assertFalse(r.getAttributes().containsKey(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR));
}
@Test
void anOmittedEndpointDescriptionIsClearedThroughTheReplacingUpdate() {
AgentRuntime runtime = runtime(null, Map.of());
AgentRuntimeEndpoint existing = new AgentRuntimeEndpoint();
existing.setName("prod");
existing.setUuid("ep-uuid");
existing.setTargetVersion("1");
existing.setLiveVersion("1");
existing.setStatus("READY");
existing.setDescription("old");
existing.setCreatedAt(Instant.EPOCH);
existing.setLastUpdatedAt(Instant.EPOCH);
when(runtimes.findEndpointByArn(REGION, "arn:ep"))
.thenReturn(Optional.of(new BedrockAgentCoreControlService.EndpointLocation(runtime, existing)));
when(runtimes.updateEndpoint(eq(RUNTIME_ID), eq("prod"), any(), any(), anyBoolean(), eq(REGION)))
.thenReturn(existing);
when(runtimes.endpointArn(existing, REGION)).thenReturn("arn:ep");
when(runtimes.arn(any(), anyString(), eq(REGION))).thenReturn(RUNTIME_ARN);
ObjectNode props = mapper.createObjectNode();
props.put("AgentRuntimeId", RUNTIME_ID);
props.put("Name", "prod");
StackResource r = resource("AWS::BedrockAgentCore::RuntimeEndpoint");
r.setPhysicalId("arn:ep");
provisioner.provision(r, props, ctx("arn:ep"));
verify(runtimes).updateEndpoint(RUNTIME_ID, "prod", null, null, true, REGION);
assertEquals("arn:ep", r.getPhysicalId());
}
}