diff --git a/docs/services/bedrock-agentcore.md b/docs/services/bedrock-agentcore.md index a37d1a6c4c..0d60336e10 100644 --- a/docs/services/bedrock-agentcore.md +++ b/docs/services/bedrock-agentcore.md @@ -165,15 +165,57 @@ block is ever produced even when a request supplies `tools`. - `agentRuntimeName` must match `[a-zA-Z][a-zA-Z0-9_]{0,47}` (no hyphens); invalid names return `ValidationException`. - Each `UpdateAgentRuntime` increments the version and preserves prior versions for - `GetAgentRuntime?version=` and `ListAgentRuntimeVersions`. + `GetAgentRuntime?version=` and `ListAgentRuntimeVersions`. As on AWS, the new version holds + exactly the configuration the request carries: an omitted `description`, + `authorizerConfiguration`, `protocolConfiguration` or `environmentVariables` is cleared on + it rather than carried over from the previous version. +- `networkConfiguration.networkMode` must be `PUBLIC` or `VPC` and + `protocolConfiguration.serverProtocol` must be `MCP`, `HTTP`, `A2A` or `AGUI`; anything else returns + the API's `ValidationException`. - Timestamps (`createdAt`, `lastUpdatedAt`) are ISO-8601 strings. -- Config blobs (`agentRuntimeArtifact`, `networkConfiguration`, …) are stored opaquely +- Config blobs (`agentRuntimeArtifact`, `networkConfiguration`, …) are otherwise stored opaquely and echoed back; they are not deeply validated. - `CreateMemory` persists `tags`, `encryptionKeyArn`, and `memoryExecutionRoleArn`; `UpdateMemory` applies `description`, `eventExpiryDuration`, and `memoryExecutionRoleArn`. As in AWS, memory tags are returned only by `ListTagsForResource`, never embedded in the `memory` response shape. +## CloudFormation + +Floci provisions these resource types: + +- `AWS::BedrockAgentCore::Runtime` +- `AWS::BedrockAgentCore::RuntimeEndpoint` +- `AWS::BedrockAgentCore::Memory` + +`Ref` follows each registry schema's `primaryIdentifier`: the runtime's `AgentRuntimeId`, the +endpoint's `AgentRuntimeEndpointArn` and the memory's `MemoryArn`. Every read-only attribute the +schemas declare resolves through `Fn::GetAtt`, including the runtime's nested +`WorkloadIdentityDetails.WorkloadIdentityArn`; `FailureReason` is always empty because the +emulated resources never leave `READY` / `ACTIVE`. Nested configuration objects +(`AgentRuntimeArtifact`, `NetworkConfiguration`, `AuthorizerConfiguration`) are stored in the +API's camelCase shape, so `GetAgentRuntime` returns what the template declared; the template's +string `ProtocolConfiguration` becomes the API's `{"serverProtocol": …}`, and an omitted +`NetworkConfiguration` defaults to `PUBLIC`. + +An update that keeps the create-only properties (the runtime's `AgentRuntimeName`, the endpoint's +`AgentRuntimeId` and `Name`, the memory's `Name` and `EncryptionKeyArn`) is applied in place with a +tag diff; a runtime whose declared configuration did not change keeps its version. The template is +the whole declared configuration: an optional property it no longer carries (a `Description`, the +runtime's `AuthorizerConfiguration`, `ProtocolConfiguration` or `EnvironmentVariables`, the +memory's `MemoryExecutionRoleArn`) is cleared on the resource. A member whose `Fn::If` selects +`AWS::NoValue` inside a nested configuration object is omitted. When a later resource fails the +stack update, an in-place change is rolled back onto the resource (a runtime as a further +version, as on AWS), and a provision that fails after its own change undoes it before the failure +propagates. Changing a create-only property creates a replacement and deletes the displaced +resource once the stack update commits, as on AWS. Deleting the stack deletes the resources. + +Properties the emulated control plane has no model for are accepted and logged once at `WARN` +rather than failing the stack: the runtime's `CapacityProviderConfiguration`, +`FilesystemConfigurations`, `LifecycleConfiguration`, `PlatformVersion` and +`RequestHeaderConfiguration`; the endpoint's `Tags`; and the memory's `MemoryStrategies`, +`IndexedKeys`, `NamespaceKeys` and `StreamDeliveryResources`. + ## Examples ```bash diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.md index 9d3c7003a4..c97f362ffd 100644 --- a/docs/services/cloudformation.md +++ b/docs/services/cloudformation.md @@ -169,6 +169,7 @@ cross-resource references. | CloudWatch Logs | `LogGroup`, `LogStream`, `MetricFilter` | | WAFv2 | `WebACL`, `WebACLAssociation` | | Config | `ConfigRule` | +| Bedrock AgentCore | `Runtime` (Ref returns the AgentRuntimeId; CapacityProviderConfiguration, FilesystemConfigurations, LifecycleConfiguration, PlatformVersion and RequestHeaderConfiguration are accepted and not stored), `RuntimeEndpoint` (Ref returns the endpoint ARN; Tags are accepted and not stored), `Memory` (Ref returns the memory ARN; MemoryStrategies, IndexedKeys, NamespaceKeys and StreamDeliveryResources are accepted and not stored) | | CloudFormation | `CustomResource`, `Custom::DynamoDBReplica` (applied natively against DynamoDB, not via a provider Lambda), `Stack` (nested stacks), `Custom::*` (Lambda-backed) | | CloudTrail | `Trail` | | CDK | `CDK::Metadata` (accepted; no-op) | diff --git a/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreControlService.java b/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreControlService.java index f0e719b430..36dc64d505 100644 --- a/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreControlService.java +++ b/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreControlService.java @@ -40,6 +40,8 @@ public class BedrockAgentCoreControlService { static final String STATUS_DELETING = "DELETING"; private static final String ARN_SERVICE = "bedrock-agentcore"; private static final Pattern NAME_PATTERN = Pattern.compile("[a-zA-Z][a-zA-Z0-9_]{0,47}"); + private static final List NETWORK_MODES = List.of("PUBLIC", "VPC"); + private static final List SERVER_PROTOCOLS = List.of("MCP", "HTTP", "A2A", "AGUI"); private static final String ID_ALPHABET = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; private static final int MAX_PAGE = 100; @@ -103,6 +105,7 @@ public class BedrockAgentCoreControlService { if (roleArn == null || roleArn.isBlank()) { throw new AwsException("ValidationException", "roleArn is required", 400); } + validateConfiguration(networkConfiguration, protocolConfiguration); Instant now = Instant.now(); String id = name + "-" + randomId(); @@ -157,6 +160,11 @@ public class BedrockAgentCoreControlService { "AgentCore runtime version not found: " + wanted, 404)); } + /** + * UpdateAgentRuntime is a PUT that publishes a new version holding exactly the configuration + * the request carries, so an omitted (null) description, authorizer, protocol or environment + * is cleared on the new version rather than carried over from the previous one. + */ public AgentRuntime updateAgentRuntime(String id, JsonNode artifact, JsonNode networkConfiguration, String roleArn, String description, Map environmentVariables, JsonNode authorizerConfiguration, JsonNode protocolConfiguration, @@ -170,6 +178,7 @@ public class BedrockAgentCoreControlService { if (roleArn == null || roleArn.isBlank()) { throw new AwsException("ValidationException", "roleArn is required", 400); } + validateConfiguration(networkConfiguration, protocolConfiguration); AgentRuntime runtime = getAgentRuntime(id, region); Instant now = Instant.now(); @@ -179,15 +188,9 @@ public class BedrockAgentCoreControlService { runtime.setDescription(description); runtime.setAgentRuntimeArtifact(artifact); runtime.setNetworkConfiguration(networkConfiguration); - if (authorizerConfiguration != null) { - runtime.setAuthorizerConfiguration(authorizerConfiguration); - } - if (protocolConfiguration != null) { - runtime.setProtocolConfiguration(protocolConfiguration); - } - if (environmentVariables != null) { - runtime.setEnvironmentVariables(new HashMap<>(environmentVariables)); - } + runtime.setAuthorizerConfiguration(authorizerConfiguration); + runtime.setProtocolConfiguration(protocolConfiguration); + runtime.setEnvironmentVariables(environmentVariables != null ? new HashMap<>(environmentVariables) : new HashMap<>()); runtime.setLastUpdatedAt(now); runtime.getVersions().add(snapshot(runtime, String.valueOf(newVersion), now)); @@ -196,6 +199,30 @@ public class BedrockAgentCoreControlService { return runtime; } + /** + * The enum members of a runtime's network and protocol configuration, rejected with the API's + * ValidationException wording. The artifact and the rest of each blob stay opaque. + */ + private static void validateConfiguration(JsonNode networkConfiguration, JsonNode protocolConfiguration) { + requireEnum(networkConfiguration.path("networkMode"), "networkConfiguration.networkMode", NETWORK_MODES); + if (protocolConfiguration != null && !protocolConfiguration.isNull()) { + requireEnum(protocolConfiguration.path("serverProtocol"), "protocolConfiguration.serverProtocol", + SERVER_PROTOCOLS); + } + } + + private static void requireEnum(JsonNode value, String member, List allowed) { + if (value.isMissingNode() || value.isNull()) { + throw new AwsException("ValidationException", member + " is required", 400); + } + if (!value.isTextual() || !allowed.contains(value.asText())) { + throw new AwsException("ValidationException", + "1 validation error detected: Value '" + value.asText() + "' at '" + member + + "' failed to satisfy constraint: Member must satisfy enum value set: " + + allowed, 400); + } + } + public AgentRuntime deleteAgentRuntime(String id, String clientToken, String region) { Optional found = storage.get(key(region, id)); if (found.isEmpty()) { @@ -269,22 +296,23 @@ public class BedrockAgentCoreControlService { // ──────────────────────────── Tagging (Phase 4) ──────────────────────────── public Map getTagsByArn(String region, String arn) { - return new HashMap<>(findByArn(region, arn).getTags()); + return new HashMap<>(getAgentRuntimeByArn(region, arn).getTags()); } public void tagByArn(String region, String arn, Map tags) { - AgentRuntime runtime = findByArn(region, arn); + AgentRuntime runtime = getAgentRuntimeByArn(region, arn); runtime.getTags().putAll(tags); storage.put(key(region, runtime.getAgentRuntimeId()), runtime); } public void untagByArn(String region, String arn, List keys) { - AgentRuntime runtime = findByArn(region, arn); + AgentRuntime runtime = getAgentRuntimeByArn(region, arn); keys.forEach(runtime.getTags()::remove); storage.put(key(region, runtime.getAgentRuntimeId()), runtime); } - private AgentRuntime findByArn(String region, String arn) { + /** The runtime a runtime ARN names, at any version; ResourceNotFoundException when none does. */ + public AgentRuntime getAgentRuntimeByArn(String region, String arn) { String uuid = uuidFromArn(arn); String prefix = keyPrefix(region); return storage.scan(k -> k.startsWith(prefix)).stream() @@ -341,8 +369,20 @@ public class BedrockAgentCoreControlService { return findEndpoint(runtime, name); } + /** UpdateAgentRuntimeEndpoint on the API: a null version or description is left as it is. */ public AgentRuntimeEndpoint updateEndpoint(String runtimeId, String name, String agentRuntimeVersion, String description, String region) { + return updateEndpoint(runtimeId, name, agentRuntimeVersion, description, false, region); + } + + /** + * Updates an endpoint from arguments that are its whole declared configuration when + * {@code replaceOmitted} is true: a null description then clears the stored one, which the API + * call leaves alone. A null version keeps the endpoint on the version it serves either way, as + * UpdateAgentRuntimeEndpoint does. + */ + public AgentRuntimeEndpoint updateEndpoint(String runtimeId, String name, String agentRuntimeVersion, + String description, boolean replaceOmitted, String region) { AgentRuntime runtime = getAgentRuntime(runtimeId, region); AgentRuntimeEndpoint endpoint = findEndpoint(runtime, name); if (agentRuntimeVersion != null) { @@ -350,7 +390,7 @@ public class BedrockAgentCoreControlService { endpoint.setTargetVersion(agentRuntimeVersion); endpoint.setLiveVersion(agentRuntimeVersion); } - if (description != null) { + if (description != null || replaceOmitted) { endpoint.setDescription(description); } endpoint.setLastUpdatedAt(Instant.now()); @@ -402,6 +442,32 @@ public class BedrockAgentCoreControlService { MAX_PAGE, "ValidationException"); } + /** An endpoint together with the runtime that holds it. */ + public record EndpointLocation(AgentRuntime runtime, AgentRuntimeEndpoint endpoint) { + } + + /** + * The endpoint an endpoint ARN ({@code agentEndpoint/}) names, with its runtime, or empty + * when no runtime in the region holds it. Endpoints are addressed by runtime id and name on the + * API, so this is the only way back from the ARN CloudFormation keeps as the physical id. + */ + public Optional findEndpointByArn(String region, String arn) { + String[] parts = arn == null ? new String[0] : arn.split(":"); + if (parts.length < 6 || !parts[5].startsWith("agentEndpoint/")) { + return Optional.empty(); + } + String uuid = parts[5].substring("agentEndpoint/".length()); + String prefix = keyPrefix(region); + for (AgentRuntime runtime : storage.scan(k -> k.startsWith(prefix))) { + for (AgentRuntimeEndpoint endpoint : runtime.getEndpoints()) { + if (uuid.equals(endpoint.getUuid())) { + return Optional.of(new EndpointLocation(runtime, endpoint)); + } + } + } + return Optional.empty(); + } + private AgentRuntimeEndpoint findEndpoint(AgentRuntime runtime, String name) { return runtime.getEndpoints().stream() .filter(e -> e.getName().equals(name)) diff --git a/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreMemoryService.java b/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreMemoryService.java index 8bd6779ad8..cc237178b9 100644 --- a/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreMemoryService.java +++ b/src/main/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreMemoryService.java @@ -97,21 +97,32 @@ public class BedrockAgentCoreMemoryService { "Memory not found: " + id, 404)); } + /** UpdateMemory on the API: a null field is left as it is, as on AWS. */ public Memory update(String id, String description, Integer eventExpiryDuration, String memoryExecutionRoleArn, String region) { + return update(id, description, eventExpiryDuration, memoryExecutionRoleArn, false, region); + } + + /** + * Updates a memory from arguments that are its whole declared configuration when + * {@code replaceOmitted} is true: a null description or execution role then clears the stored + * one, which the API call leaves alone. + */ + public Memory update(String id, String description, Integer eventExpiryDuration, + String memoryExecutionRoleArn, boolean replaceOmitted, String region) { // Validate all inputs before mutating: get() returns the live stored object, // so a throw after the first setter would leave a partially applied update. if (eventExpiryDuration != null) { validateExpiry(eventExpiryDuration); } Memory memory = get(id, region); - if (description != null) { + if (description != null || replaceOmitted) { memory.setDescription(description); } if (eventExpiryDuration != null) { memory.setEventExpiryDuration(eventExpiryDuration); } - if (memoryExecutionRoleArn != null) { + if (memoryExecutionRoleArn != null || replaceOmitted) { memory.setMemoryExecutionRoleArn(memoryExecutionRoleArn); } memory.setUpdatedAt(Instant.now()); @@ -158,22 +169,23 @@ public class BedrockAgentCoreMemoryService { // ── Tagging ── public Map getTagsByArn(String region, String arn) { - return new HashMap<>(findByArn(region, arn).getTags()); + return new HashMap<>(getByArn(region, arn).getTags()); } public void tagByArn(String region, String arn, Map tags) { - Memory memory = findByArn(region, arn); + Memory memory = getByArn(region, arn); memory.getTags().putAll(tags); storage.put(key(region, memory.getMemoryId()), memory); } public void untagByArn(String region, String arn, List keys) { - Memory memory = findByArn(region, arn); + Memory memory = getByArn(region, arn); keys.forEach(memory.getTags()::remove); storage.put(key(region, memory.getMemoryId()), memory); } - private Memory findByArn(String region, String arn) { + /** The memory a memory ARN names; ValidationException for any other ARN, ResourceNotFoundException when gone. */ + public Memory getByArn(String region, String arn) { String[] parts = arn == null ? new String[0] : arn.split(":"); if (parts.length < 6 || !parts[5].startsWith("memory/")) { throw new AwsException("ValidationException", "Unsupported resource ARN: " + arn, 400); diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/BedrockAgentCoreCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/BedrockAgentCoreCfnProvisioner.java new file mode 100644 index 0000000000..fcb1c013e9 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/BedrockAgentCoreCfnProvisioner.java @@ -0,0 +1,635 @@ +package io.github.hectorvent.floci.services.cloudformation.provisioners; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.JsonNodeFactory; +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.BedrockAgentCoreControlService.EndpointLocation; +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.model.StackResource; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import org.jboss.logging.Logger; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +/** + * CloudFormation provisioning for the Amazon Bedrock AgentCore control plane: + * {@code AWS::BedrockAgentCore::Runtime}, {@code AWS::BedrockAgentCore::RuntimeEndpoint} and + * {@code AWS::BedrockAgentCore::Memory}. + * + *

Physical ids and {@code Ref} follow each registry schema's {@code primaryIdentifier}: the + * runtime's {@code AgentRuntimeId}, the endpoint's {@code AgentRuntimeEndpointArn} and the + * memory's {@code MemoryArn}. The template reference prose says the runtime's {@code Ref} is its + * ARN, but the schema (and CDK's generated {@code RuntimeReference}) identify a runtime by id, and + * the schema is what CloudFormation resolves against. Every top-level read-only property each + * schema declares is published for {@code Fn::GetAtt}; the runtime's nested + * {@code WorkloadIdentityDetails} is published in the dotted form GetAtt addresses it by. + * + *

An update whose create-only properties are unchanged (the runtime's name; the endpoint's + * runtime id and name; the memory's name and encryption key) is applied in place through the + * service's update call and a tag diff, so the physical id survives as it does on AWS. The + * template is the whole declared configuration: a property it no longer carries is cleared on the + * entity, not left over from the previous update. What the in-place update changes is snapshotted + * first (see {@link #IN_PLACE_PRIOR_ATTR}) so a stack rollback, or this provision failing after + * the change, puts the entity back. Any create-only change creates the replacement and leaves the + * displaced entity to the {@link ReplacementCleanup} record, deleted once the stack update commits. + * + *

Template properties the emulated service has no model for are accepted and logged once at + * warn, by name, rather than failing the stack; the template is still valid CloudFormation. + */ +@ApplicationScoped +public class BedrockAgentCoreCfnProvisioner implements CfnResourceProvisioner { + + private static final Logger LOG = Logger.getLogger(BedrockAgentCoreCfnProvisioner.class); + + private static final String RUNTIME = "AWS::BedrockAgentCore::Runtime"; + private static final String RUNTIME_ENDPOINT = "AWS::BedrockAgentCore::RuntimeEndpoint"; + private static final String MEMORY = "AWS::BedrockAgentCore::Memory"; + + /** + * Template properties the backing service does not store. The runtime's capacity provider, + * filesystems, lifecycle, platform version and request-header allowlist, and the memory's + * strategies, indexed keys, namespace keys and stream delivery have no representation in the + * emulated control plane; the endpoint model carries no tags. + */ + private static final Set RUNTIME_NOT_STORED = Set.of("CapacityProviderConfiguration", + "FilesystemConfigurations", "LifecycleConfiguration", "PlatformVersion", "RequestHeaderConfiguration"); + private static final Set RUNTIME_ENDPOINT_NOT_STORED = Set.of("Tags"); + private static final Set MEMORY_NOT_STORED = Set.of("IndexedKeys", "MemoryStrategies", + "NamespaceKeys", "StreamDeliveryResources"); + private static final Set WARNED_NOT_STORED = ConcurrentHashMap.newKeySet(); + + /** + * The API requires a network configuration; the template does not. CloudFormation fills in the + * public mode AWS documents as the default + * (https://docs.aws.amazon.com/bedrock-agentcore-control/latest/APIReference/API_NetworkConfiguration.html). + */ + private static final String DEFAULT_NETWORK_MODE = "PUBLIC"; + + /** + * What an in-place update changed on a reused entity, recorded before the change so a stack + * rollback can put it back: the runtime's configuration and tags, the endpoint's target version + * and description, the memory's mutable properties and tags. Internal, like the other + * {@code __Floci} attributes. + */ + static final String IN_PLACE_PRIOR_ATTR = "__FlociBedrockAgentCorePrior"; + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private final BedrockAgentCoreControlService runtimeService; + private final BedrockAgentCoreMemoryService memoryService; + + @Inject + public BedrockAgentCoreCfnProvisioner(BedrockAgentCoreControlService runtimeService, + BedrockAgentCoreMemoryService memoryService) { + this.runtimeService = runtimeService; + this.memoryService = memoryService; + } + + @Override + public Set resourceTypes() { + return Set.of(RUNTIME, RUNTIME_ENDPOINT, MEMORY); + } + + @Override + public void provision(StackResource r, JsonNode props, ProvisionContext ctx) { + Map attributesBefore = Map.copyOf(r.getAttributes()); + switch (r.getResourceType()) { + case RUNTIME -> provisionRuntime(r, props, ctx); + case RUNTIME_ENDPOINT -> provisionRuntimeEndpoint(r, props, ctx); + case MEMORY -> provisionMemory(r, props, ctx); + default -> throw new AwsException("ValidationError", + "Unsupported resource type: " + r.getResourceType(), 400); + } + ReplacementCleanup.record(r, ctx, attributesBefore); + } + + // ──────────────────────────── Runtime ──────────────────────────── + + private void provisionRuntime(StackResource r, JsonNode props, ProvisionContext ctx) { + String region = ctx.region(); + String name = required(props, "AgentRuntimeName", ctx, RUNTIME); + String roleArn = required(props, "RoleArn", ctx, RUNTIME); + JsonNode artifact = apiShape(props, "AgentRuntimeArtifact", ctx); + if (artifact == null) { + throw new AwsException("ValidationError", RUNTIME + " requires AgentRuntimeArtifact", 400); + } + JsonNode network = apiShape(props, "NetworkConfiguration", ctx); + if (network == null) { + network = JsonNodeFactory.instance.objectNode().put("networkMode", DEFAULT_NETWORK_MODE); + } + String description = ctx.resolveOrDefault(props, "Description", null); + Map environment = resolveStringMap(props, "EnvironmentVariables", ctx); + JsonNode authorizer = apiShape(props, "AuthorizerConfiguration", ctx); + // The template's ProtocolConfiguration is the bare protocol enum; the API wraps it. + String protocol = ctx.resolveOrDefault(props, "ProtocolConfiguration", null); + JsonNode protocolConfiguration = protocol == null ? null + : JsonNodeFactory.instance.objectNode().put("serverProtocol", protocol); + Map tags = ctx.resolveTags(props, "Tags"); + warnNotStored(RUNTIME, props, RUNTIME_NOT_STORED); + + AgentRuntime prior = ctx.isUpdate() ? findRuntime(ctx.priorPhysicalId(), region) : null; + if (prior != null && name.equals(prior.getAgentRuntimeName())) { + // Every UpdateAgentRuntime publishes a new version, as on AWS, so an UpdateStack that + // left this runtime alone must not call it and bump the version for nothing. + boolean configurationChanged = !(Objects.equals(roleArn, prior.getRoleArn()) + && Objects.equals(description, prior.getDescription()) + && artifact.equals(prior.getAgentRuntimeArtifact()) + && network.equals(prior.getNetworkConfiguration()) + && Objects.equals(authorizer, prior.getAuthorizerConfiguration()) + && Objects.equals(protocolConfiguration, prior.getProtocolConfiguration()) + && environment.equals(prior.getEnvironmentVariables())); + String arn = runtimeService.arn(prior, String.valueOf(prior.getLatestVersion()), region); + Map priorTags = runtimeService.getTagsByArn(region, arn); + if (configurationChanged || !priorTags.equals(tags)) { + ObjectNode snapshot = inPlacePrior(prior.getAgentRuntimeId(), region); + if (configurationChanged) { + ObjectNode configuration = snapshot.putObject("runtime"); + configuration.put("roleArn", prior.getRoleArn()); + configuration.put("description", prior.getDescription()); + configuration.set("artifact", prior.getAgentRuntimeArtifact()); + configuration.set("network", prior.getNetworkConfiguration()); + configuration.set("authorizer", prior.getAuthorizerConfiguration()); + configuration.set("protocol", prior.getProtocolConfiguration()); + configuration.set("environment", MAPPER.valueToTree(prior.getEnvironmentVariables())); + } + snapshot.set("tags", MAPPER.valueToTree(priorTags)); + writeInPlacePrior(r, snapshot); + } + JsonNode finalNetwork = network; + CfnRollback.guarded(r, ctx, false, () -> { }, () -> undoInPlace(r), () -> { + AgentRuntime runtime = configurationChanged + ? runtimeService.updateAgentRuntime(prior.getAgentRuntimeId(), artifact, finalNetwork, roleArn, + description, environment, authorizer, protocolConfiguration, region) + : prior; + reconcileRuntimeTags(arn, tags, region); + publishRuntime(r, runtime, region); + }); + } else { + AgentRuntime runtime = runtimeService.createAgentRuntime(name, artifact, network, roleArn, description, + environment, authorizer, protocolConfiguration, null, region); + publishRuntime(r, runtime, region); + CfnRollback.guarded(r, ctx, true, + () -> runtimeService.deleteAgentRuntime(runtime.getAgentRuntimeId(), null, region), + () -> undoInPlace(r), () -> { + if (!tags.isEmpty()) { + runtimeService.tagByArn(region, r.getAttributes().get("AgentRuntimeArn"), tags); + } + }); + } + } + + private void reconcileRuntimeTags(String arn, Map desired, String region) { + List stale = ProvisionContext.staleTagKeys(runtimeService.getTagsByArn(region, arn), desired); + if (!stale.isEmpty()) { + runtimeService.untagByArn(region, arn, stale); + } + if (!desired.isEmpty()) { + runtimeService.tagByArn(region, arn, desired); + } + } + + private void publishRuntime(StackResource r, AgentRuntime runtime, String region) { + String version = String.valueOf(runtime.getLatestVersion()); + r.setPhysicalId(runtime.getAgentRuntimeId()); + r.getAttributes().put("AgentRuntimeArn", runtimeService.arn(runtime, version, region)); + r.getAttributes().put("AgentRuntimeId", runtime.getAgentRuntimeId()); + r.getAttributes().put("AgentRuntimeVersion", version); + r.getAttributes().put("Status", runtime.getStatus()); + r.getAttributes().put("CreatedAt", runtime.getCreatedAt().toString()); + r.getAttributes().put("LastUpdatedAt", runtime.getLastUpdatedAt().toString()); + // The emulated runtime is READY from creation, so there is never a failure to report. + r.getAttributes().put("FailureReason", ""); + r.getAttributes().put("WorkloadIdentityDetails.WorkloadIdentityArn", runtime.getWorkloadIdentityArn()); + } + + /** The runtime a prior physical id names, or null when it names none (gone, or a dispatcher stub). */ + private AgentRuntime findRuntime(String agentRuntimeId, String region) { + try { + return runtimeService.getAgentRuntime(agentRuntimeId, region); + } catch (AwsException e) { + if ("ResourceNotFoundException".equals(e.getErrorCode())) { + return null; + } + throw e; + } + } + + // ──────────────────────────── RuntimeEndpoint ──────────────────────────── + + private void provisionRuntimeEndpoint(StackResource r, JsonNode props, ProvisionContext ctx) { + String region = ctx.region(); + String runtimeId = required(props, "AgentRuntimeId", ctx, RUNTIME_ENDPOINT); + String name = required(props, "Name", ctx, RUNTIME_ENDPOINT); + String version = ctx.resolveOrDefault(props, "AgentRuntimeVersion", null); + String description = ctx.resolveOrDefault(props, "Description", null); + warnNotStored(RUNTIME_ENDPOINT, props, RUNTIME_ENDPOINT_NOT_STORED); + + EndpointLocation prior = ctx.isUpdate() + ? runtimeService.findEndpointByArn(region, ctx.priorPhysicalId()).orElse(null) + : null; + if (prior != null && runtimeId.equals(prior.runtime().getAgentRuntimeId()) + && name.equals(prior.endpoint().getName())) { + AgentRuntimeEndpoint existing = prior.endpoint(); + // An omitted version leaves the endpoint on the version it serves, as UpdateAgentRuntimeEndpoint does. + boolean unchanged = (version == null || version.equals(existing.getTargetVersion())) + && Objects.equals(description, existing.getDescription()); + if (unchanged) { + publishRuntimeEndpoint(r, prior.runtime(), existing, region); + return; + } + ObjectNode snapshot = inPlacePrior(runtimeId, region); + ObjectNode endpointPrior = snapshot.putObject("endpoint"); + endpointPrior.put("name", name); + endpointPrior.put("targetVersion", existing.getTargetVersion()); + endpointPrior.put("description", existing.getDescription()); + writeInPlacePrior(r, snapshot); + CfnRollback.guarded(r, ctx, false, () -> { }, () -> undoInPlace(r), + () -> publishRuntimeEndpoint(r, prior.runtime(), + runtimeService.updateEndpoint(runtimeId, name, version, description, true, region), region)); + } else { + AgentRuntimeEndpoint endpoint = runtimeService.createEndpoint(runtimeId, name, version, description, + null, region); + r.setPhysicalId(runtimeService.endpointArn(endpoint, region)); + CfnRollback.guarded(r, ctx, true, () -> runtimeService.deleteEndpoint(runtimeId, name, null, region), + () -> undoInPlace(r), + () -> publishRuntimeEndpoint(r, runtimeService.getAgentRuntime(runtimeId, region), endpoint, region)); + } + } + + private void publishRuntimeEndpoint(StackResource r, AgentRuntime runtime, AgentRuntimeEndpoint endpoint, + String region) { + String endpointArn = runtimeService.endpointArn(endpoint, region); + r.setPhysicalId(endpointArn); + r.getAttributes().put("AgentRuntimeEndpointArn", endpointArn); + r.getAttributes().put("AgentRuntimeArn", runtimeService.arn(runtime, endpoint.getTargetVersion(), region)); + r.getAttributes().put("Id", endpoint.getUuid()); + r.getAttributes().put("Status", endpoint.getStatus()); + r.getAttributes().put("TargetVersion", endpoint.getTargetVersion()); + r.getAttributes().put("LiveVersion", endpoint.getLiveVersion()); + r.getAttributes().put("CreatedAt", endpoint.getCreatedAt().toString()); + r.getAttributes().put("LastUpdatedAt", endpoint.getLastUpdatedAt().toString()); + // The emulated endpoint is READY from creation, so there is never a failure to report. + r.getAttributes().put("FailureReason", ""); + } + + // ──────────────────────────── Memory ──────────────────────────── + + private void provisionMemory(StackResource r, JsonNode props, ProvisionContext ctx) { + String region = ctx.region(); + String name = required(props, "Name", ctx, MEMORY); + Integer eventExpiryDuration = eventExpiryDuration(props, ctx); + String description = ctx.resolveOrDefault(props, "Description", null); + String encryptionKeyArn = ctx.resolveOrDefault(props, "EncryptionKeyArn", null); + String executionRoleArn = ctx.resolveOrDefault(props, "MemoryExecutionRoleArn", null); + Map tags = ctx.resolveTags(props, "Tags"); + warnNotStored(MEMORY, props, MEMORY_NOT_STORED); + + Memory prior = ctx.isUpdate() ? findMemory(ctx.priorPhysicalId(), region) : null; + if (prior != null && name.equals(prior.getName()) + && Objects.equals(encryptionKeyArn, prior.getEncryptionKeyArn())) { + boolean configurationChanged = !(Objects.equals(description, prior.getDescription()) + && eventExpiryDuration.equals(prior.getEventExpiryDuration()) + && Objects.equals(executionRoleArn, prior.getMemoryExecutionRoleArn())); + String arn = memoryService.arn(prior, region); + Map priorTags = memoryService.getTagsByArn(region, arn); + if (configurationChanged || !priorTags.equals(tags)) { + ObjectNode snapshot = inPlacePrior(prior.getMemoryId(), region); + if (configurationChanged) { + ObjectNode configuration = snapshot.putObject("memory"); + configuration.put("description", prior.getDescription()); + configuration.put("eventExpiryDuration", prior.getEventExpiryDuration()); + configuration.put("memoryExecutionRoleArn", prior.getMemoryExecutionRoleArn()); + } + snapshot.set("tags", MAPPER.valueToTree(priorTags)); + writeInPlacePrior(r, snapshot); + } + CfnRollback.guarded(r, ctx, false, () -> { }, () -> undoInPlace(r), () -> { + Memory memory = configurationChanged + ? memoryService.update(prior.getMemoryId(), description, eventExpiryDuration, + executionRoleArn, true, region) + : prior; + reconcileMemoryTags(arn, tags, region); + publishMemory(r, memory, region); + }); + } else { + // CreateMemory stores the tags with the memory, so there is no step after it to undo. + publishMemory(r, memoryService.create(name, eventExpiryDuration, description, encryptionKeyArn, + executionRoleArn, tags, null, region), region); + } + } + + private void reconcileMemoryTags(String arn, Map desired, String region) { + List stale = ProvisionContext.staleTagKeys(memoryService.getTagsByArn(region, arn), desired); + if (!stale.isEmpty()) { + memoryService.untagByArn(region, arn, stale); + } + if (!desired.isEmpty()) { + memoryService.tagByArn(region, arn, desired); + } + } + + private void publishMemory(StackResource r, Memory memory, String region) { + String arn = memoryService.arn(memory, region); + r.setPhysicalId(arn); + r.getAttributes().put("MemoryArn", arn); + r.getAttributes().put("MemoryId", memory.getMemoryId()); + r.getAttributes().put("Status", memory.getStatus()); + r.getAttributes().put("CreatedAt", memory.getCreatedAt().toString()); + r.getAttributes().put("UpdatedAt", memory.getUpdatedAt().toString()); + // The emulated memory is ACTIVE from creation, so there is never a failure to report. + r.getAttributes().put("FailureReason", ""); + } + + /** The memory a prior physical id names, or null when it names none (gone, or a dispatcher stub). */ + private Memory findMemory(String arn, String region) { + if (!arn.startsWith("arn:")) { + return null; + } + try { + return memoryService.getByArn(region, arn); + } catch (AwsException e) { + if ("ResourceNotFoundException".equals(e.getErrorCode())) { + return null; + } + throw e; + } + } + + private static Integer eventExpiryDuration(JsonNode props, ProvisionContext ctx) { + String raw = required(props, "EventExpiryDuration", ctx, MEMORY); + try { + return Integer.valueOf(raw.trim()); + } catch (NumberFormatException e) { + throw new AwsException("ValidationError", + MEMORY + " EventExpiryDuration must be an integer, got " + raw, 400); + } + } + + // ──────────────────────────── Delete ──────────────────────────── + + @Override + public void delete(String resourceType, String physicalId, String region) { + if (physicalId == null || physicalId.isBlank()) { + return; + } + switch (resourceType) { + case RUNTIME -> CfnDeletes.safeDelete("AgentCore runtime", physicalId, + () -> runtimeService.deleteAgentRuntime(physicalId, null, region), + "ResourceNotFoundException"); + case RUNTIME_ENDPOINT -> runtimeService.findEndpointByArn(region, physicalId).ifPresentOrElse( + location -> CfnDeletes.safeDelete("AgentCore runtime endpoint", physicalId, + () -> runtimeService.deleteEndpoint(location.runtime().getAgentRuntimeId(), + location.endpoint().getName(), null, region), + "ResourceNotFoundException"), + () -> LOG.debugv("AgentCore runtime endpoint already gone, treating as deleted: {0}", + physicalId)); + case MEMORY -> { + // A dispatcher stub from before this provisioner existed is not an ARN and names no memory. + if (!physicalId.startsWith("arn:")) { + return; + } + CfnDeletes.safeDelete("AgentCore memory", physicalId, + () -> memoryService.delete(memoryService.getByArn(region, physicalId).getMemoryId(), + null, region), + "ResourceNotFoundException"); + } + default -> throw new AwsException("ValidationError", + "Unsupported resource type: " + resourceType, 400); + } + } + + // ──────────────────────────── Update lifecycle ──────────────────────────── + + @Override + public boolean hasReplacementUpdate(StackResource resource) { + return ReplacementCleanup.hasReplacement(resource); + } + + @Override + public String updateCleanupPhysicalId(StackResource resource) { + return ReplacementCleanup.cleanupPhysicalId(resource); + } + + @Override + public UpdateCleanupResult completeUpdate(StackResource resource) { + resource.getAttributes().remove(IN_PLACE_PRIOR_ATTR); + return ReplacementCleanup.complete(resource, this::delete); + } + + @Override + public void clearUpdate(StackResource resource) { + resource.getAttributes().remove(IN_PLACE_PRIOR_ATTR); + ReplacementCleanup.clear(resource); + } + + /** + * A replacement is undone through the cleanup record: the displaced entity was never touched. + * A reused entity the update changed in place is put back from the snapshot taken before the + * change, which is spent only once the restore succeeded so a restore that throws is reported + * rather than claimed. Without either, the update changed nothing about the entity. A provision + * that fails mid-way restores its own snapshot before the failure propagates (see + * {@link #guarded}), because the engine discards the attempted resource, snapshot included. + */ + @Override + public boolean rollbackUpdate(StackResource resource) { + if (ReplacementCleanup.rollback(resource, this::delete)) { + resource.getAttributes().remove(IN_PLACE_PRIOR_ATTR); + return true; + } + String snapshot = resource.getAttributes().get(IN_PLACE_PRIOR_ATTR); + if (snapshot != null) { + restoreInPlace(resource, snapshot); + resource.getAttributes().remove(IN_PLACE_PRIOR_ATTR); + } + return true; + } + + /** + * Puts the entity back the way the snapshot recorded it, through the same service calls the + * update used, and republishes the resource's attributes from the entity as it now stands: a + * restored runtime is a new version, as it would be on AWS. + */ + private void restoreInPlace(StackResource resource, String snapshot) { + ObjectNode prior = readSnapshot(resource, snapshot); + String region = prior.path("region").asText(); + String entityId = prior.path("entityId").asText(); + switch (resource.getResourceType()) { + case RUNTIME -> { + AgentRuntime runtime = runtimeService.getAgentRuntime(entityId, region); + if (prior.has("runtime")) { + ObjectNode configuration = (ObjectNode) prior.get("runtime"); + runtime = runtimeService.updateAgentRuntime(entityId, configuration.get("artifact"), + configuration.get("network"), text(configuration, "roleArn"), + text(configuration, "description"), stringMap(configuration.get("environment")), + node(configuration, "authorizer"), node(configuration, "protocol"), region); + } + if (prior.has("tags")) { + reconcileRuntimeTags(runtimeService.arn(runtime, String.valueOf(runtime.getLatestVersion()), region), + stringMap(prior.get("tags")), region); + } + publishRuntime(resource, runtime, region); + } + case RUNTIME_ENDPOINT -> { + ObjectNode endpointPrior = (ObjectNode) prior.get("endpoint"); + AgentRuntimeEndpoint endpoint = runtimeService.updateEndpoint(entityId, text(endpointPrior, "name"), + text(endpointPrior, "targetVersion"), text(endpointPrior, "description"), true, region); + publishRuntimeEndpoint(resource, runtimeService.getAgentRuntime(entityId, region), endpoint, region); + } + case MEMORY -> { + Memory memory = memoryService.get(entityId, region); + if (prior.has("memory")) { + ObjectNode configuration = (ObjectNode) prior.get("memory"); + memory = memoryService.update(entityId, text(configuration, "description"), + configuration.get("eventExpiryDuration").asInt(), + text(configuration, "memoryExecutionRoleArn"), true, region); + } + if (prior.has("tags")) { + reconcileMemoryTags(memoryService.arn(memory, region), stringMap(prior.get("tags")), region); + } + publishMemory(resource, memory, region); + } + default -> throw new IllegalStateException("No in-place restore for " + resource.getResourceType()); + } + } + + /** + * A fresh snapshot for this resource. Each provision changes one entity in one go, so the + * snapshot is written once, before the change, with the entity's state as it stands now. + */ + private static ObjectNode inPlacePrior(String entityId, String region) { + ObjectNode node = MAPPER.createObjectNode(); + node.put("region", region); + node.put("entityId", entityId); + return node; + } + + private static void writeInPlacePrior(StackResource r, ObjectNode node) { + r.getAttributes().put(IN_PLACE_PRIOR_ATTR, node.toString()); + } + + private static ObjectNode readSnapshot(StackResource r, String snapshot) { + try { + return (ObjectNode) MAPPER.readTree(snapshot); + } catch (JsonProcessingException e) { + throw new IllegalStateException("Unreadable in-place snapshot on " + r.getLogicalId(), e); + } + } + + /** + * The in-place undo handed to {@link CfnRollback#guarded}: puts a reused entity back from its + * snapshot and spends it, leaving it in place when the restore fails so the next rollback can + * retry. + */ + private void undoInPlace(StackResource r) { + String snapshot = r.getAttributes().get(IN_PLACE_PRIOR_ATTR); + if (snapshot != null) { + restoreInPlace(r, snapshot); + r.getAttributes().remove(IN_PLACE_PRIOR_ATTR); + } + } + + // ──────────────────────────── Helpers ──────────────────────────── + + private static String required(JsonNode props, String name, ProvisionContext ctx, String type) { + String value = ctx.resolveOptional(props, name); + if (value == null || value.isBlank()) { + throw new AwsException("ValidationError", type + " requires " + name, 400); + } + return value; + } + + /** + * A resolved object property in the API's camelCase, or null when absent. A member whose + * {@code Fn::If} selects {@code AWS::NoValue} is omitted, as CloudFormation omits it, rather + * than resolved to an empty string. + */ + private static JsonNode apiShape(JsonNode props, String name, ProvisionContext ctx) { + if (props == null || !props.has(name) || props.get(name).isNull()) { + return null; + } + JsonNode resolved = ctx.engine().resolveNodeOmittingNoValue(props.get(name)); + return resolved == null || resolved.isNull() || !resolved.isObject() ? null : toApiShape(resolved); + } + + /** Recursively renames the members of a resolved node to the API's camelCase, dropping nulls. */ + private static JsonNode toApiShape(JsonNode node) { + if (node.isObject()) { + ObjectNode out = JsonNodeFactory.instance.objectNode(); + node.fields().forEachRemaining(field -> { + if (!field.getValue().isNull()) { + out.set(decapitalize(field.getKey()), toApiShape(field.getValue())); + } + }); + return out; + } + if (node.isArray()) { + ArrayNode out = JsonNodeFactory.instance.arrayNode(); + node.forEach(item -> out.add(toApiShape(item))); + return out; + } + return node; + } + + private static String decapitalize(String key) { + return key.isEmpty() ? key : Character.toLowerCase(key.charAt(0)) + key.substring(1); + } + + /** A {@code {key: value}} property with each value resolved, or an empty map when absent. */ + private static Map resolveStringMap(JsonNode props, String name, ProvisionContext ctx) { + Map values = new LinkedHashMap<>(); + if (props == null || !props.has(name)) { + return values; + } + JsonNode resolved = ctx.engine().resolveNodeOmittingNoValue(props.get(name)); + if (resolved != null && resolved.isObject()) { + resolved.fields().forEachRemaining(field -> { + String value = ctx.engine().resolve(field.getValue()); + values.put(field.getKey(), value == null ? "" : value); + }); + } + return values; + } + + /** A snapshot's string map member, as a mutable map. */ + private static Map stringMap(JsonNode node) { + Map values = new LinkedHashMap<>(); + if (node != null && node.isObject()) { + node.fields().forEachRemaining(field -> values.put(field.getKey(), field.getValue().asText())); + } + return values; + } + + private static String text(ObjectNode node, String field) { + return node.hasNonNull(field) ? node.get(field).asText() : null; + } + + private static JsonNode node(ObjectNode node, String field) { + return node.hasNonNull(field) ? node.get(field) : null; + } + + /** Logs, once per property per type, a template property the emulated service cannot store. */ + private static void warnNotStored(String type, JsonNode props, Set notStored) { + if (props == null) { + return; + } + for (String name : notStored) { + if (props.has(name) && !props.get(name).isNull() && WARNED_NOT_STORED.add(type + "." + name)) { + LOG.warnv("{0} {1} is accepted but not stored: the emulated AgentCore control plane " + + "has no model for it.", type, name); + } + } + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnRollback.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnRollback.java index 853dd49614..1d747ad8c3 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnRollback.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnRollback.java @@ -1,5 +1,6 @@ package io.github.hectorvent.floci.services.cloudformation.provisioners; +import io.github.hectorvent.floci.services.cloudformation.model.StackResource; import org.jboss.logging.Logger; /** @@ -238,4 +239,61 @@ public final class CfnRollback { return false; } } + + /** + * Runs the steps that follow a create or change a reused entity in place. If one of them + * throws, what this provision did is undone before the failure propagates: a created entity is + * deleted again by {@code undoCreate}, a reused one is put back by {@code undoInPlace}, which + * restores the provisioner's snapshot and is a no-op when there is none. The engine only removes + * a failed create it can see, and on a failed update it restores the previous resource metadata + * and discards the attempted one, snapshot included, so the undo has to happen here. + * + *

A compensation that fails is reported, never hidden. A created entity carries + * {@link #ROLLBACK_OWNED_ATTR} while the steps run, so the engine's create rollback deletes it + * (and reports that failing) if the undo here could not, and during an update the entity is + * also listed in the cleanup record, which the engine carries onto the restored resource and + * runs before the next committed update or the stack delete; a reused entity keeps its snapshot + * and the reason lands in {@link #UPDATE_ROLLBACK_FAILURE_ATTR}, which the engine copies onto + * the committed resource so the rollback walker reports UPDATE_ROLLBACK_FAILED instead of + * claiming the prior state is live. + */ + public static void guarded(StackResource r, ProvisionContext ctx, boolean created, Runnable undoCreate, + Runnable undoInPlace, Runnable steps) { + if (created) { + r.getAttributes().put(ROLLBACK_OWNED_ATTR, "true"); + } + try { + steps.run(); + r.getAttributes().remove(ROLLBACK_OWNED_ATTR); + } catch (RuntimeException e) { + if (created) { + try { + undoCreate.run(); + r.getAttributes().remove(ROLLBACK_OWNED_ATTR); + } catch (RuntimeException undo) { + e.addSuppressed(undo); + String reason = "Could not remove " + r.getPhysicalId() + ", created for " + r.getLogicalId() + + " by a failed update: " + undo.getMessage(); + LOG.warn(reason); + r.getAttributes().put(UPDATE_ROLLBACK_FAILURE_ATTR, reason); + if (ctx.isUpdate()) { + // The engine restores the previous resource and keeps only what the cleanup + // record carries, so the replacement is listed there for the next cleanup. + ReplacementCleanup.recordOrphan(r, r.getPhysicalId(), r.getResourceType(), ctx.region()); + } + } + } else { + try { + undoInPlace.run(); + } catch (RuntimeException undo) { + e.addSuppressed(undo); + String reason = "Could not restore " + r.getPhysicalId() + " for " + r.getLogicalId() + + " after a failed update: " + undo.getMessage(); + LOG.warn(reason); + r.getAttributes().put(UPDATE_ROLLBACK_FAILURE_ATTR, reason); + } + } + throw e; + } + } } diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2NetworkCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2NetworkCfnProvisioner.java index 9b2f9dec61..0e5cd5c566 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2NetworkCfnProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2NetworkCfnProvisioner.java @@ -411,7 +411,8 @@ public class Ec2NetworkCfnProvisioner implements CfnResourceProvisioner { r.getAttributes().put("SubnetId", subnet.getSubnetId()); r.getAttributes().put("VpcId", subnet.getVpcId()); r.getAttributes().put("AvailabilityZone", subnet.getAvailabilityZone()); - guarded(r, ctx, !reuse, () -> ec2Service.deleteSubnet(ctx.region(), subnet.getSubnetId()), () -> { + CfnRollback.guarded(r, ctx, !reuse, () -> ec2Service.deleteSubnet(ctx.region(), subnet.getSubnetId()), + () -> undoInPlace(r), () -> { applyTags(r, reuse, subnet.getSubnetId(), reuse ? existing.getTags() : List.of(), props, ctx); if (mapPublicIpOnLaunch != null) { if (reuse && ctx.isUpdate() && existing.isMapPublicIpOnLaunch() != Boolean.parseBoolean(mapPublicIpOnLaunch)) { @@ -425,61 +426,15 @@ public class Ec2NetworkCfnProvisioner implements CfnResourceProvisioner { } /** - * Runs the steps that follow an EC2 create or change a reused entity in place. If one of them - * throws, what this provision did is undone before the failure propagates: a created entity is - * deleted again, a reused one is put back from its snapshot. The engine only removes a failed - * create it can see, and on a failed update it restores the previous resource metadata and - * discards the attempted one, snapshot included, so the undo has to happen here. - * - *

A compensation that fails is reported, never hidden. A created entity carries - * {@link CfnRollback#ROLLBACK_OWNED_ATTR} while the steps run, so the engine's create rollback - * deletes it (and reports that failing) if the undo here could not, and during an update the - * entity is also listed in the cleanup record, which the engine carries onto the restored - * resource and runs before the next committed update or the stack delete; a reused entity keeps its - * snapshot and the reason lands in {@link CfnRollback#UPDATE_ROLLBACK_FAILURE_ATTR}, which the - * engine copies onto the committed resource so the rollback walker reports - * UPDATE_ROLLBACK_FAILED instead of claiming the prior state is live. + * The in-place undo handed to {@link CfnRollback#guarded}: puts a reused entity back from its + * snapshot and spends it, leaving it in place when the restore fails so the next rollback can + * retry. */ - private void guarded(StackResource r, ProvisionContext ctx, boolean created, Runnable undoCreate, Runnable steps) { - if (created) { - r.getAttributes().put(CfnRollback.ROLLBACK_OWNED_ATTR, "true"); - } - try { - steps.run(); - r.getAttributes().remove(CfnRollback.ROLLBACK_OWNED_ATTR); - } catch (RuntimeException e) { - if (created) { - try { - undoCreate.run(); - r.getAttributes().remove(CfnRollback.ROLLBACK_OWNED_ATTR); - } catch (RuntimeException undo) { - e.addSuppressed(undo); - String reason = "Could not remove " + r.getPhysicalId() + ", created for " + r.getLogicalId() - + " by a failed update: " + undo.getMessage(); - LOG.warn(reason); - r.getAttributes().put(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR, reason); - if (ctx.isUpdate()) { - // The engine restores the previous resource and keeps only what the cleanup - // record carries, so the replacement is listed there for the next cleanup. - ReplacementCleanup.recordOrphan(r, r.getPhysicalId(), r.getResourceType(), ctx.region()); - } - } - } else { - String snapshot = r.getAttributes().get(IN_PLACE_PRIOR_ATTR); - if (snapshot != null) { - try { - restoreInPlace(r, snapshot); - r.getAttributes().remove(IN_PLACE_PRIOR_ATTR); - } catch (RuntimeException undo) { - e.addSuppressed(undo); - String reason = "Could not restore " + r.getPhysicalId() + " for " + r.getLogicalId() - + " after a failed update: " + undo.getMessage(); - LOG.warn(reason); - r.getAttributes().put(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR, reason); - } - } - } - throw e; + private void undoInPlace(StackResource r) { + String snapshot = r.getAttributes().get(IN_PLACE_PRIOR_ATTR); + if (snapshot != null) { + restoreInPlace(r, snapshot); + r.getAttributes().remove(IN_PLACE_PRIOR_ATTR); } } @@ -488,7 +443,8 @@ public class Ec2NetworkCfnProvisioner implements CfnResourceProvisioner { InternetGateway igw = existing != null ? existing : ec2Service.createInternetGateway(ctx.region()); r.setPhysicalId(igw.getInternetGatewayId()); r.getAttributes().put("InternetGatewayId", igw.getInternetGatewayId()); - guarded(r, ctx, existing == null, () -> ec2Service.deleteInternetGateway(ctx.region(), igw.getInternetGatewayId()), + CfnRollback.guarded(r, ctx, existing == null, + () -> ec2Service.deleteInternetGateway(ctx.region(), igw.getInternetGatewayId()), () -> undoInPlace(r), () -> applyTags(r, existing != null, igw.getInternetGatewayId(), existing != null ? existing.getTags() : List.of(), props, ctx)); } @@ -501,7 +457,8 @@ public class Ec2NetworkCfnProvisioner implements CfnResourceProvisioner { RouteTable rt = reuse ? existing : ec2Service.createRouteTable(ctx.region(), vpcId); r.setPhysicalId(rt.getRouteTableId()); r.getAttributes().put("RouteTableId", rt.getRouteTableId()); - guarded(r, ctx, !reuse, () -> ec2Service.deleteRouteTable(ctx.region(), rt.getRouteTableId()), + CfnRollback.guarded(r, ctx, !reuse, () -> ec2Service.deleteRouteTable(ctx.region(), rt.getRouteTableId()), + () -> undoInPlace(r), () -> applyTags(r, reuse, rt.getRouteTableId(), reuse ? existing.getTags() : List.of(), props, ctx)); } @@ -569,7 +526,7 @@ public class Ec2NetworkCfnProvisioner implements CfnResourceProvisioner { target.put("egressOnlyInternetGatewayId", current.getEgressOnlyInternetGatewayId()); target.put("vpcPeeringConnectionId", current.getVpcPeeringConnectionId()); writeInPlacePrior(r, prior); - guarded(r, ctx, false, () -> { }, () -> { + CfnRollback.guarded(r, ctx, false, () -> { }, () -> undoInPlace(r), () -> { if (egressOnlyInternetGatewayId != null) { // ReplaceRoute has no egress-only target; re-creating the route is the same outcome. ec2Service.deleteRoute(ctx.region(), routeTableId, destinationCidr, destinationIpv6Cidr, destinationPrefixListId); @@ -611,7 +568,7 @@ public class Ec2NetworkCfnProvisioner implements CfnResourceProvisioner { NatGateway nat = reuse ? existing : ec2Service.createNatGateway(ctx.region(), subnetId, allocationId, connectivityType, tagList(props, ctx)); if (reuse) { - guarded(r, ctx, false, () -> { }, () -> applyTags(r, true, nat.getNatGatewayId(), existing.getTags(), props, ctx)); + CfnRollback.guarded(r, ctx, false, () -> { }, () -> undoInPlace(r), () -> applyTags(r, true, nat.getNatGatewayId(), existing.getTags(), props, ctx)); } r.setPhysicalId(nat.getNatGatewayId()); r.getAttributes().put("NatGatewayId", nat.getNatGatewayId()); @@ -626,7 +583,8 @@ public class Ec2NetworkCfnProvisioner implements CfnResourceProvisioner { r.setPhysicalId(addr.getPublicIp()); r.getAttributes().put("AllocationId", addr.getAllocationId()); r.getAttributes().put("PublicIp", addr.getPublicIp()); - guarded(r, ctx, existing == null, () -> ec2Service.releaseAddress(ctx.region(), addr.getAllocationId()), + CfnRollback.guarded(r, ctx, existing == null, + () -> ec2Service.releaseAddress(ctx.region(), addr.getAllocationId()), () -> undoInPlace(r), () -> applyTags(r, existing != null, addr.getAllocationId(), existing != null ? existing.getTags() : List.of(), props, ctx)); } } diff --git a/src/test/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreControlServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreControlServiceTest.java index 7dcf13243b..8dff340732 100644 --- a/src/test/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreControlServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreControlServiceTest.java @@ -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, diff --git a/src/test/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreMemoryServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreMemoryServiceTest.java index 3575dab632..16a76b80cb 100644 --- a/src/test/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreMemoryServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCoreMemoryServiceTest.java @@ -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"); diff --git a/src/test/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCorePersistenceTest.java b/src/test/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCorePersistenceTest.java index 6c4154df25..f02ad08d98 100644 --- a/src/test/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCorePersistenceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/bedrockagentcorecontrol/BedrockAgentCorePersistenceTest.java @@ -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")); diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java index 29614e07a5..1353ea3bce 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java @@ -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; diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationBedrockAgentCoreIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationBedrockAgentCoreIntegrationTest.java new file mode 100644 index 0000000000..8e536de931 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationBedrockAgentCoreIntegrationTest.java @@ -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. + * + *

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 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 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 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 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 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 outputs(String expectedStatus) { + return outputs(STACK, expectedStatus); + } + + private static Map 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(); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/BedrockAgentCoreCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/BedrockAgentCoreCfnProvisionerTest.java new file mode 100644 index 0000000000..55ffe6f0de --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/BedrockAgentCoreCfnProvisionerTest.java @@ -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 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 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()); + } +} diff --git a/src/test/resources/cloudformation/getatt-attribute-gaps.tsv b/src/test/resources/cloudformation/getatt-attribute-gaps.tsv index 05be7256af..74b44ac154 100644 --- a/src/test/resources/cloudformation/getatt-attribute-gaps.tsv +++ b/src/test/resources/cloudformation/getatt-attribute-gaps.tsv @@ -1,4 +1,5 @@ AWS::AppSync::GraphQLApi GraphQLEndpointArn the private-endpoint ARN of the GraphQL endpoint; Floci serves one public endpoint and has no private-endpoint model +AWS::BedrockAgentCore::Runtime WorkloadIdentityDetails the dotted WorkloadIdentityDetails.WorkloadIdentityArn is set instead, the form AWS's GetAtt exposes for the nested object AWS::CodeBuild::Project Id schema gives no description; AWS's Id may differ from the project name Floci uses AWS::CodePipeline::CustomActionType Id schema gives no description; the custom action has no separate id in Floci AWS::CodePipeline::Webhook Id schema gives no description; Floci keys webhooks by name diff --git a/src/test/resources/cloudformation/supported-resource-types.tsv b/src/test/resources/cloudformation/supported-resource-types.tsv index 0ed1f75d55..deb6896a53 100644 --- a/src/test/resources/cloudformation/supported-resource-types.tsv +++ b/src/test/resources/cloudformation/supported-resource-types.tsv @@ -36,6 +36,9 @@ AWS::Backup::BackupVault BackupVaultCfnProvisioner AWS::Batch::ComputeEnvironment BatchCfnProvisioner AWS::Batch::JobDefinition BatchCfnProvisioner AWS::Batch::JobQueue BatchCfnProvisioner +AWS::BedrockAgentCore::Memory BedrockAgentCoreCfnProvisioner +AWS::BedrockAgentCore::Runtime BedrockAgentCoreCfnProvisioner +AWS::BedrockAgentCore::RuntimeEndpoint BedrockAgentCoreCfnProvisioner AWS::CDK::Metadata CdkMetadataCfnProvisioner AWS::CertificateManager::Certificate AcmCfnProvisioner AWS::CloudFormation::CustomResource CustomResourceCfnProvisioner diff --git a/tools/docs/cfn_resource_types.yaml b/tools/docs/cfn_resource_types.yaml index 8ba08b05c2..e009864285 100644 --- a/tools/docs/cfn_resource_types.yaml +++ b/tools/docs/cfn_resource_types.yaml @@ -55,6 +55,7 @@ order: - AWS::Logs - AWS::WAFv2 - AWS::Config + - AWS::BedrockAgentCore - AWS::CloudFormation - AWS::CloudTrail - Custom @@ -109,6 +110,7 @@ type_order: AWS::Cognito: [UserPool, UserPoolClient] AWS::Events: [Rule, EventBus, EventBusPolicy] AWS::CloudFormation: [CustomResource] + AWS::BedrockAgentCore: [Runtime, RuntimeEndpoint, Memory] # Namespace -> the service name shown in the Service column. service_labels: @@ -119,6 +121,7 @@ service_labels: AWS::AutoScaling: Auto Scaling AWS::Batch: Batch AWS::Backup: Backup + AWS::BedrockAgentCore: Bedrock AgentCore AWS::CDK: CDK AWS::CertificateManager: ACM AWS::CloudFormation: CloudFormation @@ -191,6 +194,9 @@ notes: AWS::Cognito::UserPool: '`ProviderURL` is the local issuer of the tokens Floci mints, `/`' AWS::Events::Archive: '`KmsKeyIdentifier` is ignored' AWS::CloudFront::Function: '`KeyValueStoreAssociations` is ignored' + AWS::BedrockAgentCore::Runtime: 'Ref returns the AgentRuntimeId; CapacityProviderConfiguration, FilesystemConfigurations, LifecycleConfiguration, PlatformVersion and RequestHeaderConfiguration are accepted and not stored' + AWS::BedrockAgentCore::RuntimeEndpoint: 'Ref returns the endpoint ARN; Tags are accepted and not stored' + AWS::BedrockAgentCore::Memory: 'Ref returns the memory ARN; MemoryStrategies, IndexedKeys, NamespaceKeys and StreamDeliveryResources are accepted and not stored' # Trailing prose appended to a row after its type list, for behaviour that belongs to the service # rather than to one type.