diff --git a/docs/services/bedrock-agentcore.md b/docs/services/bedrock-agentcore.md index da2b6835fd..ca34224925 100644 --- a/docs/services/bedrock-agentcore.md +++ b/docs/services/bedrock-agentcore.md @@ -257,7 +257,7 @@ resource once the stack update commits, as on AWS. Deleting the stack deletes th 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`, +`RequestHeaderConfiguration`; and the memory's `MemoryStrategies`, `IndexedKeys`, `NamespaceKeys` and `StreamDeliveryResources`. ## Examples diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.md index 1a8afbf0d4..6b51ebef10 100644 --- a/docs/services/cloudformation.md +++ b/docs/services/cloudformation.md @@ -258,7 +258,7 @@ cross-resource references. | WAFv2 | `IPSet`, `LoggingConfiguration`, `WebACL`, `WebACLAssociation` | | Config | `ConfigRule` | | Amazon Bedrock | `ApplicationInferenceProfile` (Ref returns the profile id; InferenceProfileArn and InferenceProfileId are available through GetAtt) | -| 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) | +| Bedrock AgentCore | `Runtime` (Ref returns the AgentRuntimeId; CapacityProviderConfiguration, FilesystemConfigurations, LifecycleConfiguration, PlatformVersion and RequestHeaderConfiguration are accepted and not stored), `RuntimeEndpoint` (Ref returns the endpoint ARN), `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), `StackSet`, `Stack` (nested stacks), `Custom::*` (Lambda-backed) | | CloudTrail | `Trail` | | CDK | `CDK::Metadata` (accepted; no-op) | diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/ApiGatewayRestApiCfnProvisioner.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/ApiGatewayRestApiCfnProvisioner.java index 32fa6b7f43..a3e0cebee1 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/provisioners/ApiGatewayRestApiCfnProvisioner.java +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/ApiGatewayRestApiCfnProvisioner.java @@ -233,10 +233,8 @@ public class ApiGatewayRestApiCfnProvisioner implements CfnResourceProvisioner { */ @Override public void mergeFailedUpdateResourceTracking(StackResource previous, StackResource attempted) { - String snapshot = attempted.getAttributes().get(CfnRollback.REST_API_UPDATE_SNAPSHOT_ATTR); - if (REST_API.equals(previous.getResourceType()) && snapshot != null - && attempted.getAttributes().containsKey(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR)) { - previous.getAttributes().put(CfnRollback.REST_API_UPDATE_SNAPSHOT_ATTR, snapshot); + if (REST_API.equals(previous.getResourceType())) { + CfnRollback.carryFailedUndoSnapshot(previous, attempted, CfnRollback.REST_API_UPDATE_SNAPSHOT_ATTR); } } diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/AppConfigCfnProvisioner.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/AppConfigCfnProvisioner.java index dc0701cb9b..07816dda8e 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/provisioners/AppConfigCfnProvisioner.java +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/AppConfigCfnProvisioner.java @@ -421,10 +421,7 @@ public class AppConfigCfnProvisioner implements CfnResourceProvisioner { */ @Override public void mergeFailedUpdateResourceTracking(StackResource previous, StackResource attempted) { - String snapshot = attempted.getAttributes().get(CfnRollback.APPCONFIG_UPDATE_SNAPSHOT_ATTR); - if (snapshot != null && attempted.getAttributes().containsKey(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR)) { - previous.getAttributes().put(CfnRollback.APPCONFIG_UPDATE_SNAPSHOT_ATTR, snapshot); - } + CfnRollback.carryFailedUndoSnapshot(previous, attempted, CfnRollback.APPCONFIG_UPDATE_SNAPSHOT_ATTR); } /** diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/AppSyncCfnProvisioner.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/AppSyncCfnProvisioner.java index 4ae08c2d4a..1f1742d1a5 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/provisioners/AppSyncCfnProvisioner.java +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/AppSyncCfnProvisioner.java @@ -478,10 +478,7 @@ public class AppSyncCfnProvisioner implements CfnResourceProvisioner { */ @Override public void mergeFailedUpdateResourceTracking(StackResource previous, StackResource attempted) { - String snapshot = attempted.getAttributes().get(CfnRollback.APPSYNC_UPDATE_SNAPSHOT_ATTR); - if (snapshot != null && attempted.getAttributes().containsKey(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR)) { - previous.getAttributes().put(CfnRollback.APPSYNC_UPDATE_SNAPSHOT_ATTR, snapshot); - } + CfnRollback.carryFailedUndoSnapshot(previous, attempted, CfnRollback.APPSYNC_UPDATE_SNAPSHOT_ATTR); } @Override diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/BedrockAgentCoreCfnProvisioner.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/BedrockAgentCoreCfnProvisioner.java index edfa38ef49..cf47a957b8 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/provisioners/BedrockAgentCoreCfnProvisioner.java +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/BedrockAgentCoreCfnProvisioner.java @@ -19,7 +19,6 @@ 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; @@ -63,12 +62,11 @@ public class BedrockAgentCoreCfnProvisioner implements CfnResourceProvisioner { * Template properties the backing service does not store. The runtime's capacity provider, * filesystems, hooks, lifecycle, platform version, request-header allowlist and resource * configurations, 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. + * have no representation in the emulated control plane. */ private static final Set RUNTIME_NOT_STORED = Set.of("CapacityProviderConfiguration", "FilesystemConfigurations", "HooksConfiguration", "LifecycleConfiguration", "PlatformVersion", "RequestHeaderConfiguration", "ResourceConfigurations"); - 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(); @@ -82,8 +80,8 @@ public class BedrockAgentCoreCfnProvisioner implements CfnResourceProvisioner { /** * 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 + * rollback can put it back: the runtime's configuration and tags, the endpoint's target version, + * description and tags, the memory's mutable properties and tags. Internal, like the other * {@code __Floci} attributes. */ static final String IN_PLACE_PRIOR_ATTR = "__FlociBedrockAgentCorePrior"; @@ -193,13 +191,9 @@ public class BedrockAgentCoreCfnProvisioner implements CfnResourceProvisioner { } 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); - } + CfnRollback.reconcileTags(runtimeService.getTagsByArn(region, arn).keySet(), desired, + stale -> runtimeService.untagByArn(region, arn, stale), + tags -> runtimeService.tagByArn(region, arn, tags)); } private void publishRuntime(StackResource r, AgentRuntime runtime, String region) { @@ -236,7 +230,7 @@ public class BedrockAgentCoreCfnProvisioner implements CfnResourceProvisioner { 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); + Map tags = ctx.resolveTags(props, "Tags"); EndpointLocation prior = ctx.isUpdate() ? runtimeService.findEndpointByArn(region, ctx.priorPhysicalId()).orElse(null) @@ -245,24 +239,33 @@ public class BedrockAgentCoreCfnProvisioner implements CfnResourceProvisioner { && 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) { + boolean configurationChanged = !((version == null || version.equals(existing.getTargetVersion())) + && Objects.equals(description, existing.getDescription())); + String arn = runtimeService.endpointArn(runtimeId, existing, region); + Map priorTags = runtimeService.getEndpointTagsByArn(region, arn); + if (!configurationChanged && priorTags.equals(tags)) { 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()); + if (configurationChanged) { + endpointPrior.put("targetVersion", existing.getTargetVersion()); + endpointPrior.put("description", existing.getDescription()); + } + snapshot.set("tags", MAPPER.valueToTree(priorTags)); writeInPlacePrior(r, snapshot); - CfnRollback.guarded(r, ctx, false, () -> { }, () -> undoInPlace(r), - () -> publishRuntimeEndpoint(r, prior.runtime(), - runtimeService.updateEndpoint(runtimeId, name, version, description, true, region), region)); + CfnRollback.guarded(r, ctx, false, () -> { }, () -> undoInPlace(r), () -> { + AgentRuntimeEndpoint endpoint = configurationChanged + ? runtimeService.updateEndpoint(runtimeId, name, version, description, true, region) + : existing; + reconcileEndpointTags(arn, tags, region); + publishRuntimeEndpoint(r, prior.runtime(), endpoint, region); + }); } else { AgentRuntimeEndpoint endpoint = runtimeService.createEndpoint(runtimeId, name, version, description, - null, region); + tags, null, region); r.setPhysicalId(runtimeService.endpointArn(runtimeId, endpoint, region)); CfnRollback.guarded(r, ctx, true, () -> runtimeService.deleteEndpoint(runtimeId, name, null, region), () -> undoInPlace(r), @@ -270,6 +273,12 @@ public class BedrockAgentCoreCfnProvisioner implements CfnResourceProvisioner { } } + private void reconcileEndpointTags(String arn, Map desired, String region) { + CfnRollback.reconcileTags(runtimeService.getEndpointTagsByArn(region, arn).keySet(), desired, + stale -> runtimeService.untagEndpointByArn(region, arn, stale), + tags -> runtimeService.tagEndpointByArn(region, arn, tags)); + } + private void publishRuntimeEndpoint(StackResource r, AgentRuntime runtime, AgentRuntimeEndpoint endpoint, String region) { String endpointArn = runtimeService.endpointArn(runtime.getAgentRuntimeId(), endpoint, region); @@ -333,13 +342,9 @@ public class BedrockAgentCoreCfnProvisioner implements CfnResourceProvisioner { } 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); - } + CfnRollback.reconcileTags(memoryService.getTagsByArn(region, arn).keySet(), desired, + stale -> memoryService.untagByArn(region, arn, stale), + tags -> memoryService.tagByArn(region, arn, tags)); } private void publishMemory(StackResource r, Memory memory, String region) { @@ -436,6 +441,17 @@ public class BedrockAgentCoreCfnProvisioner implements CfnResourceProvisioner { ReplacementCleanup.clear(resource); } + /** + * Keeps the snapshot of an in-place update whose own undo did not complete. The engine restores + * the previous resource and reports the rollback failure once; with the snapshot of the state + * the update started from, a ContinueUpdateRollback restores that state instead of finding + * nothing to undo. + */ + @Override + public void mergeFailedUpdateResourceTracking(StackResource previous, StackResource attempted) { + CfnRollback.carryFailedUndoSnapshot(previous, attempted, IN_PLACE_PRIOR_ATTR); + } + /** * 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 @@ -485,8 +501,16 @@ public class BedrockAgentCoreCfnProvisioner implements CfnResourceProvisioner { } 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); + String endpointName = text(endpointPrior, "name"); + // A tag-only change snapshots no configuration, and restoring none leaves LastUpdatedAt alone. + AgentRuntimeEndpoint endpoint = endpointPrior.has("targetVersion") + ? runtimeService.updateEndpoint(entityId, endpointName, text(endpointPrior, "targetVersion"), + text(endpointPrior, "description"), true, region) + : runtimeService.getEndpoint(entityId, endpointName, region); + if (prior.has("tags")) { + reconcileEndpointTags(runtimeService.endpointArn(entityId, endpoint, region), + stringMap(prior.get("tags")), region); + } publishRuntimeEndpoint(resource, runtimeService.getAgentRuntime(entityId, region), endpoint, region); } case MEMORY -> { diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/CfnRollback.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/CfnRollback.java index 248914e6d5..dce6270871 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/provisioners/CfnRollback.java +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/CfnRollback.java @@ -495,6 +495,26 @@ public final class CfnRollback { } } + /** + * Carries the snapshot of an in-place update whose own undo did not complete onto the previous + * resource the engine restores, for a provisioner's {@code mergeFailedUpdateResourceTracking}: + * with the state the update started from, a ContinueUpdateRollback tries the restore again + * instead of finding nothing to undo. An undo that completed spent its snapshot and left no + * {@link #UPDATE_ROLLBACK_FAILURE_ATTR}, so nothing is carried. + */ + public static void carryFailedUndoSnapshot(StackResource previous, StackResource attempted, + String... snapshotAttrs) { + if (!attempted.getAttributes().containsKey(UPDATE_ROLLBACK_FAILURE_ATTR)) { + return; + } + for (String attr : snapshotAttrs) { + String snapshot = attempted.getAttributes().get(attr); + if (snapshot != null) { + previous.getAttributes().put(attr, snapshot); + } + } + } + /** * 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 diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/ElbV2CfnProvisioner.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/ElbV2CfnProvisioner.java index 1ae037f3be..5ce2726c49 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/provisioners/ElbV2CfnProvisioner.java +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/ElbV2CfnProvisioner.java @@ -184,16 +184,9 @@ public class ElbV2CfnProvisioner implements CfnResourceProvisioner { */ @Override public void mergeFailedUpdateResourceTracking(StackResource previous, StackResource attempted) { - if (!attempted.getAttributes().containsKey(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR)) { - return; - } - for (String attr : List.of(CfnRollback.TARGET_GROUP_TARGETS_UPDATE_SNAPSHOT_ATTR, - CfnRollback.LISTENER_CERTIFICATES_UPDATE_SNAPSHOT_ATTR)) { - String snapshot = attempted.getAttributes().get(attr); - if (snapshot != null) { - previous.getAttributes().put(attr, snapshot); - } - } + CfnRollback.carryFailedUndoSnapshot(previous, attempted, + CfnRollback.TARGET_GROUP_TARGETS_UPDATE_SNAPSHOT_ATTR, + CfnRollback.LISTENER_CERTIFICATES_UPDATE_SNAPSHOT_ATTR); } /** diff --git a/src/test/java/io/floci/aws/services/cloudformation/BedrockAgentCoreEndpointCfnUpdateRollbackRetryIntegrationTest.java b/src/test/java/io/floci/aws/services/cloudformation/BedrockAgentCoreEndpointCfnUpdateRollbackRetryIntegrationTest.java new file mode 100644 index 0000000000..ed1383cc39 --- /dev/null +++ b/src/test/java/io/floci/aws/services/cloudformation/BedrockAgentCoreEndpointCfnUpdateRollbackRetryIntegrationTest.java @@ -0,0 +1,91 @@ +package io.floci.aws.services.cloudformation; + +import io.floci.aws.core.common.AwsException; +import io.floci.aws.services.bedrockagentcorecontrol.BedrockAgentCoreControlService; +import io.floci.aws.testing.CfnStackWaits; +import io.floci.aws.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.mockito.InjectSpy; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + +import static io.floci.aws.testing.CfnRequests.cfn; +import static io.floci.aws.testing.CfnRequests.physicalIdUnauthenticated; +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.anEmptyMap; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.anyMap; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; + +/** + * A tag update of an AWS::BedrockAgentCore::RuntimeEndpoint whose own undo cannot complete leaves + * the stack in UPDATE_ROLLBACK_FAILED, and ContinueUpdateRollback takes that undo up again from the + * snapshot carried onto the restored resource. + */ +@QuarkusTest +class BedrockAgentCoreEndpointCfnUpdateRollbackRetryIntegrationTest { + + 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"}]}}}, + "Runtime":{"Type":"AWS::BedrockAgentCore::Runtime","Properties":{ + "AgentRuntimeName":"cfn_endpoint_retry_runtime", + "AgentRuntimeArtifact":{"ContainerConfiguration":{ + "ContainerUri":"000000000000.dkr.ecr.us-east-1.amazonaws.com/cfn-agent:latest"}}, + "RoleArn":{"Fn::GetAtt":["Role","Arn"]}}}, + "Endpoint":{"Type":"AWS::BedrockAgentCore::RuntimeEndpoint","Properties":{ + "AgentRuntimeId":{"Fn::GetAtt":["Runtime","AgentRuntimeId"]}, + "Name":"prod","Tags":{"%s":"%s"}}}}} + """; + + @InjectSpy + BedrockAgentCoreControlService runtimeService; + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + void aRetryPutsBackTheTagsWhoseFirstRestoreFailed() { + String stack = "agentcore-cfn-endpoint-retry-tags-it"; + try { + stackAction(stack, "CreateStack", TEMPLATE.formatted("team", "agents")); + assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stack).status()); + String endpointArn = physicalIdUnauthenticated(stack, "Endpoint"); + // The update removes the stored key, then both its tag write and the restore's fail. + Mockito.doThrow(new AwsException("ThrottlingException", "Too Many Requests", 429)) + .doThrow(new AwsException("ThrottlingException", "Too Many Requests", 429)) + .doCallRealMethod() + .when(runtimeService).tagEndpointByArn(anyString(), eq(endpointArn), anyMap()); + + stackAction(stack, "UpdateStack", TEMPLATE.formatted("owner", "ml")); + CfnStackWaits.StackState state = CfnStackWaits.awaitTerminal(stack); + assertEquals("UPDATE_ROLLBACK_FAILED", state.status(), state.reason()); + given().when().get("/tags/" + endpointArn).then().statusCode(200).body("tags", anEmptyMap()); + + CfnStackWaits.continueUpdateRollback(stack, null); + state = CfnStackWaits.awaitTerminal(stack); + assertEquals("UPDATE_ROLLBACK_COMPLETE", state.status(), state.reason()); + given().when().get("/tags/" + endpointArn).then().statusCode(200) + .body("tags.size()", equalTo(1)) + .body("tags.team", equalTo("agents")); + } finally { + deleteStack(stack); + } + } + + private static void stackAction(String stack, String action, String template) { + cfn(action, stack).formParam("TemplateBody", template).when().post("/").then().statusCode(200); + } + + private static void deleteStack(String stack) { + cfn("DeleteStack", stack).when().post("/").then().statusCode(200); + CfnStackWaits.awaitStackDeleted(stack); + } +} diff --git a/src/test/java/io/floci/aws/services/cloudformation/CloudFormationBedrockAgentCoreIntegrationTest.java b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationBedrockAgentCoreIntegrationTest.java index 304b537d5c..97cb8b00bf 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/CloudFormationBedrockAgentCoreIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationBedrockAgentCoreIntegrationTest.java @@ -169,7 +169,8 @@ class CloudFormationBedrockAgentCoreIntegrationTest { "Type": "AWS::BedrockAgentCore::RuntimeEndpoint", "Properties": { "AgentRuntimeId": {"Fn::GetAtt": ["Runtime", "AgentRuntimeId"]}, - "Name": "prod"%s + "Name": "prod"%s, + "Tags": {"team": "%s"} } }%s }, @@ -177,12 +178,13 @@ class CloudFormationBedrockAgentCoreIntegrationTest { "MemoryId": {"Value": {"Fn::GetAtt": ["Memory", "MemoryId"]}}, "MemoryArn": {"Value": {"Fn::GetAtt": ["Memory", "MemoryArn"]}}, "RuntimeId": {"Value": {"Fn::GetAtt": ["Runtime", "AgentRuntimeId"]}}, - "RuntimeArn": {"Value": {"Fn::GetAtt": ["Runtime", "AgentRuntimeArn"]}} + "RuntimeArn": {"Value": {"Fn::GetAtt": ["Runtime", "AgentRuntimeArn"]}}, + "EndpointArn": {"Value": {"Fn::GetAtt": ["Endpoint", "AgentRuntimeEndpointArn"]}} } } """.formatted(descriptionProperty(memoryDescription), tagValue, CONTAINER_URI, descriptionProperty(runtimeDescription), tagValue, descriptionProperty(endpointDescription), - failingResource); + tagValue, failingResource); } private static String descriptionProperty(String description) { @@ -303,10 +305,12 @@ class CloudFormationBedrockAgentCoreIntegrationTest { String memoryArn = outputs.get("MemoryArn"); String runtimeId = outputs.get("RuntimeId"); String runtimeArn = outputs.get("RuntimeArn"); + String endpointArn = outputs.get("EndpointArn"); + given().when().get("/tags/" + endpointArn).then().statusCode(200).body("tags.team", equalTo("agents")); // 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. + // memory, the endpoint and all three 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"); @@ -319,6 +323,13 @@ class CloudFormationBedrockAgentCoreIntegrationTest { 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")); + given().when().get("/tags/" + endpointArn).then().statusCode(200).body("tags.team", equalTo("agents")); + + // A tag-only change reaches the endpoint in place. + cloudFormation(ROLLBACK_STACK, "UpdateStack", + rollbackTemplate("memory one", "runtime one", "endpoint one", "ml", false)); + assertEquals(endpointArn, outputs(ROLLBACK_STACK, "UPDATE_COMPLETE").get("EndpointArn")); + given().when().get("/tags/" + endpointArn).then().statusCode(200).body("tags.team", equalTo("ml")); // 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. diff --git a/src/test/java/io/floci/aws/services/cloudformation/provisioners/BedrockAgentCoreCfnProvisionerTest.java b/src/test/java/io/floci/aws/services/cloudformation/provisioners/BedrockAgentCoreCfnProvisionerTest.java index 285b768051..9b3a439d35 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/provisioners/BedrockAgentCoreCfnProvisionerTest.java +++ b/src/test/java/io/floci/aws/services/cloudformation/provisioners/BedrockAgentCoreCfnProvisionerTest.java @@ -32,9 +32,11 @@ 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.doNothing; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -49,6 +51,7 @@ class BedrockAgentCoreCfnProvisionerTest { private static final String RUNTIME_ARN = "arn:aws:bedrock-agentcore:us-east-1:000000000000:runtime/" + RUNTIME_ID; 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 ENDPOINT_ARN = RUNTIME_ARN + "/runtime-endpoint/prod"; private static final String ROLE_ARN = "arn:aws:iam::000000000000:role/agent"; private final BedrockAgentCoreControlService runtimes = mock(BedrockAgentCoreControlService.class); @@ -110,6 +113,48 @@ class BedrockAgentCoreCfnProvisionerTest { return memory; } + private static AgentRuntimeEndpoint endpoint(String description) { + AgentRuntimeEndpoint endpoint = new AgentRuntimeEndpoint(); + endpoint.setName("prod"); + endpoint.setUuid("ep-uuid"); + endpoint.setTargetVersion("1"); + endpoint.setLiveVersion("1"); + endpoint.setStatus("READY"); + endpoint.setDescription(description); + endpoint.setCreatedAt(Instant.EPOCH); + endpoint.setLastUpdatedAt(Instant.EPOCH); + return endpoint; + } + + private ObjectNode endpointProps(String description, Map tags) { + ObjectNode props = mapper.createObjectNode(); + props.put("AgentRuntimeId", RUNTIME_ID); + props.put("Name", "prod"); + if (description != null) { + props.put("Description", description); + } + if (tags != null) { + ObjectNode tagNode = props.putObject("Tags"); + tags.forEach(tagNode::put); + } + return props; + } + + /** An endpoint the stack already owns at {@code arn:ep}, carrying the given tags. */ + private StackResource existingEndpoint(AgentRuntimeEndpoint existing, Map tags) { + AgentRuntime runtime = runtime(null, Map.of()); + when(runtimes.findEndpointByArn(REGION, ENDPOINT_ARN)) + .thenReturn(Optional.of(new BedrockAgentCoreControlService.EndpointLocation(runtime, existing))); + when(runtimes.endpointArn(RUNTIME_ID, existing, REGION)).thenReturn(ENDPOINT_ARN); + when(runtimes.getEndpoint(RUNTIME_ID, "prod", REGION)).thenReturn(existing); + when(runtimes.getAgentRuntime(RUNTIME_ID, REGION)).thenReturn(runtime); + when(runtimes.arn(any(), eq(REGION))).thenReturn(RUNTIME_ARN); + when(runtimes.getEndpointTagsByArn(REGION, ENDPOINT_ARN)).thenAnswer(invocation -> new HashMap<>(tags)); + StackResource r = resource("AWS::BedrockAgentCore::RuntimeEndpoint"); + r.setPhysicalId(ENDPOINT_ARN); + return r; + } + private static ObjectNode runtimeProps(ObjectMapper mapper, String description, String tag) { ObjectNode props = mapper.createObjectNode(); props.put("AgentRuntimeName", "agent"); @@ -164,15 +209,8 @@ class BedrockAgentCoreCfnProvisionerTest { @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); + AgentRuntimeEndpoint endpoint = endpoint(null); + when(runtimes.createEndpoint(RUNTIME_ID, "prod", null, null, Map.of(), null, REGION)).thenReturn(endpoint); when(runtimes.endpointArn(RUNTIME_ID, endpoint, REGION)).thenReturn("arn:ep"); when(runtimes.getAgentRuntime(RUNTIME_ID, REGION)) .thenThrow(new AwsException("InternalServerException", "boom", 500)); @@ -258,15 +296,7 @@ class BedrockAgentCoreCfnProvisionerTest { @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); + AgentRuntimeEndpoint existing = endpoint("old"); 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))) @@ -284,4 +314,123 @@ class BedrockAgentCoreCfnProvisionerTest { verify(runtimes).updateEndpoint(RUNTIME_ID, "prod", null, null, true, REGION); assertEquals("arn:ep", r.getPhysicalId()); } + + @Test + void endpointTagsAreStoredWithTheCreatedEndpoint() { + AgentRuntimeEndpoint created = endpoint(null); + when(runtimes.createEndpoint(any(), any(), any(), any(), anyMap(), any(), any())).thenReturn(created); + when(runtimes.endpointArn(RUNTIME_ID, created, REGION)).thenReturn(ENDPOINT_ARN); + when(runtimes.getAgentRuntime(RUNTIME_ID, REGION)).thenReturn(runtime(null, Map.of())); + when(runtimes.arn(any(), eq(REGION))).thenReturn(RUNTIME_ARN); + StackResource r = resource("AWS::BedrockAgentCore::RuntimeEndpoint"); + + provisioner.provision(r, endpointProps(null, Map.of("team", "agents")), ctx(null)); + + verify(runtimes).createEndpoint(RUNTIME_ID, "prod", null, null, Map.of("team", "agents"), null, REGION); + assertEquals(ENDPOINT_ARN, r.getPhysicalId()); + } + + @Test + void aTagOnlyEndpointChangeIsReconciledWithoutUpdatingTheEndpoint() { + StackResource r = existingEndpoint(endpoint("same"), Map.of("team", "agents", "stage", "beta")); + + provisioner.provision(r, endpointProps("same", Map.of("team", "ml")), ctx(ENDPOINT_ARN)); + + verify(runtimes, never()).updateEndpoint(any(), any(), any(), any(), anyBoolean(), any()); + verify(runtimes).untagEndpointByArn(REGION, ENDPOINT_ARN, List.of("stage")); + verify(runtimes).tagEndpointByArn(REGION, ENDPOINT_ARN, Map.of("team", "ml")); + assertTrue(r.getAttributes().containsKey(BedrockAgentCoreCfnProvisioner.IN_PLACE_PRIOR_ATTR)); + } + + @Test + void omittingEndpointTagsRemovesTheStoredOnes() { + StackResource r = existingEndpoint(endpoint("same"), Map.of("team", "agents")); + + provisioner.provision(r, endpointProps("same", null), ctx(ENDPOINT_ARN)); + + verify(runtimes).untagEndpointByArn(REGION, ENDPOINT_ARN, List.of("team")); + verify(runtimes, never()).tagEndpointByArn(any(), any(), anyMap()); + } + + @Test + void anEndpointWithUnchangedTagsIsNeitherRetaggedNorSnapshotted() { + StackResource r = existingEndpoint(endpoint("same"), Map.of("team", "agents")); + + provisioner.provision(r, endpointProps("same", Map.of("team", "agents")), ctx(ENDPOINT_ARN)); + + verify(runtimes, never()).tagEndpointByArn(any(), any(), anyMap()); + verify(runtimes, never()).untagEndpointByArn(any(), any(), any()); + assertFalse(r.getAttributes().containsKey(BedrockAgentCoreCfnProvisioner.IN_PLACE_PRIOR_ATTR)); + } + + @Test + void rollbackUpdateRestoresTheEndpointsPriorTags() { + AgentRuntimeEndpoint existing = endpoint("same"); + Map stored = new HashMap<>(Map.of("team", "agents")); + StackResource r = existingEndpoint(existing, stored); + provisioner.provision(r, endpointProps("same", Map.of("owner", "ml")), ctx(ENDPOINT_ARN)); + stored.clear(); + stored.put("owner", "ml"); + + assertTrue(provisioner.rollbackUpdate(r)); + + verify(runtimes).untagEndpointByArn(REGION, ENDPOINT_ARN, List.of("owner")); + verify(runtimes).tagEndpointByArn(REGION, ENDPOINT_ARN, Map.of("team", "agents")); + verify(runtimes, never()).updateEndpoint(any(), any(), any(), any(), anyBoolean(), any()); + assertNull(r.getAttributes().get(BedrockAgentCoreCfnProvisioner.IN_PLACE_PRIOR_ATTR)); + } + + @Test + void aFailedEndpointTagWriteRestoresTheKeysRemovedBeforeIt() { + AgentRuntimeEndpoint existing = endpoint("old"); + Map stored = new HashMap<>(Map.of("team", "agents")); + StackResource r = existingEndpoint(existing, stored); + when(runtimes.updateEndpoint(eq(RUNTIME_ID), eq("prod"), any(), any(), anyBoolean(), eq(REGION))) + .thenReturn(existing); + doThrow(new AwsException("ThrottlingException", "slow down", 429)) + .when(runtimes).tagEndpointByArn(REGION, ENDPOINT_ARN, Map.of("owner", "ml")); + + assertThrows(AwsException.class, + () -> provisioner.provision(r, endpointProps("new", Map.of("owner", "ml")), ctx(ENDPOINT_ARN))); + + verify(runtimes).untagEndpointByArn(REGION, ENDPOINT_ARN, List.of("team")); + verify(runtimes).updateEndpoint(RUNTIME_ID, "prod", null, "new", true, REGION); + verify(runtimes).updateEndpoint(RUNTIME_ID, "prod", "1", "old", true, REGION); + verify(runtimes).tagEndpointByArn(REGION, ENDPOINT_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 aTagRestoreThatFailedIsRetriedFromTheSnapshotCarriedOntoThePreviousResource() { + Map stored = new HashMap<>(Map.of("team", "agents")); + StackResource attempt = existingEndpoint(endpoint("same"), stored); + StackResource committed = resource("AWS::BedrockAgentCore::RuntimeEndpoint"); + committed.setPhysicalId(ENDPOINT_ARN); + doThrow(new AwsException("ThrottlingException", "slow down", 429)) + .when(runtimes).tagEndpointByArn(eq(REGION), eq(ENDPOINT_ARN), anyMap()); + + assertThrows(AwsException.class, + () -> provisioner.provision(attempt, endpointProps("same", Map.of("owner", "ml")), ctx(ENDPOINT_ARN))); + assertTrue(attempt.getAttributes().containsKey(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR)); + stored.clear(); + + provisioner.mergeFailedUpdateResourceTracking(committed, attempt); + doNothing().when(runtimes).tagEndpointByArn(eq(REGION), eq(ENDPOINT_ARN), anyMap()); + assertTrue(provisioner.rollbackUpdate(committed)); + + verify(runtimes, times(2)).tagEndpointByArn(REGION, ENDPOINT_ARN, Map.of("team", "agents")); + assertNull(committed.getAttributes().get(BedrockAgentCoreCfnProvisioner.IN_PLACE_PRIOR_ATTR)); + } + + @Test + void anEndpointUndoThatCompletedLeavesThePreviousResourceAlone() { + StackResource attempt = existingEndpoint(endpoint("same"), Map.of("team", "agents")); + StackResource committed = resource("AWS::BedrockAgentCore::RuntimeEndpoint"); + provisioner.provision(attempt, endpointProps("same", Map.of("team", "ml")), ctx(ENDPOINT_ARN)); + + provisioner.mergeFailedUpdateResourceTracking(committed, attempt); + + assertTrue(committed.getAttributes().isEmpty()); + } } diff --git a/src/test/resources/cloudformation/writable-property-gaps.tsv b/src/test/resources/cloudformation/writable-property-gaps.tsv index e9b187fa7d..4e6ab2326e 100644 --- a/src/test/resources/cloudformation/writable-property-gaps.tsv +++ b/src/test/resources/cloudformation/writable-property-gaps.tsv @@ -126,7 +126,6 @@ AWS::BedrockAgentCore::Runtime LifecycleConfiguration accepted and not stored, a AWS::BedrockAgentCore::Runtime PlatformVersion accepted and not stored, a warning is logged AWS::BedrockAgentCore::Runtime RequestHeaderConfiguration accepted and not stored, a warning is logged AWS::BedrockAgentCore::Runtime ResourceConfigurations accepted and not stored, a warning is logged -AWS::BedrockAgentCore::RuntimeEndpoint Tags accepted and not stored, a warning is logged AWS::CertificateManager::Certificate CertificateAuthorityArn accepted and ignored AWS::CertificateManager::Certificate DomainValidationOptions accepted and ignored, as the AcmCfnProvisioner javadoc records AWS::CloudFormation::CustomResource ServiceTimeout accepted and ignored diff --git a/tools/docs/cfn_resource_types.yaml b/tools/docs/cfn_resource_types.yaml index 8f36cd6ba4..334cc563ca 100644 --- a/tools/docs/cfn_resource_types.yaml +++ b/tools/docs/cfn_resource_types.yaml @@ -251,7 +251,7 @@ notes: AWS::GuardDuty::MalwareProtectionPlan: 'management plane only: no scan runs, so the plan stays ACTIVE; Ref returns the plan id; a BucketName change is rejected' AWS::Bedrock::ApplicationInferenceProfile: 'Ref returns the profile id; InferenceProfileArn and InferenceProfileId are available through GetAtt' 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::RuntimeEndpoint: 'Ref returns the endpoint ARN' AWS::BedrockAgentCore::Memory: 'Ref returns the memory ARN; MemoryStrategies, IndexedKeys, NamespaceKeys and StreamDeliveryResources are accepted and not stored' AWS::KinesisFirehose::DeliveryStream: '`DeliveryStreamName`, `Tags` and, from an S3 destination, `BucketARN`, `RoleARN`, `Prefix`, `ErrorOutputPrefix`, `CompressionFormat`, `BufferingHints`, `CloudWatchLoggingOptions` and `ProcessingConfiguration` are applied; other properties are ignored, and a destination member the template drops on update keeps its stored value, as on AWS'