From 6bde4e6bb3e97956a13c33913e01fad5fb394059 Mon Sep 17 00:00:00 2001 From: Jimmy Liu Jia <91264074+JimmyLiuJia@users.noreply.github.com> Date: Wed, 18 Nov 2026 09:08:02 +0800 Subject: [PATCH] fix(cloudformation): provision Bedrock application inference profiles (#8772) --- docs/services/bedrock.md | 52 +-- docs/services/cloudformation.md | 1 + docs/services/index.md | 2 +- .../services/bedrock/BedrockController.java | 67 +++- .../aws/services/bedrock/BedrockService.java | 276 ++++++++++++++- .../services/bedrock/BedrockTagValidator.java | 61 ++++ .../model/ApplicationInferenceProfile.java | 111 ++++++ .../provisioners/BedrockCfnProvisioner.java | 261 ++++++++++++++ .../create-only-properties.json | 5 + ...cationInferenceProfileIntegrationTest.java | 204 +++++++++++ ...pplicationInferenceProfileServiceTest.java | 129 +++++++ ...ockGuardrailCreateNameConcurrencyTest.java | 2 +- ...rockGuardrailLifecycleConcurrencyTest.java | 2 +- .../services/bedrock/BedrockServiceTest.java | 2 +- .../cloudformation/CfnProvisionerFixture.java | 11 + ...cationInferenceProfileIntegrationTest.java | 335 ++++++++++++++++++ .../BedrockCfnProvisionerTest.java | 309 ++++++++++++++++ .../cloudformation/schema-surface.tsv | 1 + .../supported-resource-types.tsv | 1 + tools/docs/cfn_resource_types.yaml | 3 + 20 files changed, 1778 insertions(+), 57 deletions(-) create mode 100644 src/main/java/io/floci/aws/services/bedrock/BedrockTagValidator.java create mode 100644 src/main/java/io/floci/aws/services/bedrock/model/ApplicationInferenceProfile.java create mode 100644 src/main/java/io/floci/aws/services/cloudformation/provisioners/BedrockCfnProvisioner.java create mode 100644 src/test/java/io/floci/aws/services/bedrock/BedrockApplicationInferenceProfileIntegrationTest.java create mode 100644 src/test/java/io/floci/aws/services/bedrock/BedrockApplicationInferenceProfileServiceTest.java create mode 100644 src/test/java/io/floci/aws/services/cloudformation/CloudFormationBedrockApplicationInferenceProfileIntegrationTest.java create mode 100644 src/test/java/io/floci/aws/services/cloudformation/provisioners/BedrockCfnProvisionerTest.java diff --git a/docs/services/bedrock.md b/docs/services/bedrock.md index b5254714d5..c7d5cc4264 100644 --- a/docs/services/bedrock.md +++ b/docs/services/bedrock.md @@ -19,14 +19,16 @@ that shares the same signing name: see [Bedrock Runtime](bedrock-runtime.md). | `ListGuardrails` | List every guardrail's `DRAFT`, or every version of one guardrail | | `ListFoundationModels` | List the catalog's foundation models served in the calling Region, filtered by provider and output modality | | `GetFoundationModel` | Read one foundation model by id or ARN | -| `ListInferenceProfiles` | List the system-defined inference profiles the calling Region can use, with `type`, `maxResults` and `nextToken` | -| `GetInferenceProfile` | Read one system-defined inference profile by id or ARN, with its destination Regions | +| `ListInferenceProfiles` | List system-defined and created application profiles, with `type`, `maxResults` and `nextToken` | +| `GetInferenceProfile` | Read a system-defined or application profile by id or ARN, including its model destinations | +| `CreateInferenceProfile` | Create an application profile from a regional foundation model or system-defined profile | +| `DeleteInferenceProfile` | Delete an application profile by id or ARN | | `PutResourcePolicy` | Attach a resource-based policy to a guardrail or a guardrail profile (`POST /resource-policy`) | | `GetResourcePolicy` | Read the resource-based policy of a guardrail or a guardrail profile | | `DeleteResourcePolicy` | Remove the resource-based policy of a guardrail or a guardrail profile | -| `TagResource` | Tag a guardrail (`POST /tagResource`) | -| `UntagResource` | Remove tags from a guardrail (`POST /untagResource`) | -| `ListTagsForResource` | List a guardrail's tags (`POST /listTagsForResource`) | +| `TagResource` | Tag a guardrail or application inference profile (`POST /tagResource`) | +| `UntagResource` | Remove tags from a guardrail or application inference profile (`POST /untagResource`) | +| `ListTagsForResource` | List a guardrail's or application inference profile's tags (`POST /listTagsForResource`) | Guardrails are versioned. The working copy is `DRAFT`, and `GetGuardrail` without a @@ -51,7 +53,7 @@ guardrail and all of its versions. Both an id (`abc123def456`) and a full ARN are accepted wherever the API takes a `guardrailIdentifier` or a `resourceARN`. -The three tag actions require a full ARN to match the stored guardrail ARN exactly, +For guardrails, the three tag actions require a full ARN to match the stored ARN exactly, including partition, service, Region, account, and resource type. An ARN that only shares the guardrail ID returns `ResourceNotFoundException` (HTTP 404) without changing tags. The existing bare-ID form remains accepted. @@ -108,11 +110,12 @@ those tags, as `TagResource` and `UntagResource` do. ## Foundation models and inference profiles -`ListFoundationModels`, `GetFoundationModel`, `ListInferenceProfiles` and -`GetInferenceProfile` read a fixed catalog, `bedrock/model-catalog.yaml`. It is a seed -rather than a mirror of AWS: a few real models (Amazon Nova Micro and Nova Lite, Titan Text -Embeddings V2, Llama 3.1 8B Instruct and Claude Sonnet 4.5) with the modalities, streaming -support, lifecycle status and Regional availability their +`ListFoundationModels` and `GetFoundationModel` read a fixed catalog, +`bedrock/model-catalog.yaml`. System-defined inference profiles come from the same seed, +while application inference profiles are created and stored by the Bedrock control plane. +The catalog is a seed rather than a mirror of AWS: a few real models (Amazon Nova Micro +and Nova Lite, Titan Text Embeddings V2, Llama 3.1 8B Instruct and Claude Sonnet 4.5) +with the modalities, streaming support, lifecycle status and Regional availability their [model cards](https://docs.aws.amazon.com/bedrock/latest/userguide/model-cards.html) publish, and their US and EU system-defined inference profiles. @@ -126,25 +129,32 @@ The answers depend on the calling Region, as on AWS: - `byOutputModality` accepts `SPEECH` and `VIDEO` as well as the published `TEXT`, `IMAGE` and `EMBEDDING`, as AWS does. No catalog model produces speech or video, so those filters return an empty list. -- An inference profile is listed only in its source Regions, and its `models` are the - foundation models in the destination Regions the card gives for the calling Region, so - `us.amazon.nova-lite-v1:0` called from `us-west-1` routes to four Regions and from +- A system-defined inference profile is listed only in its source Regions. Its + `models` are the foundation models in the destination Regions the card gives for + the calling Region, so `us.amazon.nova-lite-v1:0` called from `us-west-1` routes to four Regions and from `us-east-1` to three. `GetInferenceProfile` on a profile the Region cannot use returns `ResourceNotFoundException`. - `inferenceTypesSupported` is `ON_DEMAND` only where the model is served in the Region itself, and empty where it is reachable only through an inference profile, so `byInferenceType=ON_DEMAND` leaves those out. - `modelArn` is `arn::bedrock:::foundation-model/`, and - `inferenceProfileArn` carries the calling Region and account. `GetInferenceProfile` - answers an ARN of another service or without an account with `ValidationException`, - one of another account with `AccessDeniedException`, and one of another Region, + the system-defined `inferenceProfileArn` carries the calling Region and account. + `GetInferenceProfile` answers an ARN of another service or without an account with + `ValidationException`, one of another account with `AccessDeniedException`, and one of another Region, partition or resource type with `ResourceNotFoundException`. - The error codes and statuses follow AWS; the message text is Floci's own. +`CreateInferenceProfile` accepts `modelSource.copyFrom` with a foundation-model ARN served +in the calling Region, or a system-defined inference-profile ARN available to the calling +Region and account. It creates a stored `APPLICATION` profile whose `GetInferenceProfile` +result includes its id, ARN, name, description, models and timestamps. `ListInferenceProfiles` +includes these profiles alongside the system-defined catalog; `type=APPLICATION` selects +only the created profiles. An application profile can be deleted by id or ARN and tagged +through the Bedrock tag actions. Copying an application profile is not supported. + Deviations: models that are not in the catalog are not listed, provisioned throughput is never reported, and `customizationsSupported` is always empty, so `byCustomizationType` -and `byInferenceType=PROVISIONED` return no models. Application inference profiles cannot -be created yet, so `type=APPLICATION` returns an empty list. `ListInferenceProfiles` pages +and `byInferenceType=PROVISIONED` return no models. `ListInferenceProfiles` pages up to 1000 profiles; `maxResults` outside 1 to 1000 is rejected with `ValidationException`. ## Not implemented @@ -155,8 +165,8 @@ emulating it faithfully would require behaviour Floci has no way to model: - Custom model, model customization, model import and distillation jobs. These depend on real training runs. - Model evaluation and evaluation jobs. These depend on real inference. -- Provisioned throughput, application inference profiles and prompt routers. These - describe real capacity reservations and routing. +- Provisioned throughput and prompt routers. These describe real capacity reservations + and routing. - Model invocation logging, batch inference and async invoke. These are data-plane operations backed by real model execution. diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.md index 6259ed729c..537a731832 100644 --- a/docs/services/cloudformation.md +++ b/docs/services/cloudformation.md @@ -256,6 +256,7 @@ cross-resource references. | CloudWatch Logs | `LogGroup`, `LogStream`, `MetricFilter` | | 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) | | CloudFormation | `CustomResource`, `Custom::DynamoDBReplica` (applied natively against DynamoDB, not via a provider Lambda), `StackSet`, `Stack` (nested stacks), `Custom::*` (Lambda-backed) | | CloudTrail | `Trail` | diff --git a/docs/services/index.md b/docs/services/index.md index 9d631d0c91..338bf3f02c 100644 --- a/docs/services/index.md +++ b/docs/services/index.md @@ -104,7 +104,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac | [AppConfig](appconfig.md) | `/applications/...`, `/deploymentstrategies/...` | REST JSON | 16 | | [AppConfigData](appconfig.md#data-plane) | `/configurationsessions`, `/configuration` | REST JSON | 2 | | [AppSync](appsync.md) | `/v1/apis/...` | REST JSON | 33 | -| [Amazon Bedrock](bedrock.md) | `/guardrails`, `/guardrails/{guardrailIdentifier}`, `/foundation-models`, `/foundation-models/{modelIdentifier}`, `/inference-profiles`, `/inference-profiles/{inferenceProfileIdentifier}`, `/resource-policy`, `/resource-policy/{resourceArn}`, `/tagResource`, `/untagResource`, `/listTagsForResource` | REST JSON | 16 | +| [Amazon Bedrock](bedrock.md) | `/guardrails`, `/guardrails/{guardrailIdentifier}`, `/foundation-models`, `/foundation-models/{modelIdentifier}`, `/inference-profiles`, `/inference-profiles/{inferenceProfileIdentifier}`, `/resource-policy`, `/resource-policy/{resourceArn}`, `/tagResource`, `/untagResource`, `/listTagsForResource` | REST JSON | 18 | | [Bedrock Runtime](bedrock-runtime.md) | `/model/{modelId}/converse`, `/model/{modelId}/invoke` | REST JSON | 2 (stub; streaming returns 501) | | [Bedrock AgentCore Control](bedrock-agentcore.md) | `/runtimes/*`, `/gateways/*`, `/memories/*`, `/identities/*`, `/browsers*`, `/browser-profiles*`, `/code-interpreters*`, `/harnesses*`, `/resourcepolicy/*`, `/tags/{resourceArn}` | REST JSON | 71 (+ 3 tagging via shared `/tags/{arn}` route) | | [Bedrock AgentCore](bedrock-agentcore.md#data-plane-invokeagentruntime) | `/runtimes/{agentRuntimeArn}/invocations` | REST JSON (binary payload) | 1 (canned-response stub) | diff --git a/src/main/java/io/floci/aws/services/bedrock/BedrockController.java b/src/main/java/io/floci/aws/services/bedrock/BedrockController.java index 3aa3d6e30b..0046c1f8f5 100644 --- a/src/main/java/io/floci/aws/services/bedrock/BedrockController.java +++ b/src/main/java/io/floci/aws/services/bedrock/BedrockController.java @@ -8,6 +8,7 @@ import io.floci.aws.core.common.JsonErrorResponseUtils; import io.floci.aws.core.common.PaginatedResult; import io.floci.aws.core.common.Pagination; import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.services.bedrock.model.ApplicationInferenceProfile; import io.floci.aws.services.bedrock.model.Guardrail; import jakarta.inject.Inject; import jakarta.ws.rs.Consumes; @@ -179,13 +180,13 @@ public class BedrockController { @QueryParam("nextToken") String nextToken, @Context HttpHeaders headers) { String region = regionResolver.resolveRegion(headers); - PaginatedResult page = bedrockService.listInferenceProfiles(typeEquals, + PaginatedResult page = bedrockService.listInferenceProfiles(typeEquals, Pagination.parseMaxResults(maxResults, "ValidationException"), nextToken, region); ObjectNode response = objectMapper.createObjectNode(); ArrayNode summaries = response.putArray("inferenceProfileSummaries"); - for (BedrockModelCatalog.InferenceProfile profile : page.items()) { - summaries.add(inferenceProfileNode(profile, region)); + for (BedrockService.InferenceProfileView profile : page.items()) { + summaries.add(inferenceProfileNode(profile)); } if (page.nextToken() != null) { response.put("nextToken", page.nextToken()); @@ -199,7 +200,31 @@ public class BedrockController { @Context HttpHeaders headers) { String region = regionResolver.resolveRegion(headers); return Response.ok(inferenceProfileNode( - bedrockService.getInferenceProfile(inferenceProfileIdentifier, region), region)).build(); + bedrockService.getInferenceProfile(inferenceProfileIdentifier, region))).build(); + } + + @POST + @Path("/inference-profiles") + public Response createInferenceProfile(@Context HttpHeaders headers, String body) { + String region = regionResolver.resolveRegion(headers); + JsonNode request = readTree(body); + ApplicationInferenceProfile profile = bedrockService.createApplicationInferenceProfile( + textOrNull(request, "inferenceProfileName"), textOrNull(request, "description"), + textOrNull(request.path("modelSource"), "copyFrom"), + applicationProfileTags(request.get("tags")), + textOrNull(request, "clientRequestToken"), region); + ObjectNode response = objectMapper.createObjectNode(); + response.put("inferenceProfileArn", profile.getInferenceProfileArn()); + response.put("status", "ACTIVE"); + return Response.status(201).entity(response).build(); + } + + @DELETE + @Path("/inference-profiles/{inferenceProfileIdentifier: .+}") + public Response deleteInferenceProfile(@PathParam("inferenceProfileIdentifier") String identifier, + @Context HttpHeaders headers) { + bedrockService.deleteApplicationInferenceProfile(identifier, regionResolver.resolveRegion(headers)); + return Response.ok(objectMapper.createObjectNode()).build(); } // Resource policies @@ -246,7 +271,7 @@ public class BedrockController { String region = regionResolver.resolveRegion(headers); JsonNode request = readTree(body); bedrockService.tagResource(textOrNull(request, "resourceARN"), - BedrockService.parseTagList(request.get("tags")), region); + bedrockTagResourceTags(request.get("tags")), region); return Response.ok(objectMapper.createObjectNode()).build(); } @@ -312,7 +337,7 @@ public class BedrockController { private ObjectNode foundationModelNode(BedrockModelCatalog.FoundationModel model, String region) { ObjectNode node = objectMapper.createObjectNode(); - node.put("modelArn", foundationModelArn(model.modelId(), region)); + node.put("modelArn", bedrockService.foundationModelArn(model.modelId(), region)); node.put("modelId", model.modelId()); node.put("modelName", model.modelName()); node.put("providerName", model.providerName()); @@ -328,27 +353,25 @@ public class BedrockController { return node; } - private ObjectNode inferenceProfileNode(BedrockModelCatalog.InferenceProfile profile, String region) { + private ObjectNode inferenceProfileNode(BedrockService.InferenceProfileView profile) { ObjectNode node = objectMapper.createObjectNode(); node.put("inferenceProfileName", profile.inferenceProfileName()); - node.put("inferenceProfileArn", regionResolver.buildArn("bedrock", region, - "inference-profile/" + profile.inferenceProfileId())); + node.put("inferenceProfileArn", profile.inferenceProfileArn()); node.put("inferenceProfileId", profile.inferenceProfileId()); + if (profile.description() != null) { + node.put("description", profile.description()); + } node.put("createdAt", iso8601(profile.createdAt())); - node.put("updatedAt", iso8601(profile.createdAt())); + node.put("updatedAt", iso8601(profile.updatedAt())); ArrayNode models = node.putArray("models"); - for (String destination : profile.routes().get(region)) { - models.addObject().put("modelArn", foundationModelArn(profile.modelId(), destination)); + for (String modelArn : profile.models()) { + models.addObject().put("modelArn", modelArn); } node.put("status", "ACTIVE"); - node.put("type", "SYSTEM_DEFINED"); + node.put("type", profile.type()); return node; } - private String foundationModelArn(String modelId, String region) { - return regionResolver.buildArn("bedrock", region, "", "foundation-model/" + modelId); - } - private ObjectNode guardrailSummaryNode(Guardrail guardrail) { ObjectNode node = objectMapper.createObjectNode(); node.put("id", guardrail.getGuardrailId()); @@ -390,4 +413,14 @@ public class BedrockController { } return value.asText(); } + + private static Map applicationProfileTags(JsonNode tags) { + BedrockTagValidator.validate(tags, "key", "value", "ValidationException", "tags"); + return BedrockService.parseTagList(tags); + } + + private static Map bedrockTagResourceTags(JsonNode tags) { + BedrockTagValidator.validateRequired(tags, "key", "value", "ValidationException", "tags"); + return BedrockService.parseTagList(tags); + } } diff --git a/src/main/java/io/floci/aws/services/bedrock/BedrockService.java b/src/main/java/io/floci/aws/services/bedrock/BedrockService.java index 024097762f..109b540255 100644 --- a/src/main/java/io/floci/aws/services/bedrock/BedrockService.java +++ b/src/main/java/io/floci/aws/services/bedrock/BedrockService.java @@ -17,6 +17,7 @@ import io.floci.aws.core.resource.ResourceProvider; import io.floci.aws.core.resource.SupportedResourceType; import io.floci.aws.core.storage.StorageBackend; import io.floci.aws.core.storage.StorageFactory; +import io.floci.aws.services.bedrock.model.ApplicationInferenceProfile; import io.floci.aws.services.bedrock.model.Guardrail; import io.floci.aws.services.kms.KmsService; import io.floci.aws.services.kms.model.KmsKey; @@ -74,7 +75,14 @@ public class BedrockService implements ResourceProvider { private static final List CUSTOMIZATION_TYPES = List.of("FINE_TUNING", "CONTINUED_PRE_TRAINING", "DISTILLATION"); private static final String FOUNDATION_MODEL_PREFIX = "foundation-model/"; private static final String INFERENCE_PROFILE_PREFIX = "inference-profile/"; + private static final String APPLICATION_INFERENCE_PROFILE_PREFIX = "application-inference-profile/"; private static final List INFERENCE_PROFILE_TYPES = List.of("SYSTEM_DEFINED", "APPLICATION"); + private static final Pattern APPLICATION_PROFILE_NAME_PATTERN = + Pattern.compile("([0-9a-zA-Z][ _-]?)+"); + private static final Pattern APPLICATION_PROFILE_DESCRIPTION_PATTERN = + Pattern.compile("([0-9a-zA-Z:.][ _-]?)+"); + private static final Pattern IDEMPOTENCY_TOKEN_PATTERN = + Pattern.compile("[a-zA-Z0-9]([-a-zA-Z0-9]{0,254}[a-zA-Z0-9])?"); /** {@code TagList} from the AWS model: at most 200 items on one request. */ private static final int TAG_LIST_MAX = 200; @@ -130,6 +138,7 @@ public class BedrockService implements ResourceProvider { * Region that received {@code PutResourcePolicy}, so one ARN can hold a different policy per Region. */ private final StorageBackend guardrailProfilePolicies; + private final StorageBackend applicationInferenceProfiles; private final RegionResolver regionResolver; private final ObjectMapper objectMapper; private final KmsService kmsService; @@ -141,14 +150,19 @@ public class BedrockService implements ResourceProvider { new TypeReference>() {}), storageFactory.create("bedrock", "bedrock-guardrail-profile-policies.json", new TypeReference>() {}), + storageFactory.create("bedrock", "bedrock-application-inference-profiles.json", + new TypeReference>() {}), regionResolver, objectMapper, kmsService); } BedrockService(StorageBackend guardrails, - StorageBackend guardrailProfilePolicies, RegionResolver regionResolver, + StorageBackend guardrailProfilePolicies, + StorageBackend applicationInferenceProfiles, + RegionResolver regionResolver, ObjectMapper objectMapper, KmsService kmsService) { this.guardrails = guardrails; this.guardrailProfilePolicies = guardrailProfilePolicies; + this.applicationInferenceProfiles = applicationInferenceProfiles; this.regionResolver = regionResolver; this.objectMapper = objectMapper; this.kmsService = kmsService; @@ -308,25 +322,194 @@ public class BedrockService implements ResourceProvider { throw invalidModelIdentifier(); } - public PaginatedResult listInferenceProfiles(String typeEquals, - Integer maxResults, - String nextToken, String region) { - requireOneOf("typeEquals", typeEquals, INFERENCE_PROFILE_TYPES); - // Only system-defined profiles exist: application inference profiles cannot be created yet. - List profiles = "APPLICATION".equals(typeEquals) - ? List.of() - : BedrockModelCatalog.profilesFrom(region); - return Pagination.paginate(profiles, BedrockModelCatalog.InferenceProfile::inferenceProfileId, - maxResults, nextToken, MAX_PAGE, "ValidationException"); + public record InferenceProfileView(String inferenceProfileId, String inferenceProfileArn, + String inferenceProfileName, String description, List models, + Instant createdAt, Instant updatedAt, String type) { } - public BedrockModelCatalog.InferenceProfile getInferenceProfile(String inferenceProfileIdentifier, String region) { + public synchronized ApplicationInferenceProfile createApplicationInferenceProfile( + String name, String description, String copyFrom, Map tags, String region) { + return createApplicationInferenceProfile(name, description, copyFrom, tags, null, region); + } + + public synchronized ApplicationInferenceProfile createApplicationInferenceProfile( + String name, String description, String copyFrom, Map tags, + String clientRequestToken, String region) { + if (clientRequestToken != null) { + if (clientRequestToken.length() > 256 || !IDEMPOTENCY_TOKEN_PATTERN.matcher(clientRequestToken).matches()) { + throw new AwsException("ValidationException", "clientRequestToken is invalid.", 400); + } + Optional previous = applicationsIn(region).stream() + .filter(profile -> clientRequestToken.equals(profile.getClientRequestToken())) + .findFirst(); + if (previous.isPresent()) { + return previous.get(); + } + } + if (name == null || name.length() > 64 || !APPLICATION_PROFILE_NAME_PATTERN.matcher(name).matches()) { + throw new AwsException("ValidationException", "inferenceProfileName is invalid.", 400); + } + if (description != null && (description.length() > 200 + || !APPLICATION_PROFILE_DESCRIPTION_PATTERN.matcher(description).matches())) { + throw new AwsException("ValidationException", "description is invalid.", 400); + } + List models = modelsFromSource(copyFrom, region); + if (applicationsIn(region).stream().anyMatch(profile -> name.equals(profile.getInferenceProfileName()))) { + throw new AwsException("ConflictException", "Inference profile " + name + " already exists.", 400); + } + + String id = UUID.randomUUID().toString().replace("-", "").substring(0, 12); + String arn = regionResolver.buildArn("bedrock", region, APPLICATION_INFERENCE_PROFILE_PREFIX + id); + Map initialTags = tags == null ? Map.of() : Map.copyOf(tags); + if (initialTags.size() > TAGS_PER_RESOURCE_MAX) { + throw tooManyTags(arn, initialTags.size()); + } + Instant now = Instant.now(); + ApplicationInferenceProfile profile = new ApplicationInferenceProfile(); + profile.setInferenceProfileId(id); + profile.setInferenceProfileArn(arn); + profile.setInferenceProfileName(name); + profile.setDescription(description); + profile.setModels(models); + profile.setCreatedAt(now); + profile.setUpdatedAt(now); + profile.setTags(initialTags); + profile.setAccountId(regionResolver.getAccountId()); + profile.setRegion(region); + profile.setClientRequestToken(clientRequestToken); + applicationInferenceProfiles.put(applicationProfileKey(region, id), profile); + LOG.infov("Created Bedrock application inference profile: {0}", id); + return profile; + } + + public ApplicationInferenceProfile getApplicationInferenceProfile(String identifier, String region) { + String id = applicationProfileIdOf(identifier, region); + return applicationInferenceProfiles.get(applicationProfileKey(region, id)) + .orElseThrow(() -> profileNotFound(identifier)); + } + + public synchronized void deleteApplicationInferenceProfile(String identifier, String region) { + ApplicationInferenceProfile profile = getApplicationInferenceProfile(identifier, region); + applicationInferenceProfiles.delete(applicationProfileKey(region, profile.getInferenceProfileId())); + LOG.infov("Deleted Bedrock application inference profile: {0}", profile.getInferenceProfileId()); + } + + public PaginatedResult listInferenceProfiles(String typeEquals, + Integer maxResults, + String nextToken, String region) { + requireOneOf("typeEquals", typeEquals, INFERENCE_PROFILE_TYPES); + List profiles = new ArrayList<>(); + if (!"APPLICATION".equals(typeEquals)) { + BedrockModelCatalog.profilesFrom(region).stream() + .map(profile -> systemProfileView(profile, region)).forEach(profiles::add); + } + if (!"SYSTEM_DEFINED".equals(typeEquals)) { + applicationsIn(region).stream().map(BedrockService::applicationProfileView).forEach(profiles::add); + } + String scope = "bedrock-inference-profiles:" + regionResolver.getAccountId() + ":" + region + ":" + + (typeEquals == null ? "ALL" : typeEquals); + return Pagination.paginate(profiles, InferenceProfileView::inferenceProfileId, + maxResults, nextToken, MAX_PAGE, MAX_PAGE, 2048, "ValidationException", scope, true); + } + + public InferenceProfileView getInferenceProfile(String inferenceProfileIdentifier, String region) { + AwsArnUtils.Arn arn = arnOf(inferenceProfileIdentifier); + if (arn != null && arn.resource().startsWith(APPLICATION_INFERENCE_PROFILE_PREFIX)) { + return applicationProfileView(getApplicationInferenceProfile(inferenceProfileIdentifier, region)); + } + if (arn == null) { + Optional application = applicationInferenceProfiles.get( + applicationProfileKey(region, inferenceProfileIdentifier)); + if (application.isPresent()) { + return applicationProfileView(application.get()); + } + } String profileId = inferenceProfileIdOf(inferenceProfileIdentifier, region); return BedrockModelCatalog.profilesFrom(region).stream() .filter(profile -> profile.inferenceProfileId().equals(profileId)) + .map(profile -> systemProfileView(profile, region)) .findFirst() - .orElseThrow(() -> new AwsException("ResourceNotFoundException", - "The inference profile " + inferenceProfileIdentifier + " was not found.", 404)); + .orElseThrow(() -> profileNotFound(inferenceProfileIdentifier)); + } + + private List modelsFromSource(String copyFrom, String region) { + AwsArnUtils.Arn arn = arnOf(copyFrom); + if (arn == null || !isBedrockArnIn(arn, region)) { + throw new AwsException("ValidationException", "modelSource.copyFrom must be a Bedrock ARN in this Region.", 400); + } + if (arn.resource().startsWith(FOUNDATION_MODEL_PREFIX) && arn.accountId().isEmpty()) { + String modelId = arn.resource().substring(FOUNDATION_MODEL_PREFIX.length()); + getFoundationModel(copyFrom, region); + if (BedrockModelCatalog.MODELS.stream().noneMatch(model -> model.modelId().equals(modelId) + && model.servedInRegion(region))) { + throw new AwsException("ValidationException", "The foundation model is not served in this Region.", 400); + } + return List.of(copyFrom); + } + if (arn.resource().startsWith(INFERENCE_PROFILE_PREFIX) + && arn.accountId().equals(regionResolver.getAccountId())) { + String profileId = arn.resource().substring(INFERENCE_PROFILE_PREFIX.length()); + BedrockModelCatalog.InferenceProfile profile = BedrockModelCatalog.profilesFrom(region).stream() + .filter(candidate -> candidate.inferenceProfileId().equals(profileId)) + .findFirst().orElseThrow(() -> profileNotFound(copyFrom)); + return systemProfileModelArns(profile, region); + } + throw new AwsException("ValidationException", "modelSource.copyFrom must name a foundation model " + + "or system-defined inference profile.", 400); + } + + private InferenceProfileView systemProfileView(BedrockModelCatalog.InferenceProfile profile, String region) { + return new InferenceProfileView(profile.inferenceProfileId(), regionResolver.buildArn("bedrock", region, + INFERENCE_PROFILE_PREFIX + profile.inferenceProfileId()), profile.inferenceProfileName(), + null, systemProfileModelArns(profile, region), profile.createdAt(), profile.createdAt(), + "SYSTEM_DEFINED"); + } + + private List systemProfileModelArns(BedrockModelCatalog.InferenceProfile profile, String region) { + return profile.routes().get(region).stream() + .map(destination -> foundationModelArn(profile.modelId(), destination)).toList(); + } + + public String foundationModelArn(String modelId, String region) { + return regionResolver.buildArn("bedrock", region, "", FOUNDATION_MODEL_PREFIX + modelId); + } + + private static InferenceProfileView applicationProfileView(ApplicationInferenceProfile profile) { + return new InferenceProfileView(profile.getInferenceProfileId(), profile.getInferenceProfileArn(), + profile.getInferenceProfileName(), profile.getDescription(), profile.getModels(), + profile.getCreatedAt(), profile.getUpdatedAt(), "APPLICATION"); + } + + private List applicationsIn(String region) { + String prefix = regionResolver.getAccountId() + "::" + region + "::"; + return applicationInferenceProfiles.scan(key -> key.startsWith(prefix)); + } + + private String applicationProfileKey(String region, String id) { + return regionResolver.getAccountId() + "::" + region + "::" + id; + } + + private String applicationProfileIdOf(String identifier, String region) { + AwsArnUtils.Arn arn = arnOf(identifier); + if (arn == null) { + return identifier; + } + if (!"bedrock".equals(arn.service()) || arn.accountId().isEmpty()) { + throw new AwsException("ValidationException", "The provided inference profile identifier is invalid.", 400); + } + if (!arn.accountId().equals(regionResolver.getAccountId())) { + throw new AwsException("AccessDeniedException", + "You don't have access to the inference profile " + identifier + ".", 403); + } + if (!isBedrockArnIn(arn, region) || !arn.resource().startsWith(APPLICATION_INFERENCE_PROFILE_PREFIX)) { + throw profileNotFound(identifier); + } + return arn.resource().substring(APPLICATION_INFERENCE_PROFILE_PREFIX.length()); + } + + private static AwsException profileNotFound(String identifier) { + return new AwsException("ResourceNotFoundException", + "The inference profile " + identifier + " was not found.", 404); } /** @@ -466,6 +649,10 @@ public class BedrockService implements ResourceProvider { // Tags public Map listTags(String resourceArn, String region) { + if (isApplicationProfileResource(resourceArn, region)) { + ApplicationInferenceProfile profile = getApplicationInferenceProfile(resourceArn, region); + return profile.getTags() != null ? Map.copyOf(profile.getTags()) : Map.of(); + } Guardrail guardrail = findByArn(resourceArn, region); return guardrail.getTags() != null ? guardrail.getTags() : Map.of(); } @@ -476,6 +663,17 @@ public class BedrockService implements ResourceProvider { * the value of a key already present does not add to that total. */ public synchronized void tagResource(String resourceArn, Map tags, String region) { + if (isApplicationProfileResource(resourceArn, region)) { + ApplicationInferenceProfile profile = getApplicationInferenceProfile(resourceArn, region); + Map merged = new HashMap<>(profile.getTags() != null ? profile.getTags() : Map.of()); + merged.putAll(tags); + if (merged.size() > TAGS_PER_RESOURCE_MAX) { + throw tooManyTags(profile.getInferenceProfileArn(), merged.size()); + } + applicationInferenceProfiles.put(applicationProfileKey(region, profile.getInferenceProfileId()), + applicationProfileWithTags(profile, merged)); + return; + } Guardrail guardrail = findByArn(resourceArn, region); Map merged = guardrail.getTags() == null ? new HashMap<>() @@ -489,6 +687,16 @@ public class BedrockService implements ResourceProvider { } public synchronized void untagResource(String resourceArn, List tagKeys, String region) { + if (isApplicationProfileResource(resourceArn, region)) { + ApplicationInferenceProfile profile = getApplicationInferenceProfile(resourceArn, region); + Map remaining = new HashMap<>(profile.getTags() != null ? profile.getTags() : Map.of()); + if (tagKeys != null) { + tagKeys.forEach(remaining::remove); + } + applicationInferenceProfiles.put(applicationProfileKey(region, profile.getInferenceProfileId()), + applicationProfileWithTags(profile, remaining)); + return; + } Guardrail guardrail = findByArn(resourceArn, region); if (guardrail.getTags() != null && tagKeys != null) { tagKeys.forEach(guardrail.getTags()::remove); @@ -512,12 +720,50 @@ public class BedrockService implements ResourceProvider { guardrail.getCreatedAt() != null ? guardrail.getCreatedAt() : Instant.now(), guardrail.getTags() != null ? guardrail.getTags() : Map.of()))); } + for (String key : applicationInferenceProfiles.keys()) { + applicationInferenceProfiles.get(key).ifPresent(profile -> resources.add(new ExplorerResource( + profile.getInferenceProfileArn(), "bedrock:application-inference-profile", "bedrock", + profile.getRegion(), profile.getAccountId(), profile.getCreatedAt(), + profile.getTags() != null ? profile.getTags() : Map.of()))); + } return resources; } @Override public Set getSupportedResourceTypes() { - return Set.of(new SupportedResourceType("bedrock:guardrail", "bedrock", true)); + return Set.of(new SupportedResourceType("bedrock:guardrail", "bedrock", true), + new SupportedResourceType("bedrock:application-inference-profile", "bedrock", true)); + } + + private boolean isApplicationProfileResource(String identifier, String region) { + if (identifier == null) { + return false; + } + if (!AwsArnUtils.looksLikeArn(identifier)) { + return applicationInferenceProfiles.get(applicationProfileKey(region, identifier)).isPresent(); + } + try { + return AwsArnUtils.parse(identifier).resource().startsWith(APPLICATION_INFERENCE_PROFILE_PREFIX); + } catch (IllegalArgumentException e) { + return false; + } + } + + private static ApplicationInferenceProfile applicationProfileWithTags(ApplicationInferenceProfile source, + Map tags) { + ApplicationInferenceProfile updated = new ApplicationInferenceProfile(); + updated.setInferenceProfileId(source.getInferenceProfileId()); + updated.setInferenceProfileArn(source.getInferenceProfileArn()); + updated.setInferenceProfileName(source.getInferenceProfileName()); + updated.setDescription(source.getDescription()); + updated.setModels(source.getModels()); + updated.setCreatedAt(source.getCreatedAt()); + updated.setUpdatedAt(source.getUpdatedAt()); + updated.setTags(Map.copyOf(tags)); + updated.setAccountId(source.getAccountId()); + updated.setRegion(source.getRegion()); + updated.setClientRequestToken(source.getClientRequestToken()); + return updated; } // Helpers diff --git a/src/main/java/io/floci/aws/services/bedrock/BedrockTagValidator.java b/src/main/java/io/floci/aws/services/bedrock/BedrockTagValidator.java new file mode 100644 index 0000000000..9e5771893a --- /dev/null +++ b/src/main/java/io/floci/aws/services/bedrock/BedrockTagValidator.java @@ -0,0 +1,61 @@ +package io.floci.aws.services.bedrock; + +import com.fasterxml.jackson.databind.JsonNode; +import io.floci.aws.core.common.AwsException; + +import java.util.regex.Pattern; + +/** Validates the Bedrock TagList shape. */ +public final class BedrockTagValidator { + + private static final int TAG_LIST_MAX = 200; + private static final int TAG_KEY_MIN = 1; + private static final int TAG_KEY_MAX = 128; + private static final int TAG_VALUE_MAX = 256; + private static final Pattern TAG_PATTERN = Pattern.compile("[a-zA-Z0-9\\s._:/=+@-]*"); + + private BedrockTagValidator() { + } + + public static void validateRequired(JsonNode tags, String keyProperty, String valueProperty, + String errorCode, String propertyName) { + if (tags == null || tags.isNull()) { + throw invalid(errorCode, propertyName + " is required."); + } + validate(tags, keyProperty, valueProperty, errorCode, propertyName); + } + + public static void validate(JsonNode tags, String keyProperty, String valueProperty, + String errorCode, String propertyName) { + if (tags == null || tags.isNull()) { + return; + } + if (!tags.isArray()) { + throw invalid(errorCode, propertyName + " must be an array."); + } + if (tags.size() > TAG_LIST_MAX) { + throw invalid(errorCode, propertyName + " must have at most " + TAG_LIST_MAX + " items."); + } + for (JsonNode tag : tags) { + JsonNode key = tag.path(keyProperty); + JsonNode value = tag.path(valueProperty); + if (!tag.isObject() || !key.isTextual() || !value.isTextual()) { + throw invalid(errorCode, propertyName + " items require string " + + keyProperty + " and " + valueProperty + "."); + } + String keyText = key.textValue(); + String valueText = value.textValue(); + if (keyText.length() < TAG_KEY_MIN || keyText.length() > TAG_KEY_MAX + || !TAG_PATTERN.matcher(keyText).matches()) { + throw invalid(errorCode, propertyName + " item " + keyProperty + " is invalid."); + } + if (valueText.length() > TAG_VALUE_MAX || !TAG_PATTERN.matcher(valueText).matches()) { + throw invalid(errorCode, propertyName + " item " + valueProperty + " is invalid."); + } + } + } + + private static AwsException invalid(String errorCode, String message) { + return new AwsException(errorCode, message, 400); + } +} diff --git a/src/main/java/io/floci/aws/services/bedrock/model/ApplicationInferenceProfile.java b/src/main/java/io/floci/aws/services/bedrock/model/ApplicationInferenceProfile.java new file mode 100644 index 0000000000..5bf4147363 --- /dev/null +++ b/src/main/java/io/floci/aws/services/bedrock/model/ApplicationInferenceProfile.java @@ -0,0 +1,111 @@ +package io.floci.aws.services.bedrock.model; + +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.time.Instant; +import java.util.List; +import java.util.Map; + +@RegisterForReflection +public class ApplicationInferenceProfile { + + private String inferenceProfileId; + private String inferenceProfileArn; + private String inferenceProfileName; + private String description; + private List models; + private Instant createdAt; + private Instant updatedAt; + private Map tags; + private String accountId; + private String region; + private String clientRequestToken; + + public String getInferenceProfileId() { + return inferenceProfileId; + } + + public void setInferenceProfileId(String inferenceProfileId) { + this.inferenceProfileId = inferenceProfileId; + } + + public String getInferenceProfileArn() { + return inferenceProfileArn; + } + + public void setInferenceProfileArn(String inferenceProfileArn) { + this.inferenceProfileArn = inferenceProfileArn; + } + + public String getInferenceProfileName() { + return inferenceProfileName; + } + + public void setInferenceProfileName(String inferenceProfileName) { + this.inferenceProfileName = inferenceProfileName; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public List getModels() { + return models; + } + + public void setModels(List models) { + this.models = models; + } + + public Instant getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + + public Instant getUpdatedAt() { + return updatedAt; + } + + public void setUpdatedAt(Instant updatedAt) { + this.updatedAt = updatedAt; + } + + public Map getTags() { + return tags; + } + + public void setTags(Map tags) { + this.tags = tags; + } + + public String getAccountId() { + return accountId; + } + + public void setAccountId(String accountId) { + this.accountId = accountId; + } + + public String getRegion() { + return region; + } + + public void setRegion(String region) { + this.region = region; + } + + public String getClientRequestToken() { + return clientRequestToken; + } + + public void setClientRequestToken(String clientRequestToken) { + this.clientRequestToken = clientRequestToken; + } +} diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/BedrockCfnProvisioner.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/BedrockCfnProvisioner.java new file mode 100644 index 0000000000..efaa674391 --- /dev/null +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/BedrockCfnProvisioner.java @@ -0,0 +1,261 @@ +package io.floci.aws.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.ObjectNode; +import io.floci.aws.core.common.AwsException; +import io.floci.aws.services.bedrock.BedrockService; +import io.floci.aws.services.bedrock.BedrockTagValidator; +import io.floci.aws.services.bedrock.model.ApplicationInferenceProfile; +import io.floci.aws.services.cloudformation.model.StackResource; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; + +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.TreeSet; + +/** Provisions an application inference profile through the Bedrock control plane. */ +@ApplicationScoped +public class BedrockCfnProvisioner implements CfnResourceProvisioner { + + private static final String TYPE = "AWS::Bedrock::ApplicationInferenceProfile"; + private static final String NOT_FOUND = "ResourceNotFoundException"; + private static final String PRIOR_TAGS = "__FlociBedrockProfilePriorTags"; + private static final String MANAGED_TAG_KEYS = "__FlociBedrockProfileManagedTagKeys"; + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private final BedrockService bedrockService; + + @Inject + public BedrockCfnProvisioner(BedrockService bedrockService) { + this.bedrockService = bedrockService; + } + + @Override + public Set resourceTypes() { + return Set.of(TYPE); + } + + @Override + public Map> jsonAttributes() { + return Map.of(TYPE, Set.of("Models")); + } + + @Override + public void provision(StackResource resource, JsonNode properties, ProvisionContext ctx) { + Map attributesBefore = Map.copyOf(resource.getAttributes()); + String name = required(ctx.resolveOptional(properties, "InferenceProfileName"), "InferenceProfileName"); + String description = ctx.resolveOptional(properties, "Description"); + String source = modelSource(properties, ctx); + Map tags = tags(properties, ctx); + Set previouslyManagedTagKeys = managedTagKeys(attributesBefore); + + ApplicationInferenceProfile existing = ctx.isUpdate() + && !CfnResourceDispatcher.isStub(ctx.priorPhysicalId(), attributesBefore) + ? bedrockService.getApplicationInferenceProfile(ctx.priorPhysicalId(), ctx.region()) : null; + if (existing != null && !ctx.changes(TYPE, properties).requiresReplacement()) { + resource.getAttributes().remove(PRIOR_TAGS); + Map existingTags = existing.getTags() == null ? Map.of() : existing.getTags(); + if (tagStateChanged(existingTags, previouslyManagedTagKeys, tags)) { + ObjectNode snapshot = MAPPER.createObjectNode(); + snapshot.put("region", ctx.region()); + snapshot.put("managedTagKeys", attributesBefore.get(MANAGED_TAG_KEYS)); + Set touchedKeys = new HashSet<>(previouslyManagedTagKeys); + touchedKeys.addAll(tags.keySet()); + CfnRollback.putTagSnapshot(snapshot, touchedKeys, existingTags); + resource.getAttributes().put(PRIOR_TAGS, snapshot.toString()); + CfnRollback.guarded(resource, ctx, false, () -> { }, () -> restoreTags(resource), () -> { + reconcileTags(existing.getInferenceProfileArn(), previouslyManagedTagKeys, tags, ctx.region()); + publish(resource, bedrockService.getApplicationInferenceProfile( + existing.getInferenceProfileId(), ctx.region())); + }); + } else { + publish(resource, bedrockService.getApplicationInferenceProfile(existing.getInferenceProfileId(), + ctx.region())); + } + } else { + ApplicationInferenceProfile created = bedrockService.createApplicationInferenceProfile(name, + description, source, tags, ctx.region()); + publish(resource, created); + } + recordManagedTagKeys(resource, tags.keySet()); + ReplacementCleanup.record(resource, ctx, attributesBefore); + } + + private static String modelSource(JsonNode properties, ProvisionContext ctx) { + JsonNode source = properties == null ? null : properties.get("ModelSource"); + String copyFrom = source == null ? null : ctx.engine().resolve(source.path("CopyFrom")); + return required(copyFrom, "ModelSource.CopyFrom"); + } + + private static Map tags(JsonNode properties, ProvisionContext ctx) { + if (properties == null || !properties.has("Tags")) { + return Map.of(); + } + JsonNode resolved = ctx.engine().resolveNode(properties.get("Tags")); + if (resolved == null || !resolved.isArray()) { + throw new AwsException("ValidationError", TYPE + " Tags must be an array.", 400); + } + BedrockTagValidator.validate(resolved, "Key", "Value", "ValidationError", + TYPE + " Tags"); + Map tags = new LinkedHashMap<>(); + for (JsonNode tag : resolved) { + tags.put(tag.path("Key").textValue(), tag.path("Value").textValue()); + } + return tags; + } + + private static String required(String value, String property) { + if (value == null || value.isBlank()) { + throw new AwsException("ValidationError", TYPE + " requires " + property, 400); + } + return value; + } + + private static void publish(StackResource resource, ApplicationInferenceProfile profile) { + String id = profile.getInferenceProfileId(); + resource.setPhysicalId(id); + resource.getAttributes().put("InferenceProfileId", id); + resource.getAttributes().put("InferenceProfileArn", profile.getInferenceProfileArn()); + resource.getAttributes().put("InferenceProfileIdentifier", id); + resource.getAttributes().put("Status", "ACTIVE"); + resource.getAttributes().put("Type", "APPLICATION"); + resource.getAttributes().put("CreatedAt", profile.getCreatedAt().toString()); + resource.getAttributes().put("UpdatedAt", profile.getUpdatedAt().toString()); + ArrayNode models = MAPPER.createArrayNode(); + for (String modelArn : profile.getModels()) { + models.addObject().put("ModelArn", modelArn); + } + resource.getAttributes().put("Models", models.toString()); + } + + private static boolean tagStateChanged(Map current, Set previouslyManaged, + Map desired) { + return !previouslyManaged.equals(desired.keySet()) || previouslyManaged.stream() + .anyMatch(key -> !Objects.equals(current.get(key), desired.get(key))); + } + + private void reconcileTags(String arn, Set managedKeys, Map desired, String region) { + CfnRollback.reconcileTags(managedKeys, desired, + keys -> bedrockService.untagResource(arn, keys, region), + tags -> bedrockService.tagResource(arn, tags, region)); + } + + private void restoreTags(StackResource resource) { + JsonNode snapshot = CfnRollback.updateSnapshot(resource, PRIOR_TAGS); + if (snapshot == null) { + return; + } + String region = CfnRollback.snapshotText(snapshot, "region"); + List managedKeys = CfnRollback.snapshotTagKeys(snapshot); + Map tags = CfnRollback.snapshotTags(snapshot); + ApplicationInferenceProfile profile = bedrockService.getApplicationInferenceProfile( + resource.getPhysicalId(), region); + CfnRollback.reconcileTags(managedKeys, tags, + keys -> bedrockService.untagResource(profile.getInferenceProfileArn(), keys, region), + desired -> bedrockService.tagResource(profile.getInferenceProfileArn(), desired, region)); + restoreManagedTagKeys(resource, CfnRollback.snapshotText(snapshot, "managedTagKeys")); + resource.getAttributes().remove(PRIOR_TAGS); + } + + private static Set managedTagKeys(Map attributes) { + String raw = attributes.get(MANAGED_TAG_KEYS); + if (raw == null) { + return Set.of(); + } + try { + JsonNode keys = MAPPER.readTree(raw); + if (keys == null || !keys.isArray()) { + throw new IllegalArgumentException("managed tag keys are not an array"); + } + Set result = new HashSet<>(); + for (JsonNode key : keys) { + if (!key.isTextual()) { + throw new IllegalArgumentException("managed tag key is not a string"); + } + result.add(key.textValue()); + } + return result; + } catch (JsonProcessingException | IllegalArgumentException e) { + throw new AwsException("InternalFailure", "Invalid Bedrock profile managed-tag metadata: " + + e.getMessage(), 500); + } + } + + private static void recordManagedTagKeys(StackResource resource, Set keys) { + if (keys.isEmpty()) { + resource.getAttributes().remove(MANAGED_TAG_KEYS); + return; + } + try { + resource.getAttributes().put(MANAGED_TAG_KEYS, MAPPER.writeValueAsString(new TreeSet<>(keys))); + } catch (JsonProcessingException e) { + throw new AwsException("InternalFailure", "Failed to store Bedrock profile managed-tag metadata: " + + e.getMessage(), 500); + } + } + + private static void restoreManagedTagKeys(StackResource resource, String keys) { + if (keys == null) { + resource.getAttributes().remove(MANAGED_TAG_KEYS); + } else { + resource.getAttributes().put(MANAGED_TAG_KEYS, keys); + } + } + + @Override + public boolean rollbackUpdate(StackResource resource) { + if (ReplacementCleanup.rollback(resource, this::delete)) { + resource.getAttributes().remove(PRIOR_TAGS); + return true; + } + restoreTags(resource); + return true; + } + + @Override + public boolean hasReplacementUpdate(StackResource resource) { + return ReplacementCleanup.hasReplacement(resource); + } + + @Override + public void mergeFailedUpdateResourceTracking(StackResource previous, StackResource attempted) { + String priorTags = attempted.getAttributes().get(PRIOR_TAGS); + if (priorTags != null) { + previous.getAttributes().put(PRIOR_TAGS, priorTags); + } + } + + @Override + public String updateCleanupPhysicalId(StackResource resource) { + return ReplacementCleanup.cleanupPhysicalId(resource); + } + + @Override + public UpdateCleanupResult completeUpdate(StackResource resource) { + resource.getAttributes().remove(PRIOR_TAGS); + return ReplacementCleanup.complete(resource, this::delete); + } + + @Override + public void clearUpdate(StackResource resource) { + resource.getAttributes().remove(PRIOR_TAGS); + ReplacementCleanup.clear(resource); + } + + @Override + public void delete(String resourceType, String physicalId, String region) { + if (physicalId == null || physicalId.isBlank()) { + return; + } + CfnDeletes.safeDelete("Bedrock application inference profile", physicalId, + () -> bedrockService.deleteApplicationInferenceProfile(physicalId, region), NOT_FOUND); + } +} diff --git a/src/main/resources/cloudformation/create-only-properties.json b/src/main/resources/cloudformation/create-only-properties.json index d3c39754e5..96c6a0ad8f 100644 --- a/src/main/resources/cloudformation/create-only-properties.json +++ b/src/main/resources/cloudformation/create-only-properties.json @@ -167,6 +167,11 @@ "JobQueueName", "JobQueueType" ], + "AWS::Bedrock::ApplicationInferenceProfile": [ + "Description", + "InferenceProfileName", + "ModelSource" + ], "AWS::BedrockAgentCore::Memory": [ "Name", "EncryptionKeyArn" diff --git a/src/test/java/io/floci/aws/services/bedrock/BedrockApplicationInferenceProfileIntegrationTest.java b/src/test/java/io/floci/aws/services/bedrock/BedrockApplicationInferenceProfileIntegrationTest.java new file mode 100644 index 0000000000..d8e27c6cee --- /dev/null +++ b/src/test/java/io/floci/aws/services/bedrock/BedrockApplicationInferenceProfileIntegrationTest.java @@ -0,0 +1,204 @@ +package io.floci.aws.services.bedrock; + +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.RestAssured; +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; +import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; +import software.amazon.awssdk.http.urlconnection.UrlConnectionHttpClient; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.bedrock.BedrockClient; +import software.amazon.awssdk.services.bedrock.model.AccessDeniedException; +import software.amazon.awssdk.services.bedrock.model.CreateInferenceProfileResponse; +import software.amazon.awssdk.services.bedrock.model.GetInferenceProfileResponse; +import software.amazon.awssdk.services.bedrock.model.InferenceProfileModelSource; +import software.amazon.awssdk.services.bedrock.model.InferenceProfileStatus; +import software.amazon.awssdk.services.bedrock.model.InferenceProfileSummary; +import software.amazon.awssdk.services.bedrock.model.InferenceProfileType; +import software.amazon.awssdk.services.bedrock.model.ResourceNotFoundException; +import software.amazon.awssdk.services.bedrock.model.Tag; + +import java.net.URI; +import java.util.Collections; +import java.util.List; +import java.util.UUID; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@QuarkusTest +class BedrockApplicationInferenceProfileIntegrationTest { + + private static final String ACCOUNT = "741623800008"; + private static final String REGION = "us-east-1"; + private static final String MODEL_ARN = + "arn:aws:bedrock:us-east-1::foundation-model/amazon.nova-micro-v1:0"; + + @Test + void directCreateRejectsMalformedSuppliedTags() { + String tooLongKey = "k".repeat(129); + String tooLongValue = "v".repeat(257); + String tooManyTags = "[" + String.join(",", Collections.nCopies(201, + "{\"key\":\"team\",\"value\":\"ml\"}")) + "]"; + for (String tags : List.of("{}", "[{}]", "[{\"key\":\"team\"}]", + "[{\"key\":12,\"value\":\"ml\"}]", "[{\"key\":\"team\",\"value\":true}]", + "[{\"key\":\"\",\"value\":\"ml\"}]", "[{\"key\":\"bad?key\",\"value\":\"ml\"}]", + "[{\"key\":\"team\",\"value\":\"bad?value\"}]", + "[{\"key\":\"" + tooLongKey + "\",\"value\":\"ml\"}]", + "[{\"key\":\"team\",\"value\":\"" + tooLongValue + "\"}]", tooManyTags)) { + String name = "malformed-tags-" + UUID.randomUUID(); + given().contentType("application/json") + .body(""" + {"inferenceProfileName":"%s", + "modelSource":{"copyFrom":"%s"},"tags":%s} + """.formatted(name, MODEL_ARN, tags)) + .when().post("/inference-profiles") + .then().statusCode(400).body("__type", equalTo("ValidationException")); + List names = given().when().get("/inference-profiles?type=APPLICATION&maxResults=1000") + .then().statusCode(200).extract().path("inferenceProfileSummaries.inferenceProfileName"); + assertFalse(names.contains(name), tags); + } + } + + @Test + void tagResourceRequiresAndValidatesTagsWithoutChangingApplicationProfileTags() { + String name = "tag-resource-validation-" + UUID.randomUUID(); + String arn = given().contentType("application/json").body(""" + {"inferenceProfileName":"%s","modelSource":{"copyFrom":"%s"}, + "tags":[{"key":"team","value":"original"}]} + """.formatted(name, MODEL_ARN)) + .when().post("/inference-profiles") + .then().statusCode(201).extract().path("inferenceProfileArn"); + + try (BedrockClient client = client("000000000000", REGION)) { + try { + given().contentType("application/json").body(""" + {"resourceARN":"%s"} + """.formatted(arn)) + .when().post("/tagResource") + .then().statusCode(400).body("__type", equalTo("ValidationException")); + given().contentType("application/json").body(""" + {"resourceARN":"%s","tags":[{"key":"bad?key","value":"changed"}]} + """.formatted(arn)) + .when().post("/tagResource") + .then().statusCode(400).body("__type", equalTo("ValidationException")); + assertEquals(List.of(Tag.builder().key("team").value("original").build()), + client.listTagsForResource(request -> request.resourceARN(arn)).tags()); + } finally { + client.deleteInferenceProfile(request -> request.inferenceProfileIdentifier(arn)); + } + } + } + + @Test + void directCreateAllowsWhitespaceKeyAndMaximumTagLengths() { + String name = "boundary-tags-" + UUID.randomUUID(); + String maxKey = "k".repeat(128); + String maxValue = "v".repeat(256); + String body = """ + {"inferenceProfileName":"%s","modelSource":{"copyFrom":"%s"}, + "tags":[{"key":" ","value":""},{"key":"%s","value":"%s"}]} + """.formatted(name, MODEL_ARN, maxKey, maxValue); + String arn = given().contentType("application/json").body(body) + .when().post("/inference-profiles") + .then().statusCode(201).extract().path("inferenceProfileArn"); + + try (BedrockClient client = client("000000000000", REGION)) { + try { + List tags = client.listTagsForResource(request -> request.resourceARN(arn)).tags(); + assertTrue(tags.contains(Tag.builder().key(" ").value("").build())); + assertTrue(tags.contains(Tag.builder().key(maxKey).value(maxValue).build())); + } finally { + client.deleteInferenceProfile(request -> request.inferenceProfileIdentifier(arn)); + } + } + } + + @Test + void directCreateStillAllowsOmittedTags() { + String name = "untagged-profile-" + UUID.randomUUID(); + try (BedrockClient client = client(ACCOUNT, REGION)) { + String arn = client.createInferenceProfile(request -> request.inferenceProfileName(name) + .modelSource(InferenceProfileModelSource.builder().copyFrom(MODEL_ARN).build())) + .inferenceProfileArn(); + try { + assertTrue(client.listTagsForResource(request -> request.resourceARN(arn)).tags().isEmpty()); + } finally { + client.deleteInferenceProfile(request -> request.inferenceProfileIdentifier(arn)); + } + } + } + + @Test + void sdkCreateGetListTagAndDeleteUseTheApplicationProfileWireContract() { + String name = "application-profile-" + UUID.randomUUID(); + String token = UUID.randomUUID().toString(); + try (BedrockClient client = client(ACCOUNT, REGION)) { + CreateInferenceProfileResponse created = client.createInferenceProfile(request -> request + .inferenceProfileName(name).description("tracks cost") + .modelSource(InferenceProfileModelSource.builder().copyFrom(MODEL_ARN).build()) + .clientRequestToken(token).tags(Tag.builder().key("team").value("ml").build())); + String arn = created.inferenceProfileArn(); + String id = arn.substring(arn.lastIndexOf('/') + 1); + try { + assertEquals("arn:aws:bedrock:" + REGION + ":" + ACCOUNT + + ":application-inference-profile/" + id, arn); + assertEquals(InferenceProfileStatus.ACTIVE, created.status()); + + GetInferenceProfileResponse fetched = client.getInferenceProfile(request -> request + .inferenceProfileIdentifier(id)); + assertEquals(arn, fetched.inferenceProfileArn()); + assertEquals(name, fetched.inferenceProfileName()); + assertEquals("tracks cost", fetched.description()); + assertEquals(InferenceProfileType.APPLICATION, fetched.type()); + assertEquals(List.of(MODEL_ARN), fetched.models().stream().map(model -> model.modelArn()).toList()); + assertEquals(id, client.getInferenceProfile(request -> request + .inferenceProfileIdentifier(arn)).inferenceProfileId()); + + List application = client.listInferenceProfiles(request -> request + .typeEquals(InferenceProfileType.APPLICATION)).inferenceProfileSummaries(); + assertTrue(application.stream().anyMatch(profile -> id.equals(profile.inferenceProfileId()) + && arn.equals(profile.inferenceProfileArn()))); + assertTrue(client.listInferenceProfiles(request -> request + .typeEquals(InferenceProfileType.SYSTEM_DEFINED)).inferenceProfileSummaries().stream() + .noneMatch(profile -> id.equals(profile.inferenceProfileId()))); + + CreateInferenceProfileResponse replay = client.createInferenceProfile(request -> request + .inferenceProfileName(name + " changed") + .modelSource(InferenceProfileModelSource.builder().copyFrom("invalid").build()) + .clientRequestToken(token)); + assertEquals(arn, replay.inferenceProfileArn()); + + client.tagResource(request -> request.resourceARN(arn) + .tags(Tag.builder().key("owner").value("platform").build())); + assertEquals(2, client.listTagsForResource(request -> request.resourceARN(arn)).tags().size()); + client.untagResource(request -> request.resourceARN(arn).tagKeys("owner")); + assertEquals(List.of(Tag.builder().key("team").value("ml").build()), + client.listTagsForResource(request -> request.resourceARN(arn)).tags()); + + try (BedrockClient otherAccount = client("741623800009", REGION); + BedrockClient otherRegion = client(ACCOUNT, "us-west-2")) { + assertThrows(AccessDeniedException.class, () -> otherAccount.getInferenceProfile( + request -> request.inferenceProfileIdentifier(arn))); + assertThrows(ResourceNotFoundException.class, () -> otherRegion.getInferenceProfile( + request -> request.inferenceProfileIdentifier(arn))); + } + } finally { + client.deleteInferenceProfile(request -> request.inferenceProfileIdentifier(arn)); + } + assertThrows(ResourceNotFoundException.class, () -> client.getInferenceProfile( + request -> request.inferenceProfileIdentifier(id))); + } + } + + private BedrockClient client(String account, String region) { + return BedrockClient.builder().endpointOverride(URI.create("http://localhost:" + RestAssured.port)) + .httpClientBuilder(UrlConnectionHttpClient.builder()).region(Region.of(region)) + .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create(account, "test"))) + .build(); + } +} diff --git a/src/test/java/io/floci/aws/services/bedrock/BedrockApplicationInferenceProfileServiceTest.java b/src/test/java/io/floci/aws/services/bedrock/BedrockApplicationInferenceProfileServiceTest.java new file mode 100644 index 0000000000..833522d89d --- /dev/null +++ b/src/test/java/io/floci/aws/services/bedrock/BedrockApplicationInferenceProfileServiceTest.java @@ -0,0 +1,129 @@ +package io.floci.aws.services.bedrock; + +import com.fasterxml.jackson.databind.ObjectMapper; +import io.floci.aws.core.common.AwsException; +import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.storage.InMemoryStorage; +import io.floci.aws.services.bedrock.model.ApplicationInferenceProfile; +import io.floci.aws.services.kms.KmsService; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; + +class BedrockApplicationInferenceProfileServiceTest { + + private static final String REGION = "us-east-1"; + private static final String ACCOUNT = "000000000000"; + private static final String MODEL_ARN = + "arn:aws:bedrock:us-east-1::foundation-model/amazon.nova-micro-v1:0"; + private static final String SYSTEM_PROFILE_ARN = + "arn:aws:bedrock:us-east-1:" + ACCOUNT + ":inference-profile/us.amazon.nova-lite-v1:0"; + + private final InMemoryStorage profiles = new InMemoryStorage<>(); + private final BedrockService service = serviceFor(ACCOUNT); + + private BedrockService serviceFor(String account) { + return new BedrockService(new InMemoryStorage<>(), new InMemoryStorage<>(), profiles, + new RegionResolver(REGION, account), new ObjectMapper(), mock(KmsService.class)); + } + + @Test + void applicationProfilePersistsAndIsListedAlongsideSystemProfiles() { + ApplicationInferenceProfile created = service.createApplicationInferenceProfile( + "my profile", "test profile", MODEL_ARN, Map.of("team", "ml"), REGION); + BedrockService restarted = serviceFor(ACCOUNT); + + assertEquals("arn:aws:bedrock:us-east-1:" + ACCOUNT + ":application-inference-profile/" + + created.getInferenceProfileId(), created.getInferenceProfileArn()); + assertEquals(List.of(MODEL_ARN), restarted.getApplicationInferenceProfile( + created.getInferenceProfileArn(), REGION).getModels()); + assertEquals(created.getInferenceProfileId(), restarted.getInferenceProfile( + created.getInferenceProfileId(), REGION).inferenceProfileId()); + assertEquals("APPLICATION", restarted.getInferenceProfile( + created.getInferenceProfileArn(), REGION).type()); + assertEquals(List.of(created.getInferenceProfileId()), restarted.listInferenceProfiles( + "APPLICATION", null, null, REGION).items().stream() + .map(BedrockService.InferenceProfileView::inferenceProfileId).toList()); + assertTrue(restarted.listInferenceProfiles(null, null, null, REGION).items().stream() + .anyMatch(profile -> "SYSTEM_DEFINED".equals(profile.type()))); + assertEquals(Map.of("team", "ml"), restarted.listTags(created.getInferenceProfileArn(), REGION)); + } + + @Test + void systemProfileSourceCopiesEveryDestinationModelAndTagsRoundTrip() { + ApplicationInferenceProfile created = service.createApplicationInferenceProfile( + "cross region", null, SYSTEM_PROFILE_ARN, Map.of(), REGION); + assertEquals(service.getInferenceProfile("us.amazon.nova-lite-v1:0", REGION).models(), + created.getModels()); + + service.tagResource(created.getInferenceProfileArn(), Map.of("owner", "team"), REGION); + assertEquals(Map.of("owner", "team"), service.listTags(created.getInferenceProfileArn(), REGION)); + service.untagResource(created.getInferenceProfileArn(), List.of("owner"), REGION); + assertEquals(Map.of(), service.listTags(created.getInferenceProfileArn(), REGION)); + assertTrue(service.getResources().stream() + .anyMatch(resource -> created.getInferenceProfileArn().equals(resource.arn()))); + } + + @Test + void deleteRemovesTheProfileAndCannotDeleteSystemProfiles() { + ApplicationInferenceProfile created = service.createApplicationInferenceProfile( + "to delete", null, MODEL_ARN, Map.of(), REGION); + service.deleteApplicationInferenceProfile(created.getInferenceProfileArn(), REGION); + assertEquals("ResourceNotFoundException", assertThrows(AwsException.class, + () -> service.getInferenceProfile(created.getInferenceProfileId(), REGION)).getErrorCode()); + assertEquals("ResourceNotFoundException", assertThrows(AwsException.class, + () -> service.deleteApplicationInferenceProfile(SYSTEM_PROFILE_ARN, REGION)).getErrorCode()); + } + + @Test + void profilesAreIsolatedByAccountAndRegion() { + ApplicationInferenceProfile created = service.createApplicationInferenceProfile( + "private", null, MODEL_ARN, Map.of(), REGION); + BedrockService otherAccount = serviceFor("000000000001"); + + assertTrue(otherAccount.listInferenceProfiles("APPLICATION", null, null, REGION).items().isEmpty()); + assertEquals("ResourceNotFoundException", assertThrows(AwsException.class, + () -> otherAccount.getInferenceProfile(created.getInferenceProfileId(), REGION)).getErrorCode()); + assertEquals("AccessDeniedException", assertThrows(AwsException.class, + () -> otherAccount.getInferenceProfile(created.getInferenceProfileArn(), REGION)).getErrorCode()); + assertTrue(service.listInferenceProfiles("APPLICATION", null, null, "us-west-2").items().isEmpty()); + assertEquals("ResourceNotFoundException", assertThrows(AwsException.class, + () -> service.getInferenceProfile(created.getInferenceProfileArn(), "us-west-2")).getErrorCode()); + } + + @Test + void sourceAndDuplicateNameValidationLeaveStorageUnchanged() { + for (String invalidSource : List.of("not-an-arn", + "arn:aws:bedrock:eu-west-1::foundation-model/amazon.nova-micro-v1:0", + "arn:aws:bedrock:us-east-1:" + ACCOUNT + ":application-inference-profile/other")) { + assertEquals("ValidationException", assertThrows(AwsException.class, + () -> service.createApplicationInferenceProfile( + "bad source", null, invalidSource, Map.of(), REGION)).getErrorCode()); + } + assertTrue(service.listInferenceProfiles("APPLICATION", null, null, REGION).items().isEmpty()); + service.createApplicationInferenceProfile("taken", null, MODEL_ARN, Map.of(), REGION); + assertEquals("ConflictException", assertThrows(AwsException.class, + () -> service.createApplicationInferenceProfile("taken", null, MODEL_ARN, Map.of(), REGION)) + .getErrorCode()); + } + + @Test + void idempotencyTokenReturnsTheOriginalProfile() { + ApplicationInferenceProfile created = service.createApplicationInferenceProfile( + "first", null, MODEL_ARN, Map.of(), "same-token", REGION); + ApplicationInferenceProfile replay = service.createApplicationInferenceProfile( + "changed", "changed", "invalid source", Map.of("other", "value"), "same-token", REGION); + + assertEquals(created.getInferenceProfileArn(), replay.getInferenceProfileArn()); + assertEquals("first", replay.getInferenceProfileName()); + assertEquals(1, service.listInferenceProfiles("APPLICATION", null, null, REGION).items().size()); + assertFalse(service.listTags(created.getInferenceProfileArn(), REGION).containsKey("other")); + } +} diff --git a/src/test/java/io/floci/aws/services/bedrock/BedrockGuardrailCreateNameConcurrencyTest.java b/src/test/java/io/floci/aws/services/bedrock/BedrockGuardrailCreateNameConcurrencyTest.java index d639d5794f..f7b7378091 100644 --- a/src/test/java/io/floci/aws/services/bedrock/BedrockGuardrailCreateNameConcurrencyTest.java +++ b/src/test/java/io/floci/aws/services/bedrock/BedrockGuardrailCreateNameConcurrencyTest.java @@ -33,7 +33,7 @@ class BedrockGuardrailCreateNameConcurrencyTest { private static void overlappingCreates(boolean sameName) throws Exception { ParkingStore storage = new ParkingStore<>(); ObjectMapper mapper = new ObjectMapper(); - BedrockService service = new BedrockService(storage, new InMemoryStorage<>(), + BedrockService service = new BedrockService(storage, new InMemoryStorage<>(), new InMemoryStorage<>(), new RegionResolver("us-east-1", "000000000000"), mapper, mock(KmsService.class)); AtomicReference firstResult = new AtomicReference<>(); AtomicReference secondResult = new AtomicReference<>(); diff --git a/src/test/java/io/floci/aws/services/bedrock/BedrockGuardrailLifecycleConcurrencyTest.java b/src/test/java/io/floci/aws/services/bedrock/BedrockGuardrailLifecycleConcurrencyTest.java index 26305e2b15..c47ecad6ba 100644 --- a/src/test/java/io/floci/aws/services/bedrock/BedrockGuardrailLifecycleConcurrencyTest.java +++ b/src/test/java/io/floci/aws/services/bedrock/BedrockGuardrailLifecycleConcurrencyTest.java @@ -43,7 +43,7 @@ class BedrockGuardrailLifecycleConcurrencyTest { private static void overlappingWrite(Write operation) throws Exception { ParkingStore storage = new ParkingStore<>(); ObjectMapper mapper = new ObjectMapper(); - BedrockService service = new BedrockService(storage, new InMemoryStorage<>(), + BedrockService service = new BedrockService(storage, new InMemoryStorage<>(), new InMemoryStorage<>(), new RegionResolver(REGION, "000000000000"), mapper, mock(KmsService.class)); ObjectNode request = mapper.createObjectNode().put("name", "lifecycle") .put("blockedInputMessaging", "blocked").put("blockedOutputsMessaging", "blocked"); diff --git a/src/test/java/io/floci/aws/services/bedrock/BedrockServiceTest.java b/src/test/java/io/floci/aws/services/bedrock/BedrockServiceTest.java index f424bd2df6..0c8a401119 100644 --- a/src/test/java/io/floci/aws/services/bedrock/BedrockServiceTest.java +++ b/src/test/java/io/floci/aws/services/bedrock/BedrockServiceTest.java @@ -40,7 +40,7 @@ class BedrockServiceTest { @BeforeEach void setUp() { kmsService = mock(KmsService.class); - service = new BedrockService(new InMemoryStorage<>(), new InMemoryStorage<>(), + service = new BedrockService(new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new RegionResolver(REGION, ACCOUNT), mapper, kmsService); } diff --git a/src/test/java/io/floci/aws/services/cloudformation/CfnProvisionerFixture.java b/src/test/java/io/floci/aws/services/cloudformation/CfnProvisionerFixture.java index e88b556b5c..ab4f3b6814 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/CfnProvisionerFixture.java +++ b/src/test/java/io/floci/aws/services/cloudformation/CfnProvisionerFixture.java @@ -13,6 +13,7 @@ import io.floci.aws.services.appsync.AppSyncService; import io.floci.aws.services.autoscaling.AutoScalingService; import io.floci.aws.services.backup.BackupService; import io.floci.aws.services.batch.BatchService; +import io.floci.aws.services.bedrock.BedrockService; import io.floci.aws.services.bedrockagentcorecontrol.BedrockAgentCoreControlService; import io.floci.aws.services.bedrockagentcorecontrol.BedrockAgentCoreMemoryService; import io.floci.aws.services.cloudformation.provisioners.AcmCfnProvisioner; @@ -33,6 +34,7 @@ import io.floci.aws.services.cloudformation.provisioners.AutoScalingScalingPolic import io.floci.aws.services.cloudformation.provisioners.BackupVaultCfnProvisioner; import io.floci.aws.services.cloudformation.provisioners.BatchCfnProvisioner; import io.floci.aws.services.cloudformation.provisioners.BedrockAgentCoreCfnProvisioner; +import io.floci.aws.services.cloudformation.provisioners.BedrockCfnProvisioner; import io.floci.aws.services.cloudformation.provisioners.CdkMetadataCfnProvisioner; import io.floci.aws.services.cloudformation.provisioners.CfnDynamicReferences; import io.floci.aws.services.cloudformation.provisioners.CfnResourceDispatcher; @@ -297,6 +299,7 @@ final class CfnProvisionerFixture { private CloudMapService cloudMapService; private EventBridgeV2Service eventBridgeV2Service; private GuardDutyService guardDutyService; + private BedrockService bedrockService; private BedrockAgentCoreControlService bedrockAgentCoreControlService; private BedrockAgentCoreMemoryService bedrockAgentCoreMemoryService; private CloudFormationResourceRegistry resourceRegistry; @@ -579,6 +582,9 @@ final class CfnProvisionerFixture { if (guardDutyService != null) { discovered.add(new GuardDutyMalwareProtectionPlanCfnProvisioner(guardDutyService)); } + if (bedrockService != null) { + discovered.add(new BedrockCfnProvisioner(bedrockService)); + } if (bedrockAgentCoreControlService != null && bedrockAgentCoreMemoryService != null) { discovered.add(new BedrockAgentCoreCfnProvisioner(bedrockAgentCoreControlService, bedrockAgentCoreMemoryService)); @@ -941,6 +947,11 @@ final class CfnProvisionerFixture { return this; } + public Builder bedrock(BedrockService v) { + this.bedrockService = v; + return this; + } + public Builder bedrockAgentCoreControl(BedrockAgentCoreControlService v) { this.bedrockAgentCoreControlService = v; return this; diff --git a/src/test/java/io/floci/aws/services/cloudformation/CloudFormationBedrockApplicationInferenceProfileIntegrationTest.java b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationBedrockApplicationInferenceProfileIntegrationTest.java new file mode 100644 index 0000000000..81974b8245 --- /dev/null +++ b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationBedrockApplicationInferenceProfileIntegrationTest.java @@ -0,0 +1,335 @@ +package io.floci.aws.services.cloudformation; + +import com.fasterxml.jackson.databind.JsonNode; +import io.floci.aws.services.cloudformation.model.StackResource; +import io.floci.aws.services.cloudformation.provisioners.CfnResourceDispatcher; +import io.floci.aws.testing.AwsTestClients; +import io.floci.aws.testing.CfnStackWaits; +import io.quarkus.test.junit.QuarkusTest; +import jakarta.inject.Inject; +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.bedrock.BedrockClient; +import software.amazon.awssdk.services.bedrock.model.GetInferenceProfileResponse; +import software.amazon.awssdk.services.bedrock.model.InferenceProfileSummary; +import software.amazon.awssdk.services.bedrock.model.InferenceProfileType; +import software.amazon.awssdk.services.bedrock.model.ResourceNotFoundException; +import software.amazon.awssdk.services.bedrock.model.Tag; +import software.amazon.awssdk.services.cloudformation.CloudFormationClient; +import software.amazon.awssdk.services.cloudformation.model.Stack; + +import java.time.Instant; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@QuarkusTest +class CloudFormationBedrockApplicationInferenceProfileIntegrationTest { + + @Inject + CloudFormationService cloudFormationService; + + @Inject + CfnResourceDispatcher dispatcher; + + private static final String ACCOUNT = "000000000000"; + private static final Region REGION = Region.US_EAST_1; + private static final String STACK = "cfn-bedrock-application-profile-it"; + private static final String PROFILE_NAME = "cfn-bedrock-application-profile"; + private static final String SOURCE_ARN = + "arn:aws:bedrock:us-east-1::foundation-model/amazon.nova-micro-v1:0"; + private static final String OTHER_SOURCE_ARN = + "arn:aws:bedrock:us-east-1::foundation-model/amazon.nova-lite-v1:0"; + + private static String template(String profileName, String tagValue) { + return template(profileName, tagValue, SOURCE_ARN); + } + + private static String template(String profileName, String tagValue, String sourceArn) { + return """ + { + "Resources": { + "Profile": { + "Type": "AWS::Bedrock::ApplicationInferenceProfile", + "Properties": { + "InferenceProfileName": "%s", + "ModelSource": {"CopyFrom": "%s"}, + "Tags": [{"Key": "team", "Value": "%s"}] + } + } + }, + "Outputs": { + "ProfileRef": {"Value": {"Ref": "Profile"}}, + "ProfileId": {"Value": {"Fn::GetAtt": ["Profile", "InferenceProfileId"]}}, + "ProfileArn": {"Value": {"Fn::GetAtt": ["Profile", "InferenceProfileArn"]}}, + "ProfileIdentifier": {"Value": {"Fn::GetAtt": ["Profile", "InferenceProfileIdentifier"]}}, + "ProfileType": {"Value": {"Fn::GetAtt": ["Profile", "Type"]}}, + "ProfileStatus": {"Value": {"Fn::GetAtt": ["Profile", "Status"]}}, + "ProfileCreatedAt": {"Value": {"Fn::GetAtt": ["Profile", "CreatedAt"]}}, + "ProfileUpdatedAt": {"Value": {"Fn::GetAtt": ["Profile", "UpdatedAt"]}} + } + } + """.formatted(profileName, sourceArn, tagValue); + } + + @Test + void stackCreatesAnApplicationProfileAndExposesItsIdAndArn() { + try (CloudFormationClient cfn = AwsTestClients.create(CloudFormationClient.builder(), ACCOUNT, REGION); + BedrockClient bedrock = AwsTestClients.create(BedrockClient.builder(), ACCOUNT, REGION)) { + Stack stack = CfnStackWaits.createStack(cfn, STACK, template(PROFILE_NAME, "infra"), "CREATE_COMPLETE"); + try { + List profiles = bedrock.listInferenceProfiles(request -> request + .typeEquals(InferenceProfileType.APPLICATION)) + .inferenceProfileSummaries().stream() + .filter(profile -> PROFILE_NAME.equals(profile.inferenceProfileName())) + .toList(); + assertEquals(1, profiles.size(), "CloudFormation must create a backing Bedrock application profile"); + + InferenceProfileSummary profile = profiles.getFirst(); + String id = profile.inferenceProfileId(); + String arn = "arn:aws:bedrock:us-east-1:" + ACCOUNT + ":application-inference-profile/" + id; + assertEquals(arn, profile.inferenceProfileArn()); + assertEquals(id, CfnStackWaits.output(stack, "ProfileRef")); + assertEquals(id, CfnStackWaits.output(stack, "ProfileId")); + assertEquals(arn, CfnStackWaits.output(stack, "ProfileArn")); + assertEquals(id, CfnStackWaits.output(stack, "ProfileIdentifier")); + assertEquals("APPLICATION", CfnStackWaits.output(stack, "ProfileType")); + assertEquals("ACTIVE", CfnStackWaits.output(stack, "ProfileStatus")); + + GetInferenceProfileResponse fetched = bedrock.getInferenceProfile(request -> request + .inferenceProfileIdentifier(id)); + assertEquals(PROFILE_NAME, fetched.inferenceProfileName()); + assertEquals(id, fetched.inferenceProfileId()); + assertEquals(arn, fetched.inferenceProfileArn()); + assertEquals(InferenceProfileType.APPLICATION, fetched.type()); + assertEquals(fetched.createdAt(), Instant.parse(CfnStackWaits.output(stack, "ProfileCreatedAt"))); + assertEquals(fetched.updatedAt(), Instant.parse(CfnStackWaits.output(stack, "ProfileUpdatedAt"))); + assertEquals(List.of(SOURCE_ARN), fetched.models().stream().map(model -> model.modelArn()).toList()); + StackResource resource = cloudFormationService.describeStackResources(STACK, REGION.id()).stream() + .filter(item -> "Profile".equals(item.getLogicalId())) + .findFirst().orElseThrow(); + JsonNode models = dispatcher.attributeValue(resource.getResourceType(), "Models", + resource.getAttributes().get("Models")); + assertTrue(models.isArray(), "Models GetAtt must be an array, not a JSON string"); + assertEquals(SOURCE_ARN, models.get(0).path("ModelArn").asText()); + assertEquals(List.of(Tag.builder().key("team").value("infra").build()), + bedrock.listTagsForResource(request -> request.resourceARN(arn)).tags()); + + Stack tagUpdate = CfnStackWaits.updateStack(cfn, STACK, + template(PROFILE_NAME, "platform"), "UPDATE_COMPLETE"); + assertEquals(id, CfnStackWaits.output(tagUpdate, "ProfileRef")); + assertEquals(List.of(Tag.builder().key("team").value("platform").build()), + bedrock.listTagsForResource(request -> request.resourceARN(arn)).tags()); + + String replacementName = PROFILE_NAME + "-replacement"; + Stack replacement = CfnStackWaits.updateStack(cfn, STACK, + template(replacementName, "platform"), "UPDATE_COMPLETE"); + String replacementId = CfnStackWaits.output(replacement, "ProfileRef"); + assertNotEquals(id, replacementId); + assertEquals(replacementName, bedrock.getInferenceProfile(request -> request + .inferenceProfileIdentifier(replacementId)).inferenceProfileName()); + assertThrows(ResourceNotFoundException.class, + () -> bedrock.getInferenceProfile(request -> request.inferenceProfileIdentifier(id))); + } finally { + CfnStackWaits.deleteStack(cfn, STACK); + List remaining = bedrock.listInferenceProfiles(request -> request + .typeEquals(InferenceProfileType.APPLICATION)) + .inferenceProfileSummaries().stream() + .filter(profile -> profile.inferenceProfileName().startsWith(PROFILE_NAME)) + .toList(); + assertTrue(remaining.isEmpty(), "CloudFormation must delete its backing Bedrock profile"); + } + } + } + + @Test + void missingModelSourceFailsWithoutCreatingAnApplicationProfile() { + String name = PROFILE_NAME + "-no-source"; + String stackName = STACK + "-no-source"; + String template = """ + {"Resources":{"Profile":{"Type":"AWS::Bedrock::ApplicationInferenceProfile", + "Properties":{"InferenceProfileName":"%s"}}}} + """.formatted(name); + try (CloudFormationClient cfn = AwsTestClients.create(CloudFormationClient.builder(), ACCOUNT, REGION); + BedrockClient bedrock = AwsTestClients.create(BedrockClient.builder(), ACCOUNT, REGION)) { + try { + CfnStackWaits.createStack(cfn, stackName, template, "ROLLBACK_COMPLETE"); + assertTrue(bedrock.listInferenceProfiles(request -> request + .typeEquals(InferenceProfileType.APPLICATION)) + .inferenceProfileSummaries().stream() + .noneMatch(profile -> name.equals(profile.inferenceProfileName()))); + } finally { + CfnStackWaits.deleteStack(cfn, stackName); + } + } + } + + @Test + void wholePropertyConditionsResolveModelSourceAndTagsBeforeProvisioning() { + String stackName = STACK + "-conditional"; + String name = PROFILE_NAME + "-conditional"; + String template = """ + {"Conditions":{"UsePrimary":{"Fn::Equals":["primary","primary"]}}, + "Resources":{"Profile":{"Type":"AWS::Bedrock::ApplicationInferenceProfile", + "Properties":{"InferenceProfileName":"%s", + "ModelSource":{"Fn::If":["UsePrimary",{"CopyFrom":"%s"},{"CopyFrom":"%s"}]}, + "Tags":{"Fn::If":["UsePrimary",[{"Key":"team","Value":"chosen"}], + [{"Key":"team","Value":"unused"}]]}}}}, + "Outputs":{"ProfileRef":{"Value":{"Ref":"Profile"}}}} + """.formatted(name, SOURCE_ARN, OTHER_SOURCE_ARN); + try (CloudFormationClient cfn = AwsTestClients.create(CloudFormationClient.builder(), ACCOUNT, REGION); + BedrockClient bedrock = AwsTestClients.create(BedrockClient.builder(), ACCOUNT, REGION)) { + Stack created = CfnStackWaits.createStack(cfn, stackName, template, "CREATE_COMPLETE"); + try { + String id = CfnStackWaits.output(created, "ProfileRef"); + GetInferenceProfileResponse profile = bedrock.getInferenceProfile(request -> request + .inferenceProfileIdentifier(id)); + assertEquals(List.of(SOURCE_ARN), profile.models().stream() + .map(model -> model.modelArn()).toList()); + assertEquals(List.of(Tag.builder().key("team").value("chosen").build()), + bedrock.listTagsForResource(request -> request.resourceARN(profile.inferenceProfileArn())) + .tags()); + } finally { + CfnStackWaits.deleteStack(cfn, stackName); + } + } + } + + @Test + void tagsConditionSelectingNoValueCreatesAnUntaggedProfile() { + String stackName = STACK + "-no-tags"; + String name = PROFILE_NAME + "-no-tags"; + String template = """ + {"Conditions":{"UseTags":{"Fn::Equals":["enabled","disabled"]}}, + "Resources":{"Profile":{"Type":"AWS::Bedrock::ApplicationInferenceProfile", + "Properties":{"InferenceProfileName":"%s", + "ModelSource":{"CopyFrom":"%s"}, + "Tags":{"Fn::If":["UseTags",[{"Key":"team","Value":"ignored"}], + {"Ref":"AWS::NoValue"}]}}}}, + "Outputs":{"ProfileRef":{"Value":{"Ref":"Profile"}}}} + """.formatted(name, SOURCE_ARN); + try (CloudFormationClient cfn = AwsTestClients.create(CloudFormationClient.builder(), ACCOUNT, REGION); + BedrockClient bedrock = AwsTestClients.create(BedrockClient.builder(), ACCOUNT, REGION)) { + try { + Stack created = CfnStackWaits.createStack(cfn, stackName, template, "CREATE_COMPLETE"); + String id = CfnStackWaits.output(created, "ProfileRef"); + GetInferenceProfileResponse profile = bedrock.getInferenceProfile(request -> request + .inferenceProfileIdentifier(id)); + assertEquals(List.of(), bedrock.listTagsForResource(request -> request + .resourceARN(profile.inferenceProfileArn())).tags()); + } finally { + CfnStackWaits.deleteStack(cfn, stackName); + } + } + } + + @Test + void externallyDeletedPriorProfileBlocksReplacementCreation() { + String stackName = STACK + "-deleted-prior"; + String name = PROFILE_NAME + "-deleted-prior"; + String replacementName = name + "-replacement"; + try (CloudFormationClient cfn = AwsTestClients.create(CloudFormationClient.builder(), ACCOUNT, REGION); + BedrockClient bedrock = AwsTestClients.create(BedrockClient.builder(), ACCOUNT, REGION)) { + Stack created = CfnStackWaits.createStack(cfn, stackName, template(name, "original"), "CREATE_COMPLETE"); + try { + String id = CfnStackWaits.output(created, "ProfileRef"); + bedrock.deleteInferenceProfile(request -> request.inferenceProfileIdentifier(id)); + + CfnStackWaits.updateStack(cfn, stackName, + template(replacementName, "changed"), "UPDATE_ROLLBACK_COMPLETE"); + + assertTrue(bedrock.listInferenceProfiles(request -> request + .typeEquals(InferenceProfileType.APPLICATION)).inferenceProfileSummaries().stream() + .noneMatch(profile -> replacementName.equals(profile.inferenceProfileName()))); + } finally { + CfnStackWaits.deleteStack(cfn, stackName); + } + } + } + + @Test + void failedUpdateRestoresApplicationProfileTags() { + String stackName = STACK + "-tag-rollback"; + String name = PROFILE_NAME + "-tag-rollback"; + String failedTemplate = """ + {"Resources":{ + "Profile":{"Type":"AWS::Bedrock::ApplicationInferenceProfile", + "Properties":{"InferenceProfileName":"%s", + "ModelSource":{"CopyFrom":"%s"}, + "Tags":[{"Key":"team","Value":"changed"}]}}, + "Later":{"Type":"AWS::EC2::Instance","DependsOn":"Profile", + "Properties":{"LaunchTemplate":{ + "LaunchTemplateId":"lt-0123456789abcdef0","Version":"1"}}} + }} + """.formatted(name, SOURCE_ARN); + try (CloudFormationClient cfn = AwsTestClients.create(CloudFormationClient.builder(), ACCOUNT, REGION); + BedrockClient bedrock = AwsTestClients.create(BedrockClient.builder(), ACCOUNT, REGION)) { + Stack created = CfnStackWaits.createStack(cfn, stackName, template(name, "original"), "CREATE_COMPLETE"); + try { + String id = CfnStackWaits.output(created, "ProfileRef"); + CfnStackWaits.updateStack(cfn, stackName, failedTemplate, "UPDATE_ROLLBACK_COMPLETE"); + assertEquals(id, CfnStackWaits.output(cfn.describeStacks(request -> request.stackName(stackName)) + .stacks().getFirst(), "ProfileRef")); + String arn = bedrock.getInferenceProfile(request -> request.inferenceProfileIdentifier(id)) + .inferenceProfileArn(); + assertEquals(List.of(Tag.builder().key("team").value("original").build()), + bedrock.listTagsForResource(request -> request.resourceARN(arn)).tags()); + } finally { + CfnStackWaits.deleteStack(cfn, stackName); + } + } + } + + @Test + void updatePreservesTagsAddedOutsideTheTemplate() { + String stackName = STACK + "-external-tag"; + String name = PROFILE_NAME + "-external-tag"; + try (CloudFormationClient cfn = AwsTestClients.create(CloudFormationClient.builder(), ACCOUNT, REGION); + BedrockClient bedrock = AwsTestClients.create(BedrockClient.builder(), ACCOUNT, REGION)) { + Stack created = CfnStackWaits.createStack(cfn, stackName, template(name, "original"), "CREATE_COMPLETE"); + try { + String id = CfnStackWaits.output(created, "ProfileRef"); + String arn = bedrock.getInferenceProfile(request -> request.inferenceProfileIdentifier(id)) + .inferenceProfileArn(); + Tag external = Tag.builder().key("external").value("keep").build(); + bedrock.tagResource(request -> request.resourceARN(arn).tags(external)); + + CfnStackWaits.updateStack(cfn, stackName, template(name, "updated"), "UPDATE_COMPLETE"); + + List tags = bedrock.listTagsForResource(request -> request.resourceARN(arn)).tags(); + assertEquals(2, tags.size()); + assertTrue(tags.contains(Tag.builder().key("team").value("updated").build())); + assertTrue(tags.contains(external)); + } finally { + CfnStackWaits.deleteStack(cfn, stackName); + } + } + } + + @Test + void sourceReplacementWithTheSameNameKeepsThePriorProfile() { + String stackName = STACK + "-source-rollback"; + String name = PROFILE_NAME + "-source-rollback"; + try (CloudFormationClient cfn = AwsTestClients.create(CloudFormationClient.builder(), ACCOUNT, REGION); + BedrockClient bedrock = AwsTestClients.create(BedrockClient.builder(), ACCOUNT, REGION)) { + Stack created = CfnStackWaits.createStack(cfn, stackName, template(name, "original"), "CREATE_COMPLETE"); + try { + String id = CfnStackWaits.output(created, "ProfileRef"); + CfnStackWaits.updateStack(cfn, stackName, + template(name, "original", OTHER_SOURCE_ARN), "UPDATE_ROLLBACK_COMPLETE"); + Stack rolledBack = cfn.describeStacks(request -> request.stackName(stackName)).stacks().getFirst(); + assertEquals(id, CfnStackWaits.output(rolledBack, "ProfileRef")); + assertEquals(List.of(SOURCE_ARN), bedrock.getInferenceProfile(request -> request + .inferenceProfileIdentifier(id)).models().stream().map(model -> model.modelArn()).toList()); + assertEquals(1, bedrock.listInferenceProfiles(request -> request.typeEquals( + InferenceProfileType.APPLICATION)).inferenceProfileSummaries().stream() + .filter(profile -> name.equals(profile.inferenceProfileName())).count()); + } finally { + CfnStackWaits.deleteStack(cfn, stackName); + } + } + } +} diff --git a/src/test/java/io/floci/aws/services/cloudformation/provisioners/BedrockCfnProvisionerTest.java b/src/test/java/io/floci/aws/services/cloudformation/provisioners/BedrockCfnProvisionerTest.java new file mode 100644 index 0000000000..85d110f432 --- /dev/null +++ b/src/test/java/io/floci/aws/services/cloudformation/provisioners/BedrockCfnProvisionerTest.java @@ -0,0 +1,309 @@ +package io.floci.aws.services.cloudformation.provisioners; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.floci.aws.core.common.AwsException; +import io.floci.aws.services.bedrock.BedrockService; +import io.floci.aws.services.bedrock.model.ApplicationInferenceProfile; +import io.floci.aws.services.cloudformation.model.StackResource; +import org.junit.jupiter.api.Test; + +import java.time.Instant; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +class BedrockCfnProvisionerTest { + + private static final String TYPE = "AWS::Bedrock::ApplicationInferenceProfile"; + private static final String REGION = "us-east-1"; + private static final String ID = "a1b2c3d4e5f6"; + private static final String ARN = + "arn:aws:bedrock:us-east-1:000000000000:application-inference-profile/" + ID; + private static final String SOURCE = + "arn:aws:bedrock:us-east-1::foundation-model/amazon.nova-micro-v1:0"; + + private final BedrockService bedrock = mock(BedrockService.class); + private final BedrockCfnProvisioner provisioner = new BedrockCfnProvisioner(bedrock); + private final ObjectMapper mapper = new ObjectMapper(); + + private StackResource resource() { + StackResource resource = new StackResource(); + resource.setLogicalId("Profile"); + resource.setResourceType(TYPE); + resource.setAttributes(new HashMap<>()); + return resource; + } + + private ProvisionContext context() { + return new ProvisionContext(ProvisionContexts.passthroughEngine(), REGION, "000000000000", "stack"); + } + + private static ApplicationInferenceProfile profile() { + ApplicationInferenceProfile profile = new ApplicationInferenceProfile(); + profile.setInferenceProfileId(ID); + profile.setInferenceProfileArn(ARN); + profile.setModels(List.of(SOURCE)); + profile.setCreatedAt(Instant.parse("2026-01-01T00:00:00Z")); + profile.setUpdatedAt(Instant.parse("2026-01-01T00:00:00Z")); + return profile; + } + + @Test + void createUsesTheBedrockServiceAndPublishesExactCloudFormationAttributes() throws Exception { + ObjectNode properties = mapper.createObjectNode() + .put("InferenceProfileName", "example") + .put("Description", "example profile"); + properties.putObject("ModelSource").put("CopyFrom", SOURCE); + properties.putArray("Tags").addObject().put("Key", "team").put("Value", "ml"); + when(bedrock.createApplicationInferenceProfile("example", "example profile", SOURCE, + Map.of("team", "ml"), REGION)).thenReturn(profile()); + StackResource resource = resource(); + + provisioner.provision(resource, properties, context()); + + verify(bedrock).createApplicationInferenceProfile("example", "example profile", SOURCE, + Map.of("team", "ml"), REGION); + assertEquals(Set.of(TYPE), provisioner.resourceTypes()); + assertEquals(Map.of(TYPE, Set.of("Models")), provisioner.jsonAttributes()); + assertEquals(ID, resource.getPhysicalId()); + assertEquals(Set.of("InferenceProfileId", "InferenceProfileArn", "InferenceProfileIdentifier", + "Status", "Type", "CreatedAt", "UpdatedAt", "Models", + "__FlociBedrockProfileManagedTagKeys"), resource.getAttributes().keySet()); + assertEquals(ID, resource.getAttributes().get("InferenceProfileId")); + assertEquals(ARN, resource.getAttributes().get("InferenceProfileArn")); + assertEquals("[\"team\"]", resource.getAttributes().get("__FlociBedrockProfileManagedTagKeys")); + assertEquals(ID, resource.getAttributes().get("InferenceProfileIdentifier")); + assertEquals("ACTIVE", resource.getAttributes().get("Status")); + assertEquals("APPLICATION", resource.getAttributes().get("Type")); + assertEquals(SOURCE, mapper.readTree(resource.getAttributes().get("Models")) + .get(0).path("ModelArn").asText()); + } + + @Test + void missingSourceDoesNotCallBedrock() { + ObjectNode properties = mapper.createObjectNode().put("InferenceProfileName", "example"); + + AwsException error = assertThrows(AwsException.class, + () -> provisioner.provision(resource(), properties, context())); + + assertEquals("ValidationError", error.getErrorCode()); + verifyNoInteractions(bedrock); + } + + @Test + void replacementRejectsAnExternallyDeletedPriorProfileBeforeCreatingAnother() throws Exception { + ObjectNode properties = mapper.createObjectNode().put("InferenceProfileName", "replacement"); + properties.putObject("ModelSource").put("CopyFrom", SOURCE); + StackResource resource = resource(); + resource.setPhysicalId(ID); + resource.getAttributes().put("InferenceProfileId", ID); + resource.getAttributes().put("InferenceProfileArn", ARN); + when(bedrock.getApplicationInferenceProfile(ID, REGION)) + .thenThrow(new AwsException("ResourceNotFoundException", "missing", 404)); + + AwsException error = assertThrows(AwsException.class, () -> provisioner.provision(resource, properties, + ProvisionContexts.update(REGION, "000000000000", "stack", ID, + "{\"InferenceProfileName\":\"example\"}"))); + + assertEquals("ResourceNotFoundException", error.getErrorCode()); + assertEquals(ID, resource.getPhysicalId()); + verify(bedrock).getApplicationInferenceProfile(ID, REGION); + verifyNoMoreInteractions(bedrock); + } + + @Test + void updateOfARealDispatcherStubCreatesTheFirstProfile() throws Exception { + ObjectNode properties = mapper.createObjectNode().put("InferenceProfileName", "example"); + properties.putObject("ModelSource").put("CopyFrom", SOURCE); + StackResource resource = resource(); + String stubId = "Profile-01234567"; + resource.setPhysicalId(stubId); + resource.getAttributes().put("Arn", "arn:aws:stub:::Profile"); + when(bedrock.createApplicationInferenceProfile("example", null, SOURCE, Map.of(), REGION)) + .thenReturn(profile()); + + provisioner.provision(resource, properties, ProvisionContexts.update(REGION, "000000000000", + "stack", stubId, "{\"InferenceProfileName\":\"example\"}")); + + assertEquals(ID, resource.getPhysicalId()); + verify(bedrock).createApplicationInferenceProfile("example", null, SOURCE, Map.of(), REGION); + verifyNoMoreInteractions(bedrock); + } + + @Test + void malformedSuppliedTagsFailBeforeProfileLookupOrTagReconciliation() throws Exception { + ObjectNode properties = mapper.createObjectNode().put("InferenceProfileName", "example"); + properties.putObject("ModelSource").put("CopyFrom", SOURCE); + String tooLongKey = "k".repeat(129); + String tooLongValue = "v".repeat(257); + String tooManyTags = "[" + String.join(",", Collections.nCopies(201, + "{\"Key\":\"team\",\"Value\":\"ml\"}")) + "]"; + for (String tagsJson : List.of("{}", "[{\"Value\":\"ml\"}]", "[{\"Key\":\"team\"}]", + "[{\"Key\":42,\"Value\":\"ml\"}]", "[{\"Key\":\"team\",\"Value\":null}]", + "[{\"Key\":\"\",\"Value\":\"ml\"}]", "[{\"Key\":\"bad?key\",\"Value\":\"ml\"}]", + "[{\"Key\":\"team\",\"Value\":\"bad?value\"}]", + "[{\"Key\":\"" + tooLongKey + "\",\"Value\":\"ml\"}]", + "[{\"Key\":\"team\",\"Value\":\"" + tooLongValue + "\"}]", tooManyTags)) { + properties.set("Tags", mapper.readTree(tagsJson)); + StackResource resource = resource(); + resource.setPhysicalId(ID); + + AwsException error = assertThrows(AwsException.class, () -> provisioner.provision(resource, + properties, ProvisionContexts.update(REGION, "000000000000", "stack", ID, + "{\"InferenceProfileName\":\"example\"}")), tagsJson); + + assertEquals("ValidationError", error.getErrorCode(), tagsJson); + } + verifyNoInteractions(bedrock); + } + + @Test + void validBoundaryTagsAreAllowedByTheBedrockTagPattern() { + ObjectNode properties = mapper.createObjectNode().put("InferenceProfileName", "example"); + properties.putObject("ModelSource").put("CopyFrom", SOURCE); + String maxKey = "k".repeat(128); + String maxValue = "v".repeat(256); + properties.putArray("Tags").addObject().put("Key", " ").put("Value", ""); + properties.withArray("Tags").addObject().put("Key", maxKey).put("Value", maxValue); + Map expectedTags = Map.of(" ", "", maxKey, maxValue); + when(bedrock.createApplicationInferenceProfile("example", null, SOURCE, expectedTags, REGION)) + .thenReturn(profile()); + + provisioner.provision(resource(), properties, context()); + + verify(bedrock).createApplicationInferenceProfile("example", null, SOURCE, expectedTags, REGION); + } + + @Test + void omittedTagsRemainValid() { + ObjectNode properties = mapper.createObjectNode().put("InferenceProfileName", "example"); + properties.putObject("ModelSource").put("CopyFrom", SOURCE); + when(bedrock.createApplicationInferenceProfile("example", null, SOURCE, Map.of(), REGION)) + .thenReturn(profile()); + + provisioner.provision(resource(), properties, context()); + + verify(bedrock).createApplicationInferenceProfile("example", null, SOURCE, Map.of(), REGION); + } + + @Test + void updateRemovesOnlyPreviouslyTemplateManagedTags() throws Exception { + ObjectNode properties = mapper.createObjectNode().put("InferenceProfileName", "example"); + properties.putObject("ModelSource").put("CopyFrom", SOURCE); + StackResource resource = resource(); + resource.setPhysicalId(ID); + resource.getAttributes().put("InferenceProfileId", ID); + resource.getAttributes().put("InferenceProfileArn", ARN); + resource.getAttributes().put("__FlociBedrockProfileManagedTagKeys", "[\"team\"]"); + ApplicationInferenceProfile existing = profile(); + existing.setTags(Map.of("team", "stack", "external", "keep")); + when(bedrock.getApplicationInferenceProfile(ID, REGION)).thenReturn(existing); + + provisioner.provision(resource, properties, ProvisionContexts.update(REGION, "000000000000", "stack", ID, + "{\"InferenceProfileName\":\"example\",\"ModelSource\":{\"CopyFrom\":\"" + SOURCE + + "\"},\"Tags\":[{\"Key\":\"team\",\"Value\":\"stack\"}]}")); + + verify(bedrock).untagResource(ARN, List.of("team"), REGION); + assertFalse(resource.getAttributes().containsKey("__FlociBedrockProfileManagedTagKeys")); + } + + @Test + void failedProfileLookupAfterTagMutationRestoresPriorTags() throws Exception { + ObjectNode properties = mapper.createObjectNode().put("InferenceProfileName", "example"); + properties.putObject("ModelSource").put("CopyFrom", SOURCE); + properties.putArray("Tags").addObject().put("Key", "team").put("Value", "new"); + StackResource resource = resource(); + resource.setPhysicalId(ID); + resource.getAttributes().put("InferenceProfileId", ID); + resource.getAttributes().put("InferenceProfileArn", ARN); + resource.getAttributes().put("__FlociBedrockProfileManagedTagKeys", "[\"team\"]"); + + ApplicationInferenceProfile existing = profile(); + existing.setTags(Map.of("team", "old")); + when(bedrock.getApplicationInferenceProfile(ID, REGION)).thenReturn(existing) + .thenThrow(new AwsException("InternalFailure", "publish lookup failed", 500)) + .thenReturn(existing); + + AwsException updateFailure = assertThrows(AwsException.class, () -> provisioner.provision(resource, + properties, ProvisionContexts.update(REGION, "000000000000", "stack", ID, + "{\"InferenceProfileName\":\"example\",\"ModelSource\":{\"CopyFrom\":\"" + SOURCE + + "\"},\"Tags\":[{\"Key\":\"team\",\"Value\":\"old\"}]}"))); + + assertEquals("InternalFailure", updateFailure.getErrorCode()); + assertFalse(resource.getAttributes().containsKey("__FlociBedrockProfilePriorTags")); + assertFalse(resource.getAttributes().containsKey(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR)); + verify(bedrock).tagResource(ARN, Map.of("team", "new"), REGION); + verify(bedrock).tagResource(ARN, Map.of("team", "old"), REGION); + } + + @Test + void failedTagUpdateCarriesSnapshotIntoContinueUpdateRollback() throws Exception { + ObjectNode properties = mapper.createObjectNode().put("InferenceProfileName", "example"); + properties.putObject("ModelSource").put("CopyFrom", SOURCE); + properties.putArray("Tags").addObject().put("Key", "new").put("Value", "value"); + + StackResource previous = resource(); + previous.setPhysicalId(ID); + previous.getAttributes().put("InferenceProfileId", ID); + previous.getAttributes().put("InferenceProfileArn", ARN); + previous.getAttributes().put("__FlociBedrockProfileManagedTagKeys", "[\"team\"]"); + StackResource attempted = resource(); + attempted.setPhysicalId(ID); + attempted.getAttributes().putAll(previous.getAttributes()); + + ApplicationInferenceProfile existing = profile(); + existing.setTags(Map.of("team", "stack", "external", "keep")); + when(bedrock.getApplicationInferenceProfile(ID, REGION)).thenReturn(existing); + doThrow(new AwsException("InternalFailure", "update untag failed", 500)) + .when(bedrock).untagResource(ARN, List.of("team"), REGION); + doThrow(new AwsException("InternalFailure", "compensation tag failed", 500)) + .doNothing().when(bedrock).tagResource(ARN, Map.of("team", "stack"), REGION); + + AwsException updateFailure = assertThrows(AwsException.class, () -> provisioner.provision(attempted, + properties, ProvisionContexts.update(REGION, "000000000000", "stack", ID, + "{\"InferenceProfileName\":\"example\",\"ModelSource\":{\"CopyFrom\":\"" + SOURCE + + "\"},\"Tags\":[{\"Key\":\"team\",\"Value\":\"stack\"}]}"))); + + assertEquals("InternalFailure", updateFailure.getErrorCode()); + assertTrue(attempted.getAttributes().containsKey(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR)); + assertTrue(attempted.getAttributes().containsKey("__FlociBedrockProfilePriorTags")); + + provisioner.mergeFailedUpdateResourceTracking(previous, attempted); + previous.getAttributes().put(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR, + attempted.getAttributes().get(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR)); + assertTrue(previous.getAttributes().containsKey("__FlociBedrockProfilePriorTags")); + + assertTrue(provisioner.rollbackUpdate(previous)); + + assertFalse(previous.getAttributes().containsKey("__FlociBedrockProfilePriorTags")); + verify(bedrock, times(2)).tagResource(ARN, Map.of("team", "stack"), REGION); + } + + @Test + void deleteIgnoresOnlyAnAlreadyDeletedProfile() { + doThrow(new AwsException("ResourceNotFoundException", "missing", 404)) + .when(bedrock).deleteApplicationInferenceProfile(ID, REGION); + assertDoesNotThrow(() -> provisioner.delete(TYPE, ID, REGION)); + + doThrow(new AwsException("AccessDeniedException", "denied", 403)) + .when(bedrock).deleteApplicationInferenceProfile(ID, REGION); + assertEquals("AccessDeniedException", assertThrows(AwsException.class, + () -> provisioner.delete(TYPE, ID, REGION)).getErrorCode()); + } +} diff --git a/src/test/resources/cloudformation/schema-surface.tsv b/src/test/resources/cloudformation/schema-surface.tsv index bad924440d..dd81a8375f 100644 --- a/src/test/resources/cloudformation/schema-surface.tsv +++ b/src/test/resources/cloudformation/schema-surface.tsv @@ -40,6 +40,7 @@ AWS::Backup::BackupVault BackupVaultArn AccessPolicy,BackupVaultName,BackupVault AWS::Batch::ComputeEnvironment ComputeEnvironmentArn ComputeEnvironmentName,ComputeResources,Context,EcsSettings,EksConfiguration,ReplaceComputeEnvironment,ServiceRole,State,Tags,Type,UnmanagedvCpus,UpdatePolicy AWS::Batch::JobDefinition JobDefinitionArn ConsumableResourceProperties,ContainerProperties,EcsProperties,EksProperties,JobDefinitionName,NodeProperties,Parameters,PlatformCapabilities,PropagateTags,ResourceRetentionPolicy,RetryStrategy,SchedulingPriority,Tags,Timeout,Type AWS::Batch::JobQueue JobQueueArn ComputeEnvironmentOrder,JobQueueName,JobQueueType,JobStateTimeLimitActions,Priority,SchedulingPolicyArn,ServiceEnvironmentOrder,State,Tags +AWS::Bedrock::ApplicationInferenceProfile CreatedAt,InferenceProfileArn,InferenceProfileId,InferenceProfileIdentifier,Models,Status,Type,UpdatedAt Description,InferenceProfileName,ModelSource,Tags AWS::BedrockAgentCore::Memory CreatedAt,FailureReason,MemoryArn,MemoryId,Status,UpdatedAt Description,EncryptionKeyArn,EventExpiryDuration,IndexedKeys,MemoryExecutionRoleArn,MemoryStrategies,Name,NamespaceKeys,StreamDeliveryResources,Tags AWS::BedrockAgentCore::Runtime AgentRuntimeArn,AgentRuntimeId,AgentRuntimeVersion,CreatedAt,FailureReason,LastUpdatedAt,Status,WorkloadIdentityDetails AgentRuntimeArtifact,AgentRuntimeName,AuthorizerConfiguration,CapacityProviderConfiguration,Description,EnvironmentVariables,FilesystemConfigurations,LifecycleConfiguration,NetworkConfiguration,PlatformVersion,ProtocolConfiguration,RequestHeaderConfiguration,RoleArn,Tags AWS::BedrockAgentCore::RuntimeEndpoint AgentRuntimeArn,AgentRuntimeEndpointArn,CreatedAt,FailureReason,Id,LastUpdatedAt,LiveVersion,Status,TargetVersion AgentRuntimeId,AgentRuntimeVersion,Description,Name,Tags diff --git a/src/test/resources/cloudformation/supported-resource-types.tsv b/src/test/resources/cloudformation/supported-resource-types.tsv index 4965369832..9d915dc189 100644 --- a/src/test/resources/cloudformation/supported-resource-types.tsv +++ b/src/test/resources/cloudformation/supported-resource-types.tsv @@ -40,6 +40,7 @@ AWS::Backup::BackupVault BackupVaultCfnProvisioner AWS::Batch::ComputeEnvironment BatchCfnProvisioner AWS::Batch::JobDefinition BatchCfnProvisioner AWS::Batch::JobQueue BatchCfnProvisioner +AWS::Bedrock::ApplicationInferenceProfile BedrockCfnProvisioner AWS::BedrockAgentCore::Memory BedrockAgentCoreCfnProvisioner AWS::BedrockAgentCore::Runtime BedrockAgentCoreCfnProvisioner AWS::BedrockAgentCore::RuntimeEndpoint BedrockAgentCoreCfnProvisioner diff --git a/tools/docs/cfn_resource_types.yaml b/tools/docs/cfn_resource_types.yaml index 6a011207f9..3b67436cf6 100644 --- a/tools/docs/cfn_resource_types.yaml +++ b/tools/docs/cfn_resource_types.yaml @@ -63,6 +63,7 @@ order: - AWS::Logs - AWS::WAFv2 - AWS::Config + - AWS::Bedrock - AWS::BedrockAgentCore - AWS::CloudFormation - AWS::CloudTrail @@ -134,6 +135,7 @@ service_labels: AWS::AutoScaling: Auto Scaling AWS::Batch: Batch AWS::Backup: Backup + AWS::Bedrock: Amazon Bedrock AWS::BedrockAgentCore: Bedrock AgentCore AWS::CDK: CDK AWS::CertificateManager: ACM @@ -243,6 +245,7 @@ notes: AWS::AppConfig::DeploymentStrategy: '`Tags` are accepted and not stored; `ReplicateTo: SSM_DOCUMENT` writes no SSM document' AWS::CloudFront::Function: '`KeyValueStoreAssociations` is ignored' 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::Memory: 'Ref returns the memory ARN; MemoryStrategies, IndexedKeys, NamespaceKeys and StreamDeliveryResources are accepted and not stored'