feat(bedrock): add guardrail lifecycle and versions (#3380)

* feat(bedrock): add guardrail lifecycle and versions

Amazon Bedrock control plane over REST JSON: CreateGuardrail through
DeleteGuardrail, CreateGuardrailVersion, ListGuardrails with pagination, and
resource tagging on /tagResource, /untagResource and /listTagsForResource.
Guardrails report READY on the first read, so the Terraform provider's status
poll for aws_bedrock_guardrail completes without a transition.

The control plane and bedrock-runtime both sign as "bedrock". The runtime
descriptor keeps that credential scope, and the new descriptor routes through
its resource class, which ServiceEnabledFilter checks first.

Policy blocks are stored under the read-shape member names, so a *Config
submitted on create or update reads back unsuffixed. ListGuardrails honours
maxResults and nextToken, and DeleteGuardrail rejects a guardrailVersion that
is not a GuardrailNumericalVersion.

* fix(bedrock): enforce guardrail length caps and resolve kmsKeyId to a key ARN

The AWS model caps description at 200 characters and both blockedInputMessaging
and blockedOutputsMessaging at 500, each with a minimum of 1. None of those were
checked, so an over-long value was stored and read back. name was already bounded
by its [0-9a-zA-Z-_]{1,50} pattern.

kmsKeyId on CreateGuardrail and UpdateGuardrail is a KmsKeyId: a key id, a key
ARN, an alias name or an alias ARN. kmsKeyArn on the read shapes is a KmsKeyArn,
which is only ever the full key ARN. The request value was echoed back verbatim,
so a bare key id or an alias produced a response that does not match the shape
GetGuardrail declares. It now resolves through KmsService.describeKey, the same
way RDS, DocDB and ElastiCache already resolve their KmsKeyId, and a key that is
missing, disabled or pending deletion is rejected with ValidationException.

* test(bedrock): drive the guardrail lifecycle from the AWS SDK v2 client

Adds the bedrock SDK module to the compatibility project, a BedrockClient
factory on TestFixtures, and a BedrockGuardrailTest covering create, read,
update, versioning, listing, tagging and delete. The test also submits kmsKeyId
as a bare key id and as an alias and asserts both read back as the same full KMS
key ARN.

* fix(bedrock): enforce the guardrail tag caps from the AWS model

The AWS model gives TagList a max of 200 items, and that shape backs the tags
member of both CreateGuardrail and TagResource. TooManyTagsException, declared
on both operations, documents a separate limit of 50 tags per resource counted
over the tags already on the resource together with the ones in the request.

parseTagList now rejects an array over 200 items with ValidationException, and
it moved to BedrockService so both entry points share it. CreateGuardrail and
TagResource raise TooManyTagsException once the total the guardrail would be
left holding passes 50, carrying resourceName as the model declares.
This commit is contained in:
lex00 authored and GitHub committed 2026-09-11 20:36:45 -04:00
1 parent 78cf107fcb
commit cae8f9a013
17 files changed
+2456 -1

No files matched your search

+2 -1
View File
@@ -235,7 +235,7 @@ Floci supports local emulation for application services, data services, eventing
| Events and workflows | EventBridge, EventBridge Pipes, EventBridge Scheduler, Step Functions, SWF, CloudWatch Logs, CloudWatch Metrics, CloudWatch RUM, Managed Prometheus (AMP) |
| API and identity | API Gateway REST, API Gateway v2, AppSync, Cognito, ACM, Route53, Route 53 Resolver, Cloud Map, Global Accelerator |
| Containers and compute | ECS, EC2, Lightsail, EKS, MWAA, ECR, EFS, CodeBuild, CodeDeploy, CodePipeline, CodeGuru Reviewer, AWS Batch, Auto Scaling, Application Auto Scaling, Elastic Beanstalk, ELB v2, ELB Classic |
| Data, analytics, and AI | Athena, Glue, Lake Formation, EMR, EMR Serverless, Redshift, Redshift Data API, Firehose, Managed Service for Apache Flink, OpenSearch, S3 Tables, S3 Vectors, Textract, Transcribe, Comprehend, Rekognition, Translate, Bedrock Runtime, Bedrock AgentCore |
| Data, analytics, and AI | Athena, Glue, Lake Formation, EMR, EMR Serverless, Redshift, Redshift Data API, Firehose, Managed Service for Apache Flink, OpenSearch, S3 Tables, S3 Vectors, Textract, Transcribe, Comprehend, Rekognition, Translate, Bedrock, Bedrock Runtime, Bedrock AgentCore |
| Databases and caching | RDS, RDS Data API, Neptune, DocumentDB, MemoryDB, ElastiCache |
| Messaging and transfer | SES, Kinesis, MSK, Amazon MQ, Transfer Family, IoT Core, Amazon Connect, Amazon AppIntegrations |
| Security and governance | AWS Network Firewall, AWS RAM, Service Quotas, WAF v2, GuardDuty, Amazon Inspector, CloudTrail, CloudFront, Resource Groups Tagging API, Resource Explorer 2, CloudHSM v2, Organizations, AWS Account Management, IAM Access Analyzer, IAM Identity Center (SSO Admin, OIDC, Access Portal, SCIM), Identity Store, Amazon Macie, Amazon Detective, Security Hub, Amazon Verified Permissions, Control Catalog, Control Tower, Service Catalog, AWS Marketplace |
@@ -295,6 +295,7 @@ For operation-level compatibility, see the [Services Overview](https://floci.io/
| OpenSearch | Real Docker | Domain CRUD, tags, versions, instance types, upgrade stubs |
| AppConfig | In-process | Applications, environments, profiles, hosted versions, deployments |
| AppConfigData | In-process | Configuration sessions and dynamic configuration retrieval |
| Bedrock | In-process | Guardrail lifecycle, versions, and tags on the control plane |
| Bedrock Runtime | In-process stub | Dummy Converse and InvokeModel responses for local development |
| Bedrock AgentCore | In-process stub | Stateful control plane (agent runtimes, gateways, memory, workload identity); canned InvokeAgentRuntime responses |
| EKS | Real Docker, mock mode available | k3s clusters with live Kubernetes API server |
@@ -420,6 +420,11 @@
<groupId>software.amazon.awssdk</groupId>
<artifactId>pipes</artifactId>
</dependency>
<!-- Bedrock control-plane client (guardrails) -->
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>bedrock</artifactId>
</dependency>
<!-- Bedrock AgentCore control-plane client -->
<dependency>
<groupId>software.amazon.awssdk</groupId>
@@ -89,6 +89,7 @@ import software.amazon.awssdk.services.amp.AmpClient;
import software.amazon.awssdk.services.efs.EfsClient;
import software.amazon.awssdk.services.ec2.Ec2Client;
import software.amazon.awssdk.services.ecr.EcrClient;
import software.amazon.awssdk.services.bedrock.BedrockClient;
import software.amazon.awssdk.services.bedrockagentcore.BedrockAgentCoreClient;
import software.amazon.awssdk.services.bedrockagentcorecontrol.BedrockAgentCoreControlClient;
import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeAsyncClient;
@@ -1194,6 +1195,14 @@ public final class TestFixtures {
.build();
}
public static BedrockClient bedrockClient() {
return BedrockClient.builder()
.endpointOverride(ENDPOINT)
.region(REGION)
.credentialsProvider(CREDENTIALS)
.build();
}
public static BedrockAgentCoreControlClient bedrockAgentCoreControlClient() {
return BedrockAgentCoreControlClient.builder()
.endpointOverride(ENDPOINT)
@@ -0,0 +1,239 @@
package com.floci.test;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import software.amazon.awssdk.services.bedrock.BedrockClient;
import software.amazon.awssdk.services.bedrock.model.CreateGuardrailResponse;
import software.amazon.awssdk.services.bedrock.model.CreateGuardrailVersionResponse;
import software.amazon.awssdk.services.bedrock.model.GetGuardrailResponse;
import software.amazon.awssdk.services.bedrock.model.GuardrailContentFilterType;
import software.amazon.awssdk.services.bedrock.model.GuardrailFilterStrength;
import software.amazon.awssdk.services.bedrock.model.GuardrailStatus;
import software.amazon.awssdk.services.bedrock.model.GuardrailTopicType;
import software.amazon.awssdk.services.bedrock.model.ListGuardrailsResponse;
import software.amazon.awssdk.services.bedrock.model.ResourceNotFoundException;
import software.amazon.awssdk.services.bedrock.model.Tag;
import software.amazon.awssdk.services.bedrock.model.TooManyTagsException;
import software.amazon.awssdk.services.bedrock.model.UpdateGuardrailResponse;
import software.amazon.awssdk.services.bedrock.model.ValidationException;
import software.amazon.awssdk.services.kms.KmsClient;
import java.util.ArrayList;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@DisplayName("Bedrock guardrails")
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class BedrockGuardrailTest {
private static BedrockClient bedrock;
private static String name;
private static String guardrailId;
private static String guardrailArn;
private static String kmsKeyId;
private static String kmsKeyArn;
private static String kmsAlias;
@BeforeAll
static void setup() {
bedrock = TestFixtures.bedrockClient();
name = "sdk-test-guardrail-" + System.currentTimeMillis();
kmsAlias = "alias/sdk-test-guardrail-" + System.currentTimeMillis();
try (KmsClient kms = TestFixtures.kmsClient()) {
var key = kms.createKey(r -> r.description("sdk compatibility guardrail key")).keyMetadata();
kmsKeyId = key.keyId();
kmsKeyArn = key.arn();
kms.createAlias(r -> r.aliasName(kmsAlias).targetKeyId(kmsKeyId));
}
}
@AfterAll
static void cleanup() {
if (bedrock != null) {
if (guardrailId != null) {
try {
bedrock.deleteGuardrail(r -> r.guardrailIdentifier(guardrailId));
} catch (Exception e) {
System.out.println("Guardrail cleanup skipped: " + e.getMessage());
}
}
bedrock.close();
}
}
@Test
@Order(1)
void createGuardrail() {
CreateGuardrailResponse response = bedrock.createGuardrail(r -> r
.name(name)
.description("created by the sdk compatibility suite")
.blockedInputMessaging("Input blocked.")
.blockedOutputsMessaging("Output blocked.")
.kmsKeyId(kmsKeyId)
.topicPolicyConfig(t -> t.topicsConfig(topic -> topic
.name("Investments")
.definition("Advice about buying or selling securities.")
.type(GuardrailTopicType.DENY)))
.contentPolicyConfig(c -> c.filtersConfig(f -> f
.type(GuardrailContentFilterType.HATE)
.inputStrength(GuardrailFilterStrength.HIGH)
.outputStrength(GuardrailFilterStrength.HIGH)))
.tags(Tag.builder().key("suite").value("sdk-compat").build()));
guardrailId = response.guardrailId();
guardrailArn = response.guardrailArn();
assertThat(guardrailId).isNotBlank();
assertThat(guardrailArn).contains(":bedrock:").contains(":guardrail/" + guardrailId);
assertThat(response.version()).isEqualTo("DRAFT");
assertThat(response.createdAt()).isNotNull();
}
@Test
@Order(2)
void getGuardrailReadsBackTheReadShapes() {
GetGuardrailResponse response = bedrock.getGuardrail(r -> r.guardrailIdentifier(guardrailId));
assertThat(response.name()).isEqualTo(name);
assertThat(response.guardrailId()).isEqualTo(guardrailId);
assertThat(response.guardrailArn()).isEqualTo(guardrailArn);
assertThat(response.version()).isEqualTo("DRAFT");
// The terraform provider's create waiter polls until the guardrail leaves CREATING.
assertThat(response.status()).isEqualTo(GuardrailStatus.READY);
assertThat(response.blockedInputMessaging()).isEqualTo("Input blocked.");
assertThat(response.blockedOutputsMessaging()).isEqualTo("Output blocked.");
// A bare key id on the request comes back as a full KMS key ARN, which is the
// only shape the GetGuardrail response model accepts.
assertThat(response.kmsKeyArn()).isEqualTo(kmsKeyArn);
assertThat(response.topicPolicy().topics()).singleElement()
.satisfies(t -> assertThat(t.name()).isEqualTo("Investments"));
assertThat(response.contentPolicy().filters()).singleElement()
.satisfies(f -> assertThat(f.type()).isEqualTo(GuardrailContentFilterType.HATE));
}
@Test
@Order(3)
void updateGuardrail() {
UpdateGuardrailResponse response = bedrock.updateGuardrail(r -> r
.guardrailIdentifier(guardrailId)
.name(name)
.description("updated by the sdk compatibility suite")
.blockedInputMessaging("Input still blocked.")
.blockedOutputsMessaging("Output still blocked.")
.kmsKeyId(kmsAlias));
assertThat(response.guardrailId()).isEqualTo(guardrailId);
assertThat(response.version()).isEqualTo("DRAFT");
assertThat(response.updatedAt()).isNotNull();
GetGuardrailResponse updated = bedrock.getGuardrail(r -> r.guardrailIdentifier(guardrailId));
assertThat(updated.description()).isEqualTo("updated by the sdk compatibility suite");
// An alias resolves to the same key ARN a bare key id did.
assertThat(updated.kmsKeyArn()).isEqualTo(kmsKeyArn);
}
@Test
@Order(4)
void createGuardrailRejectsAnOverLongBlockedMessaging() {
assertThatThrownBy(() -> bedrock.createGuardrail(r -> r
.name(name + "-toolong")
.blockedInputMessaging("x".repeat(501))
.blockedOutputsMessaging("Output blocked.")))
.isInstanceOf(ValidationException.class);
}
@Test
@Order(5)
void createGuardrailVersionSnapshotsTheDraft() {
CreateGuardrailVersionResponse response = bedrock.createGuardrailVersion(r -> r
.guardrailIdentifier(guardrailId)
.description("first published version"));
assertThat(response.guardrailId()).isEqualTo(guardrailId);
assertThat(response.version()).isEqualTo("1");
GetGuardrailResponse published = bedrock.getGuardrail(r -> r
.guardrailIdentifier(guardrailId).guardrailVersion("1"));
assertThat(published.version()).isEqualTo("1");
assertThat(published.description()).isEqualTo("first published version");
assertThat(published.blockedInputMessaging()).isEqualTo("Input still blocked.");
}
@Test
@Order(6)
void listGuardrailsReturnsTheDraft() {
ListGuardrailsResponse response = bedrock.listGuardrails(r -> r.maxResults(100));
assertThat(response.guardrails())
.anySatisfy(g -> {
assertThat(g.id()).isEqualTo(guardrailId);
assertThat(g.arn()).isEqualTo(guardrailArn);
assertThat(g.status()).isEqualTo(GuardrailStatus.READY);
});
}
@Test
@Order(7)
void tagResourceRoundTrip() {
bedrock.tagResource(r -> r.resourceARN(guardrailArn)
.tags(Tag.builder().key("env").value("test").build()));
assertThat(bedrock.listTagsForResource(r -> r.resourceARN(guardrailArn)).tags())
.anySatisfy(t -> {
assertThat(t.key()).isEqualTo("env");
assertThat(t.value()).isEqualTo("test");
});
bedrock.untagResource(r -> r.resourceARN(guardrailArn).tagKeys("env"));
assertThat(bedrock.listTagsForResource(r -> r.resourceARN(guardrailArn)).tags())
.noneSatisfy(t -> assertThat(t.key()).isEqualTo("env"));
}
@Test
@Order(8)
void tagResourceRejectsMoreTagsThanOneResourceMayHold() {
// The 50 tag limit belongs to the resource, so it is measured against the total left
// after the merge rather than the size of the incoming request.
bedrock.tagResource(r -> r.resourceARN(guardrailArn).tags(tags("bulk-", 49)));
assertThatThrownBy(() -> bedrock.tagResource(r -> r.resourceARN(guardrailArn)
.tags(Tag.builder().key("one-too-many").value("x").build())))
.isInstanceOf(TooManyTagsException.class)
.satisfies(e -> assertThat(((TooManyTagsException) e).resourceName()).isEqualTo(guardrailArn));
bedrock.untagResource(r -> r.resourceARN(guardrailArn)
.tagKeys(tags("bulk-", 49).stream().map(Tag::key).toList()));
}
private static List<Tag> tags(String prefix, int count) {
List<Tag> tags = new ArrayList<>();
for (int i = 0; i < count; i++) {
tags.add(Tag.builder().key(prefix + i).value("v" + i).build());
}
return tags;
}
@Test
@Order(9)
void deleteGuardrailThenGetThrowsResourceNotFound() {
bedrock.deleteGuardrail(r -> r.guardrailIdentifier(guardrailId));
// The terraform provider's delete waiter matches this typed exception to treat
// the guardrail as gone.
String deletedId = guardrailId;
assertThatThrownBy(() -> bedrock.getGuardrail(r -> r.guardrailIdentifier(deletedId)))
.isInstanceOf(ResourceNotFoundException.class);
guardrailId = null;
}
}
+108
View File
@@ -0,0 +1,108 @@
# Amazon Bedrock (control plane)
**Protocol:** REST-JSON
**Endpoint:** `http://localhost:4566/guardrails` (SigV4 service `bedrock`)
This page covers the Bedrock control plane. Model invocation is a separate service
that shares the same signing name: see [Bedrock Runtime](bedrock-runtime.md).
## Supported Actions
<!-- floci:actions:start -->
| Action | Description |
| --- | --- |
| `CreateGuardrail` | Create a guardrail; returns the `DRAFT` version, `READY` immediately |
| `GetGuardrail` | Read a guardrail by id or ARN, at `DRAFT` or a numbered `guardrailVersion` |
| `UpdateGuardrail` | Replace the `DRAFT` configuration |
| `CreateGuardrailVersion` | Snapshot the `DRAFT` under the next numerical version |
| `DeleteGuardrail` | Delete one numerical version, or the guardrail and all its versions |
| `ListGuardrails` | List every guardrail's `DRAFT`, or every version of one guardrail |
| `TagResource` | Tag a guardrail (`POST /tagResource`) |
| `UntagResource` | Remove tags from a guardrail (`POST /untagResource`) |
| `ListTagsForResource` | List a guardrail's tags (`POST /listTagsForResource`) |
<!-- floci:actions:end -->
Guardrails are versioned. The working copy is `DRAFT`, and `GetGuardrail` without a
`guardrailVersion` query parameter returns it. `CreateGuardrailVersion` copies the
current `DRAFT` to `1`, `2` and so on. Those snapshots are immutable, because
`UpdateGuardrail` only ever writes `DRAFT`.
`GuardrailStatus` is `READY` from the first read, so `aws_bedrock_guardrail`'s status
poll completes without a transition. Policy blocks are submitted as the `*Config`
shapes (`topicPolicyConfig`, `contentPolicyConfig` and the rest) and read back under
their unsuffixed names (`topicPolicy.topics`, `contentPolicy.filters`), matching the
AWS model.
`ListGuardrails` returns one `DRAFT` summary per guardrail. Passing
`guardrailIdentifier` returns every version of that one guardrail instead. Both forms
honour `maxResults` and `nextToken`.
`DeleteGuardrail` takes a `GuardrailNumericalVersion`, so a version query parameter of
`DRAFT` is rejected with `ValidationException`. Omit the parameter to delete the
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`.
`kmsKeyId` on `CreateGuardrail` and `UpdateGuardrail` is a `KmsKeyId`: a key id, a key
ARN, an alias name or an alias ARN. `kmsKeyArn` on the read shapes is a `KmsKeyArn`,
which is only ever the full key ARN, so every accepted form is resolved through KMS to
that one shape. A key that does not exist, is disabled, or is pending deletion is
rejected with `ValidationException`.
The AWS model's length constraints are enforced: `name` is 1 to 50 characters matching
`[0-9a-zA-Z-_]+`, `description` is 1 to 200, and `blockedInputMessaging` and
`blockedOutputsMessaging` are 1 to 500 each. A value outside those bounds is rejected
with `ValidationException`.
The model's tag limits are enforced as well. A `TagList` holds at most 200 items on one
request, and a longer array is rejected with `ValidationException`. A guardrail holds at
most 50 tags, counted over the tags already on it together with the tags in the current
request, so `CreateGuardrail` and `TagResource` both raise `TooManyTagsException` once
the resulting total would pass 50. Replacing the value of a tag key the guardrail
already carries does not add to that total.
## Not implemented
The rest of the Bedrock control plane is absent rather than stubbed, because
emulating it faithfully would require behaviour Floci has no way to model:
- `ListFoundationModels` and `GetFoundationModel`. The AWS service model carries no
enumeration of foundation model ids, so any catalogue would be invented data.
- 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, inference profiles 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.
## Configuration
| Variable | Default | Description |
|---|---|---|
| `FLOCI_SERVICES_BEDROCK_ENABLED` | `true` | Enable or disable the service |
## Examples
```bash
export AWS_ENDPOINT_URL=http://localhost:4566
aws bedrock create-guardrail \
--name my-guardrail \
--blocked-input-messaging "Blocked." \
--blocked-outputs-messaging "Blocked." \
--content-policy-config '{"filtersConfig":[{"type":"HATE","inputStrength":"HIGH","outputStrength":"HIGH"}]}'
aws bedrock get-guardrail --guardrail-identifier abc123def456
aws bedrock create-guardrail-version --guardrail-identifier abc123def456
aws bedrock list-guardrails
aws bedrock tag-resource \
--resource-arn arn:aws:bedrock:us-east-1:000000000000:guardrail/abc123def456 \
--tags key=team,value=ai
aws bedrock delete-guardrail --guardrail-identifier abc123def456
```
+1
View File
@@ -89,6 +89,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}`, `/tagResource`, `/untagResource`, `/listTagsForResource` | REST JSON | 9 |
| [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*`, `/resourcepolicy/*`, `/tags/{resourceArn}` | REST JSON | 61 (+ 3 tagging via shared `/tags/{arn}` route) |
| [Bedrock AgentCore](bedrock-agentcore.md#data-plane-invokeagentruntime) | `/runtimes/{agentRuntimeArn}/invocations` | REST JSON (binary payload) | 1 (canned-response stub) |
+1
View File
@@ -170,6 +170,7 @@ nav:
- EC2: services/ec2.md
- Lightsail: services/lightsail.md
- AppConfig: services/appconfig.md
- Bedrock: services/bedrock.md
- Bedrock Runtime: services/bedrock-runtime.md
- Bedrock AgentCore: services/bedrock-agentcore.md
- ELB v2: services/elb.md
@@ -672,6 +672,7 @@ public interface EmulatorConfig {
AppConfigDataServiceConfig appconfigdata();
EcrServiceConfig ecr();
ResourceGroupsTaggingServiceConfig tagging();
BedrockServiceConfig bedrock();
BedrockRuntimeServiceConfig bedrockRuntime();
EksServiceConfig eks();
MwaaServiceConfig mwaa();
@@ -1751,6 +1752,11 @@ public interface EmulatorConfig {
boolean enabled();
}
interface BedrockServiceConfig {
@WithDefault("true")
boolean enabled();
}
interface BedrockRuntimeServiceConfig {
@WithDefault("true")
boolean enabled();
@@ -6,6 +6,7 @@ import io.github.hectorvent.floci.services.backup.BackupController;
import io.github.hectorvent.floci.services.resourceexplorer2.ResourceExplorer2Controller;
import io.github.hectorvent.floci.services.appconfig.AppConfigDataController;
import io.github.hectorvent.floci.services.batch.BatchController;
import io.github.hectorvent.floci.services.bedrock.BedrockController;
import io.github.hectorvent.floci.services.bedrockruntime.BedrockRuntimeController;
import io.github.hectorvent.floci.services.cognito.CognitoOAuthController;
import io.github.hectorvent.floci.services.cognito.CognitoWellKnownController;
@@ -317,6 +318,17 @@ public class ResolvedServiceCatalog {
config.storage().services().tagging().flushIntervalMs(), null, ServiceProtocol.JSON,
protocols(ServiceProtocol.JSON),
Set.of("ResourceGroupsTaggingAPI_20170126."), Set.of("tagging"), Set.of(), Set.of()),
descriptor("bedrock", "bedrock", config.services().bedrock().enabled(), true,
"bedrock", config.storage().mode(), 5000L, null, ServiceProtocol.REST_JSON,
protocols(ServiceProtocol.REST_JSON),
Set.of(),
// The control plane and bedrock-runtime both sign as "bedrock", and
// credential-scope registration is last-write-wins. bedrock-runtime
// already claims that scope; claiming it again here would move its
// enablement resolution onto this descriptor. Requests for these
// routes resolve through resourceClasses, which is checked first.
Set.of(), Set.of(),
Set.of(BedrockController.class)),
descriptor("bedrock-runtime", "bedrock-runtime",
config.services().bedrockRuntime().enabled(), true,
null, null, 5000L, null, ServiceProtocol.REST_JSON,
@@ -0,0 +1,258 @@
package io.github.hectorvent.floci.services.bedrock;
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.github.hectorvent.floci.core.common.JsonErrorResponseUtils;
import io.github.hectorvent.floci.core.common.PaginatedResult;
import io.github.hectorvent.floci.core.common.Pagination;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.services.bedrock.model.Guardrail;
import jakarta.inject.Inject;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.DELETE;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.PUT;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.QueryParam;
import jakarta.ws.rs.WebApplicationException;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import java.time.Instant;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* Amazon Bedrock control plane REST-JSON controller.
*
* <p>Only the operations declared below are served. The data plane
* ({@code /model/{modelId}/...}) belongs to the separate bedrock-runtime service,
* which signs under the same {@code bedrock} name.
*/
@Path("/")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class BedrockController {
private final BedrockService bedrockService;
private final RegionResolver regionResolver;
private final ObjectMapper objectMapper;
@Inject
public BedrockController(BedrockService bedrockService, RegionResolver regionResolver,
ObjectMapper objectMapper) {
this.bedrockService = bedrockService;
this.regionResolver = regionResolver;
this.objectMapper = objectMapper;
}
// Guardrails
@POST
@Path("/guardrails")
public Response createGuardrail(@Context HttpHeaders headers, String body) {
String region = regionResolver.resolveRegion(headers);
Guardrail guardrail = bedrockService.createGuardrail(readTree(body), region);
ObjectNode response = objectMapper.createObjectNode();
response.put("guardrailId", guardrail.getGuardrailId());
response.put("guardrailArn", guardrail.getGuardrailArn());
response.put("version", guardrail.getVersion());
response.put("createdAt", iso8601(guardrail.getCreatedAt()));
return Response.status(202).entity(response).build();
}
@GET
@Path("/guardrails/{guardrailIdentifier}")
public Response getGuardrail(@PathParam("guardrailIdentifier") String guardrailIdentifier,
@QueryParam("guardrailVersion") String guardrailVersion,
@Context HttpHeaders headers) {
String region = regionResolver.resolveRegion(headers);
Guardrail guardrail = bedrockService.getGuardrail(guardrailIdentifier, guardrailVersion, region);
return Response.ok(guardrailNode(guardrail)).build();
}
@PUT
@Path("/guardrails/{guardrailIdentifier}")
public Response updateGuardrail(@PathParam("guardrailIdentifier") String guardrailIdentifier,
@Context HttpHeaders headers, String body) {
String region = regionResolver.resolveRegion(headers);
Guardrail guardrail = bedrockService.updateGuardrail(guardrailIdentifier, readTree(body), region);
ObjectNode response = objectMapper.createObjectNode();
response.put("guardrailId", guardrail.getGuardrailId());
response.put("guardrailArn", guardrail.getGuardrailArn());
response.put("version", guardrail.getVersion());
response.put("updatedAt", iso8601(guardrail.getUpdatedAt()));
return Response.status(202).entity(response).build();
}
@POST
@Path("/guardrails/{guardrailIdentifier}")
public Response createGuardrailVersion(@PathParam("guardrailIdentifier") String guardrailIdentifier,
@Context HttpHeaders headers, String body) {
String region = regionResolver.resolveRegion(headers);
JsonNode request = readTree(body);
Guardrail version = bedrockService.createGuardrailVersion(guardrailIdentifier,
textOrNull(request, "description"), region);
ObjectNode response = objectMapper.createObjectNode();
response.put("guardrailId", version.getGuardrailId());
response.put("version", version.getVersion());
return Response.status(202).entity(response).build();
}
@DELETE
@Path("/guardrails/{guardrailIdentifier}")
public Response deleteGuardrail(@PathParam("guardrailIdentifier") String guardrailIdentifier,
@QueryParam("guardrailVersion") String guardrailVersion,
@Context HttpHeaders headers) {
String region = regionResolver.resolveRegion(headers);
bedrockService.deleteGuardrail(guardrailIdentifier, guardrailVersion, region);
return Response.status(202).build();
}
@GET
@Path("/guardrails")
public Response listGuardrails(@QueryParam("guardrailIdentifier") String guardrailIdentifier,
@QueryParam("maxResults") String maxResults,
@QueryParam("nextToken") String nextToken,
@Context HttpHeaders headers) {
String region = regionResolver.resolveRegion(headers);
PaginatedResult<Guardrail> page = bedrockService.listGuardrails(guardrailIdentifier,
Pagination.parseMaxResults(maxResults, "ValidationException"), nextToken, region);
ObjectNode response = objectMapper.createObjectNode();
ArrayNode summaries = response.putArray("guardrails");
for (Guardrail guardrail : page.items()) {
summaries.add(guardrailSummaryNode(guardrail));
}
if (page.nextToken() != null) {
response.put("nextToken", page.nextToken());
}
return Response.ok(response).build();
}
// Tags
@POST
@Path("/tagResource")
public Response tagResource(@Context HttpHeaders headers, String body) {
String region = regionResolver.resolveRegion(headers);
JsonNode request = readTree(body);
bedrockService.tagResource(textOrNull(request, "resourceARN"),
BedrockService.parseTagList(request.get("tags")), region);
return Response.ok(objectMapper.createObjectNode()).build();
}
@POST
@Path("/untagResource")
public Response untagResource(@Context HttpHeaders headers, String body) {
String region = regionResolver.resolveRegion(headers);
JsonNode request = readTree(body);
List<String> tagKeys = new ArrayList<>();
JsonNode keys = request.get("tagKeys");
if (keys != null && keys.isArray()) {
keys.forEach(key -> tagKeys.add(key.asText()));
}
bedrockService.untagResource(textOrNull(request, "resourceARN"), tagKeys, region);
return Response.ok(objectMapper.createObjectNode()).build();
}
@POST
@Path("/listTagsForResource")
public Response listTagsForResource(@Context HttpHeaders headers, String body) {
String region = regionResolver.resolveRegion(headers);
JsonNode request = readTree(body);
Map<String, String> tags = bedrockService.listTags(textOrNull(request, "resourceARN"), region);
ObjectNode response = objectMapper.createObjectNode();
ArrayNode array = response.putArray("tags");
tags.forEach((key, value) -> {
ObjectNode tag = array.addObject();
tag.put("key", key);
tag.put("value", value);
});
return Response.ok(response).build();
}
// Helpers
private ObjectNode guardrailNode(Guardrail guardrail) {
ObjectNode node = objectMapper.createObjectNode();
node.put("name", guardrail.getName());
if (guardrail.getDescription() != null) {
node.put("description", guardrail.getDescription());
}
node.put("guardrailId", guardrail.getGuardrailId());
node.put("guardrailArn", guardrail.getGuardrailArn());
node.put("version", guardrail.getVersion());
node.put("status", BedrockService.READY);
setIfPresent(node, "topicPolicy", guardrail.getTopicPolicy());
setIfPresent(node, "contentPolicy", guardrail.getContentPolicy());
setIfPresent(node, "wordPolicy", guardrail.getWordPolicy());
setIfPresent(node, "sensitiveInformationPolicy", guardrail.getSensitiveInformationPolicy());
setIfPresent(node, "contextualGroundingPolicy", guardrail.getContextualGroundingPolicy());
setIfPresent(node, "automatedReasoningPolicy", guardrail.getAutomatedReasoningPolicy());
setIfPresent(node, "crossRegionDetails", guardrail.getCrossRegionDetails());
node.put("createdAt", iso8601(guardrail.getCreatedAt()));
node.put("updatedAt", iso8601(guardrail.getUpdatedAt()));
node.put("blockedInputMessaging", guardrail.getBlockedInputMessaging());
node.put("blockedOutputsMessaging", guardrail.getBlockedOutputsMessaging());
if (guardrail.getKmsKeyArn() != null) {
node.put("kmsKeyArn", guardrail.getKmsKeyArn());
}
return node;
}
private ObjectNode guardrailSummaryNode(Guardrail guardrail) {
ObjectNode node = objectMapper.createObjectNode();
node.put("id", guardrail.getGuardrailId());
node.put("arn", guardrail.getGuardrailArn());
node.put("status", BedrockService.READY);
node.put("name", guardrail.getName());
if (guardrail.getDescription() != null) {
node.put("description", guardrail.getDescription());
}
node.put("version", guardrail.getVersion());
node.put("createdAt", iso8601(guardrail.getCreatedAt()));
node.put("updatedAt", iso8601(guardrail.getUpdatedAt()));
setIfPresent(node, "crossRegionDetails", guardrail.getCrossRegionDetails());
return node;
}
private void setIfPresent(ObjectNode node, String field, JsonNode value) {
if (value != null && !value.isNull()) {
node.set(field, value);
}
}
private String iso8601(Instant instant) {
return DateTimeFormatter.ISO_INSTANT.format(instant);
}
private JsonNode readTree(String body) {
try {
return objectMapper.readTree(body == null || body.isBlank() ? "{}" : body);
} catch (Exception e) {
throw new WebApplicationException(JsonErrorResponseUtils.createSerializationErrorResponse());
}
}
private String textOrNull(JsonNode node, String field) {
JsonNode value = node.get(field);
if (value == null || value.isNull()) {
return null;
}
return value.asText();
}
}
@@ -0,0 +1,529 @@
package io.github.hectorvent.floci.services.bedrock;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.PaginatedResult;
import io.github.hectorvent.floci.core.common.Pagination;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.bedrock.model.Guardrail;
import io.github.hectorvent.floci.services.kms.KmsService;
import io.github.hectorvent.floci.services.kms.model.KmsKey;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Pattern;
/**
* Amazon Bedrock control plane (signing name {@code bedrock}). Guardrails are
* versioned: the working copy is {@code DRAFT} and {@code CreateGuardrailVersion}
* snapshots it under the next numerical version. Every guardrail is READY as soon
* as it is created, so {@code aws_bedrock_guardrail}'s status poll completes on its
* first read.
*
* <p>Model invocation is a separate service, {@code bedrock-runtime}, which shares
* this signing name but serves the {@code /model/...} routes.
*/
@ApplicationScoped
public class BedrockService {
public static final String DRAFT_VERSION = "DRAFT";
public static final String READY = "READY";
private static final Logger LOG = Logger.getLogger(BedrockService.class);
/** {@code GuardrailName} from the AWS model. */
private static final Pattern NAME_PATTERN = Pattern.compile("[0-9a-zA-Z\\-_]{1,50}");
/** {@code GuardrailNumericalVersion} from the AWS model. */
private static final Pattern NUMERICAL_VERSION_PATTERN = Pattern.compile("[1-9][0-9]{0,7}");
/** {@code GuardrailDescription} from the AWS model: min 1, max 200. */
private static final int DESCRIPTION_MAX = 200;
/** {@code GuardrailBlockedMessaging} from the AWS model: min 1, max 500. */
private static final int BLOCKED_MESSAGING_MAX = 500;
/** {@code MaxResults} on {@code ListGuardrails} is capped at 1000 by the AWS model. */
private static final int MAX_PAGE = 1000;
/** {@code TagList} from the AWS model: at most 200 items on one request. */
private static final int TAG_LIST_MAX = 200;
/**
* {@code TooManyTagsException} documents a limit of 50 tags per resource, counted over the
* tags already on the resource together with the tags carried by the current request.
*/
private static final int TAGS_PER_RESOURCE_MAX = 50;
/**
* Policy blocks arrive as {@code *Config} shapes on create and update, and are read back
* as their unsuffixed counterparts. The member structures are identical in the AWS
* model, only these container keys are renamed.
*/
private static final Map<String, String> POLICY_MEMBER_RENAMES = Map.of(
"topicsConfig", "topics",
"filtersConfig", "filters",
"tierConfig", "tier",
"wordsConfig", "words",
"managedWordListsConfig", "managedWordLists",
"piiEntitiesConfig", "piiEntities",
"regexesConfig", "regexes");
private final StorageBackend<String, Guardrail> guardrails;
private final RegionResolver regionResolver;
private final ObjectMapper objectMapper;
private final KmsService kmsService;
@Inject
public BedrockService(StorageFactory storageFactory, RegionResolver regionResolver,
ObjectMapper objectMapper, KmsService kmsService) {
this(storageFactory.create("bedrock", "bedrock-guardrails.json",
new TypeReference<Map<String, Guardrail>>() {}), regionResolver, objectMapper, kmsService);
}
BedrockService(StorageBackend<String, Guardrail> guardrails, RegionResolver regionResolver,
ObjectMapper objectMapper, KmsService kmsService) {
this.guardrails = guardrails;
this.regionResolver = regionResolver;
this.objectMapper = objectMapper;
this.kmsService = kmsService;
}
public Guardrail createGuardrail(JsonNode request, String region) {
String name = requiredName(request);
String description = boundedDescription(request);
String blockedInputMessaging = requiredBlockedMessaging(request, "blockedInputMessaging");
String blockedOutputsMessaging = requiredBlockedMessaging(request, "blockedOutputsMessaging");
for (Guardrail existing : draftsIn(region)) {
if (name.equals(existing.getName())) {
throw new AwsException("ConflictException",
"Guardrail with name " + name + " already exists.", 400);
}
}
String guardrailId = newGuardrailId();
String guardrailArn = regionResolver.buildArn("bedrock", region, "guardrail/" + guardrailId);
Map<String, String> tags = parseTagList(request.get("tags"));
if (tags.size() > TAGS_PER_RESOURCE_MAX) {
throw tooManyTags(guardrailArn, tags.size());
}
Instant now = Instant.now();
Guardrail guardrail = new Guardrail();
guardrail.setGuardrailId(guardrailId);
guardrail.setGuardrailArn(guardrailArn);
guardrail.setName(name);
guardrail.setDescription(description);
guardrail.setVersion(DRAFT_VERSION);
guardrail.setBlockedInputMessaging(blockedInputMessaging);
guardrail.setBlockedOutputsMessaging(blockedOutputsMessaging);
guardrail.setKmsKeyArn(resolveKmsKeyArn(textOrNull(request, "kmsKeyId"), region));
guardrail.setCreatedAt(now);
guardrail.setUpdatedAt(now);
guardrail.setTags(tags);
guardrail.setAccountId(regionResolver.getAccountId());
applyPolicies(guardrail, request, region);
guardrails.put(storageKey(region, guardrailId, DRAFT_VERSION), guardrail);
LOG.infov("Created Bedrock guardrail: {0}", guardrailId);
return guardrail;
}
public Guardrail getGuardrail(String identifier, String version, String region) {
String guardrailId = resolveGuardrailId(identifier);
String effectiveVersion = (version == null || version.isBlank()) ? DRAFT_VERSION : version;
return guardrails.get(storageKey(region, guardrailId, effectiveVersion))
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
"Guardrail " + guardrailId + " version " + effectiveVersion + " does not exist.", 404));
}
public Guardrail updateGuardrail(String identifier, JsonNode request, String region) {
String name = requiredName(request);
String description = boundedDescription(request);
String blockedInputMessaging = requiredBlockedMessaging(request, "blockedInputMessaging");
String blockedOutputsMessaging = requiredBlockedMessaging(request, "blockedOutputsMessaging");
Guardrail guardrail = getGuardrail(identifier, DRAFT_VERSION, region);
guardrail.setName(name);
guardrail.setDescription(description);
guardrail.setBlockedInputMessaging(blockedInputMessaging);
guardrail.setBlockedOutputsMessaging(blockedOutputsMessaging);
guardrail.setKmsKeyArn(resolveKmsKeyArn(textOrNull(request, "kmsKeyId"), region));
guardrail.setUpdatedAt(Instant.now());
applyPolicies(guardrail, request, region);
guardrails.put(storageKey(region, guardrail.getGuardrailId(), DRAFT_VERSION), guardrail);
LOG.infov("Updated Bedrock guardrail: {0}", guardrail.getGuardrailId());
return guardrail;
}
/**
* Deletes one numerical version, or the whole guardrail when no version is given.
* {@code guardrailVersion} is a {@code GuardrailNumericalVersion} in the AWS model,
* so DRAFT cannot be deleted on its own.
*/
public void deleteGuardrail(String identifier, String version, String region) {
String guardrailId = resolveGuardrailId(identifier);
if (version != null && !version.isBlank()) {
if (!NUMERICAL_VERSION_PATTERN.matcher(version).matches()) {
throw new AwsException("ValidationException",
"guardrailVersion must be a numerical version.", 400);
}
getGuardrail(guardrailId, version, region);
guardrails.delete(storageKey(region, guardrailId, version));
LOG.infov("Deleted Bedrock guardrail {0} version {1}", guardrailId, version);
return;
}
List<Guardrail> versions = versionsOf(guardrailId, region);
if (versions.isEmpty()) {
throw new AwsException("ResourceNotFoundException",
"Guardrail " + guardrailId + " does not exist.", 404);
}
for (Guardrail guardrail : versions) {
guardrails.delete(storageKey(region, guardrailId, guardrail.getVersion()));
}
LOG.infov("Deleted Bedrock guardrail: {0}", guardrailId);
}
/**
* With no identifier, lists the DRAFT of every guardrail. With an identifier,
* lists every version of that guardrail, which is what the AWS model documents.
*/
public PaginatedResult<Guardrail> listGuardrails(String identifier, Integer maxResults,
String nextToken, String region) {
List<Guardrail> matches;
if (identifier == null || identifier.isBlank()) {
matches = draftsIn(region);
} else {
String guardrailId = resolveGuardrailId(identifier);
matches = versionsOf(guardrailId, region);
if (matches.isEmpty()) {
throw new AwsException("ResourceNotFoundException",
"Guardrail " + guardrailId + " does not exist.", 404);
}
}
return Pagination.paginate(matches, BedrockService::listCursor, maxResults, nextToken,
MAX_PAGE, "ValidationException");
}
public Guardrail createGuardrailVersion(String identifier, String description, String region) {
Guardrail draft = getGuardrail(identifier, DRAFT_VERSION, region);
String guardrailId = draft.getGuardrailId();
String version = String.valueOf(nextVersionNumber(guardrailId, region));
Guardrail snapshot = copyOf(draft);
snapshot.setVersion(version);
if (description != null) {
snapshot.setDescription(description);
}
snapshot.setUpdatedAt(Instant.now());
guardrails.put(storageKey(region, guardrailId, version), snapshot);
LOG.infov("Created Bedrock guardrail {0} version {1}", guardrailId, version);
return snapshot;
}
// Tags
public Map<String, String> listTags(String resourceArn, String region) {
Guardrail guardrail = findByArn(resourceArn, region);
return guardrail.getTags() != null ? guardrail.getTags() : Map.of();
}
/**
* The 50 tag limit applies to the resource, not to the request, so it is checked against the
* total the resource is left holding once the incoming tags are merged in. A tag that replaces
* the value of a key already present does not add to that total.
*/
public synchronized void tagResource(String resourceArn, Map<String, String> tags, String region) {
Guardrail guardrail = findByArn(resourceArn, region);
Map<String, String> merged = guardrail.getTags() == null
? new HashMap<>()
: new HashMap<>(guardrail.getTags());
merged.putAll(tags);
if (merged.size() > TAGS_PER_RESOURCE_MAX) {
throw tooManyTags(guardrail.getGuardrailArn(), merged.size());
}
guardrail.setTags(merged);
guardrails.put(storageKey(region, guardrail.getGuardrailId(), DRAFT_VERSION), guardrail);
}
public synchronized void untagResource(String resourceArn, List<String> tagKeys, String region) {
Guardrail guardrail = findByArn(resourceArn, region);
if (guardrail.getTags() != null && tagKeys != null) {
tagKeys.forEach(guardrail.getTags()::remove);
}
guardrails.put(storageKey(region, guardrail.getGuardrailId(), DRAFT_VERSION), guardrail);
}
// Helpers
private void applyPolicies(Guardrail guardrail, JsonNode request, String region) {
guardrail.setTopicPolicy(renamePolicy(request.get("topicPolicyConfig")));
guardrail.setContentPolicy(renamePolicy(request.get("contentPolicyConfig")));
guardrail.setWordPolicy(renamePolicy(request.get("wordPolicyConfig")));
guardrail.setSensitiveInformationPolicy(renamePolicy(request.get("sensitiveInformationPolicyConfig")));
guardrail.setContextualGroundingPolicy(renamePolicy(request.get("contextualGroundingPolicyConfig")));
guardrail.setAutomatedReasoningPolicy(renamePolicy(request.get("automatedReasoningPolicyConfig")));
guardrail.setCrossRegionDetails(crossRegionDetails(request.get("crossRegionConfig"), region));
}
private JsonNode renamePolicy(JsonNode policyConfig) {
if (policyConfig == null || !policyConfig.isObject()) {
return null;
}
ObjectNode policy = objectMapper.createObjectNode();
policyConfig.properties().forEach(entry ->
policy.set(POLICY_MEMBER_RENAMES.getOrDefault(entry.getKey(), entry.getKey()), entry.getValue()));
return policy;
}
private JsonNode crossRegionDetails(JsonNode crossRegionConfig, String region) {
if (crossRegionConfig == null || !crossRegionConfig.isObject()) {
return null;
}
JsonNode identifier = crossRegionConfig.get("guardrailProfileIdentifier");
if (identifier == null || identifier.isNull()) {
return null;
}
String value = identifier.asText();
String profileId = value.startsWith("arn:")
? value.substring(value.lastIndexOf('/') + 1)
: value;
ObjectNode details = objectMapper.createObjectNode();
details.put("guardrailProfileId", profileId);
details.put("guardrailProfileArn",
regionResolver.buildArn("bedrock", region, "guardrail-profile/" + profileId));
return details;
}
private Guardrail copyOf(Guardrail source) {
Guardrail copy = new Guardrail();
copy.setGuardrailId(source.getGuardrailId());
copy.setGuardrailArn(source.getGuardrailArn());
copy.setName(source.getName());
copy.setDescription(source.getDescription());
copy.setBlockedInputMessaging(source.getBlockedInputMessaging());
copy.setBlockedOutputsMessaging(source.getBlockedOutputsMessaging());
copy.setKmsKeyArn(source.getKmsKeyArn());
copy.setCreatedAt(source.getCreatedAt());
copy.setUpdatedAt(source.getUpdatedAt());
copy.setTags(source.getTags() != null ? new HashMap<>(source.getTags()) : new HashMap<>());
copy.setAccountId(source.getAccountId());
copy.setTopicPolicy(source.getTopicPolicy());
copy.setContentPolicy(source.getContentPolicy());
copy.setWordPolicy(source.getWordPolicy());
copy.setSensitiveInformationPolicy(source.getSensitiveInformationPolicy());
copy.setContextualGroundingPolicy(source.getContextualGroundingPolicy());
copy.setAutomatedReasoningPolicy(source.getAutomatedReasoningPolicy());
copy.setCrossRegionDetails(source.getCrossRegionDetails());
return copy;
}
private int nextVersionNumber(String guardrailId, String region) {
int highest = 0;
for (Guardrail guardrail : versionsOf(guardrailId, region)) {
if (DRAFT_VERSION.equals(guardrail.getVersion())) {
continue;
}
try {
highest = Math.max(highest, Integer.parseInt(guardrail.getVersion()));
} catch (NumberFormatException e) {
LOG.debugv("Ignoring non-numerical guardrail version {0} on {1}: {2}",
guardrail.getVersion(), guardrailId, e.getMessage());
}
}
return highest + 1;
}
private List<Guardrail> versionsOf(String guardrailId, String region) {
String prefix = region + "::" + guardrailId + "::";
List<Guardrail> versions = new ArrayList<>(guardrails.scan(key -> key.startsWith(prefix)));
versions.sort(Comparator.comparing(Guardrail::getVersion));
return versions;
}
private List<Guardrail> draftsIn(String region) {
String prefix = region + "::";
String suffix = "::" + DRAFT_VERSION;
return guardrails.scan(key -> key.startsWith(prefix) && key.endsWith(suffix));
}
/**
* Pagination cursor. DRAFT sorts after the numerical versions of the same guardrail
* because the padded numbers never reach the letter range.
*/
private static String listCursor(Guardrail guardrail) {
String version = guardrail.getVersion();
String sortableVersion = NUMERICAL_VERSION_PATTERN.matcher(version).matches()
? String.format(Locale.ROOT, "%08d", Integer.parseInt(version))
: version;
return guardrail.getGuardrailId() + "::" + sortableVersion;
}
private Guardrail findByArn(String resourceArn, String region) {
if (resourceArn == null || resourceArn.isBlank()) {
throw new AwsException("ValidationException", "resourceARN is required", 400);
}
String guardrailId = resolveGuardrailId(resourceArn);
return guardrails.get(storageKey(region, guardrailId, DRAFT_VERSION))
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
"Resource " + resourceArn + " does not exist.", 404));
}
private String resolveGuardrailId(String identifier) {
if (identifier == null || identifier.isBlank()) {
throw new AwsException("ValidationException", "guardrailIdentifier is required", 400);
}
if (!identifier.startsWith("arn:")) {
return identifier;
}
String resource;
try {
resource = AwsArnUtils.parse(identifier).resource();
} catch (IllegalArgumentException e) {
throw new AwsException("ValidationException",
"Invalid guardrail identifier: " + identifier, 400);
}
int slash = resource.indexOf('/');
if (slash < 0 || slash == resource.length() - 1) {
throw new AwsException("ValidationException",
"Invalid guardrail identifier: " + identifier, 400);
}
return resource.substring(slash + 1);
}
private String storageKey(String region, String guardrailId, String version) {
return region + "::" + guardrailId + "::" + version;
}
private String newGuardrailId() {
return UUID.randomUUID().toString().replace("-", "").substring(0, 12).toLowerCase(Locale.ROOT);
}
private String requiredName(JsonNode request) {
String name = requiredText(request, "name");
if (!NAME_PATTERN.matcher(name).matches()) {
throw new AwsException("ValidationException",
"name must match [0-9a-zA-Z-_]+ and be at most 50 characters.", 400);
}
return name;
}
/**
* {@code description} is optional, but the AWS model gives it a 1 to 200 character
* {@code GuardrailDescription} shape, so an over-long or empty value is rejected.
*/
private String boundedDescription(JsonNode request) {
String description = textOrNull(request, "description");
if (description == null) {
return null;
}
return bounded(description, "description", DESCRIPTION_MAX);
}
private String requiredBlockedMessaging(JsonNode request, String field) {
return bounded(requiredText(request, field), field, BLOCKED_MESSAGING_MAX);
}
private String bounded(String value, String field, int max) {
if (value.isEmpty() || value.length() > max) {
throw new AwsException("ValidationException",
field + " must be between 1 and " + max + " characters.", 400);
}
return value;
}
/**
* {@code kmsKeyId} on the request is a {@code KmsKeyId}: a key id, a key ARN, an alias name
* or an alias ARN. {@code kmsKeyArn} on the read shapes is a {@code KmsKeyArn}, which is only
* ever the full key ARN, so every accepted form resolves through KMS to that one shape.
*/
private String resolveKmsKeyArn(String kmsKeyId, String region) {
if (kmsKeyId == null || kmsKeyId.isBlank()) {
return null;
}
if (kmsService == null) {
throw new IllegalStateException("BedrockService was built without a KmsService; "
+ "a kmsKeyId cannot be resolved");
}
KmsKey key;
try {
key = kmsService.describeKey(kmsKeyId, region);
} catch (AwsException e) {
LOG.debugv("Rejecting Bedrock guardrail kmsKeyId {0}: {1}", kmsKeyId, e.getMessage());
throw kmsKeyNotUsable(kmsKeyId);
}
if (!key.isEnabled() || "PendingDeletion".equals(key.getKeyState())) {
throw kmsKeyNotUsable(kmsKeyId);
}
return key.getArn();
}
private static AwsException kmsKeyNotUsable(String kmsKeyId) {
return new AwsException("ValidationException", "The KMS key " + kmsKeyId
+ " does not exist, is not enabled, or cannot be used.", 400);
}
private String requiredText(JsonNode request, String field) {
String value = textOrNull(request, field);
if (value == null || value.isBlank()) {
throw new AwsException("ValidationException", field + " is required", 400);
}
return value;
}
private String textOrNull(JsonNode request, String field) {
JsonNode value = request.get(field);
if (value == null || value.isNull()) {
return null;
}
return value.asText();
}
/**
* Reads a {@code TagList}. Shared with the controller so that {@code CreateGuardrail} and
* {@code TagResource}, which both declare that shape, apply the same item cap.
*/
static Map<String, String> parseTagList(JsonNode tagsNode) {
Map<String, String> tags = new HashMap<>();
if (tagsNode == null || !tagsNode.isArray()) {
return tags;
}
if (tagsNode.size() > TAG_LIST_MAX) {
throw new AwsException("ValidationException",
"tags must have at most " + TAG_LIST_MAX + " items.", 400);
}
for (JsonNode tag : tagsNode) {
JsonNode key = tag.get("key");
JsonNode value = tag.get("value");
if (key != null && !key.isNull() && value != null && !value.isNull()) {
tags.put(key.asText(), value.asText());
}
}
return tags;
}
private static AwsException tooManyTags(String resourceArn, int total) {
return new AwsException("TooManyTagsException",
"Resource " + resourceArn + " would hold " + total + " tags, over the limit of "
+ TAGS_PER_RESOURCE_MAX + " tags per resource.",
400, Map.<String, Object>of("resourceName", resourceArn));
}
}
@@ -0,0 +1,184 @@
package io.github.hectorvent.floci.services.bedrock.model;
import com.fasterxml.jackson.databind.JsonNode;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
import java.util.Map;
@RegisterForReflection
public class Guardrail {
private String guardrailId;
private String guardrailArn;
private String name;
private String description;
private String version;
private String blockedInputMessaging;
private String blockedOutputsMessaging;
private String kmsKeyArn;
private Instant createdAt;
private Instant updatedAt;
private Map<String, String> tags;
private String accountId;
private JsonNode topicPolicy;
private JsonNode contentPolicy;
private JsonNode wordPolicy;
private JsonNode sensitiveInformationPolicy;
private JsonNode contextualGroundingPolicy;
private JsonNode automatedReasoningPolicy;
private JsonNode crossRegionDetails;
public String getGuardrailId() {
return guardrailId;
}
public void setGuardrailId(String guardrailId) {
this.guardrailId = guardrailId;
}
public String getGuardrailArn() {
return guardrailArn;
}
public void setGuardrailArn(String guardrailArn) {
this.guardrailArn = guardrailArn;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getBlockedInputMessaging() {
return blockedInputMessaging;
}
public void setBlockedInputMessaging(String blockedInputMessaging) {
this.blockedInputMessaging = blockedInputMessaging;
}
public String getBlockedOutputsMessaging() {
return blockedOutputsMessaging;
}
public void setBlockedOutputsMessaging(String blockedOutputsMessaging) {
this.blockedOutputsMessaging = blockedOutputsMessaging;
}
public String getKmsKeyArn() {
return kmsKeyArn;
}
public void setKmsKeyArn(String kmsKeyArn) {
this.kmsKeyArn = kmsKeyArn;
}
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<String, String> getTags() {
return tags;
}
public void setTags(Map<String, String> tags) {
this.tags = tags;
}
public String getAccountId() {
return accountId;
}
public void setAccountId(String accountId) {
this.accountId = accountId;
}
public JsonNode getTopicPolicy() {
return topicPolicy;
}
public void setTopicPolicy(JsonNode topicPolicy) {
this.topicPolicy = topicPolicy;
}
public JsonNode getContentPolicy() {
return contentPolicy;
}
public void setContentPolicy(JsonNode contentPolicy) {
this.contentPolicy = contentPolicy;
}
public JsonNode getWordPolicy() {
return wordPolicy;
}
public void setWordPolicy(JsonNode wordPolicy) {
this.wordPolicy = wordPolicy;
}
public JsonNode getSensitiveInformationPolicy() {
return sensitiveInformationPolicy;
}
public void setSensitiveInformationPolicy(JsonNode sensitiveInformationPolicy) {
this.sensitiveInformationPolicy = sensitiveInformationPolicy;
}
public JsonNode getContextualGroundingPolicy() {
return contextualGroundingPolicy;
}
public void setContextualGroundingPolicy(JsonNode contextualGroundingPolicy) {
this.contextualGroundingPolicy = contextualGroundingPolicy;
}
public JsonNode getAutomatedReasoningPolicy() {
return automatedReasoningPolicy;
}
public void setAutomatedReasoningPolicy(JsonNode automatedReasoningPolicy) {
this.automatedReasoningPolicy = automatedReasoningPolicy;
}
public JsonNode getCrossRegionDetails() {
return crossRegionDetails;
}
public void setCrossRegionDetails(JsonNode crossRegionDetails) {
this.crossRegionDetails = crossRegionDetails;
}
}
+2
View File
@@ -513,6 +513,8 @@ floci:
# endpoint: unset by default — Floci derives the sidecar's callback address automatically.
# Set an absolute http:// or https:// URL here only to override that derivation.
insecure-skip-tls-verify: false
bedrock:
enabled: true
bedrock-runtime:
enabled: true
backend: stub
@@ -0,0 +1,552 @@
package io.github.hectorvent.floci.services.bedrock;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class BedrockIntegrationTest {
private static String guardrailId;
private static String guardrailArn;
private static String guardrailVersion;
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
@Order(1)
void createGuardrail() {
var response = given()
.contentType("application/json")
.body("""
{
"name": "integration-guardrail",
"description": "blocks the loud stuff",
"blockedInputMessaging": "input blocked",
"blockedOutputsMessaging": "output blocked",
"topicPolicyConfig": {
"topicsConfig": [
{"name": "Investments", "definition": "Investment advice", "type": "DENY"}
]
},
"contentPolicyConfig": {
"filtersConfig": [
{"type": "HATE", "inputStrength": "HIGH", "outputStrength": "HIGH"}
]
},
"wordPolicyConfig": {
"wordsConfig": [{"text": "forbidden"}],
"managedWordListsConfig": [{"type": "PROFANITY"}]
},
"sensitiveInformationPolicyConfig": {
"piiEntitiesConfig": [{"type": "EMAIL", "action": "BLOCK"}]
},
"tags": [{"key": "team", "value": "ai"}]
}
""")
.when()
.post("/guardrails")
.then()
.statusCode(202)
.body("guardrailId", notNullValue())
.body("guardrailArn", containsString(":bedrock:"))
.body("guardrailArn", containsString(":guardrail/"))
.body("version", equalTo("DRAFT"))
.body("createdAt", notNullValue())
.extract();
guardrailId = response.path("guardrailId");
guardrailArn = response.path("guardrailArn");
}
@Test
@Order(2)
void getGuardrailReturnsReadyAndEchoesRequest() {
given()
.when()
.get("/guardrails/" + guardrailId)
.then()
.statusCode(200)
.body("guardrailId", equalTo(guardrailId))
.body("guardrailArn", equalTo(guardrailArn))
.body("name", equalTo("integration-guardrail"))
.body("description", equalTo("blocks the loud stuff"))
.body("version", equalTo("DRAFT"))
.body("status", equalTo("READY"))
.body("blockedInputMessaging", equalTo("input blocked"))
.body("blockedOutputsMessaging", equalTo("output blocked"))
.body("topicPolicy.topics[0].name", equalTo("Investments"))
.body("topicPolicy.topics[0].type", equalTo("DENY"))
.body("contentPolicy.filters[0].type", equalTo("HATE"))
.body("contentPolicy.filters[0].inputStrength", equalTo("HIGH"))
.body("wordPolicy.words[0].text", equalTo("forbidden"))
.body("wordPolicy.managedWordLists[0].type", equalTo("PROFANITY"))
.body("sensitiveInformationPolicy.piiEntities[0].type", equalTo("EMAIL"))
.body("createdAt", notNullValue())
.body("updatedAt", notNullValue());
}
@Test
@Order(3)
void getGuardrailByArnResolvesTheSameResource() {
String encodedArn = java.net.URLEncoder.encode(guardrailArn, java.nio.charset.StandardCharsets.UTF_8);
given()
.urlEncodingEnabled(false)
.when()
.get("/guardrails/" + encodedArn)
.then()
.statusCode(200)
.body("guardrailId", equalTo(guardrailId))
.body("status", equalTo("READY"));
}
@Test
@Order(4)
void listGuardrailsIncludesTheDraft() {
given()
.when()
.get("/guardrails")
.then()
.statusCode(200)
.body("guardrails.id", hasItem(guardrailId))
.body("guardrails.find { it.id == '" + guardrailId + "' }.status", equalTo("READY"))
.body("guardrails.find { it.id == '" + guardrailId + "' }.version", equalTo("DRAFT"))
.body("guardrails.find { it.id == '" + guardrailId + "' }.arn", equalTo(guardrailArn));
}
@Test
@Order(5)
void listTagsForGuardrail() {
given()
.contentType("application/json")
.body("{\"resourceARN\": \"" + guardrailArn + "\"}")
.when()
.post("/listTagsForResource")
.then()
.statusCode(200)
.body("tags.find { it.key == 'team' }.value", equalTo("ai"));
}
@Test
@Order(6)
void tagAndUntagGuardrail() {
given()
.contentType("application/json")
.body("{\"resourceARN\": \"" + guardrailArn + "\", \"tags\": [{\"key\": \"env\", \"value\": \"test\"}]}")
.when()
.post("/tagResource")
.then()
.statusCode(200);
given()
.contentType("application/json")
.body("{\"resourceARN\": \"" + guardrailArn + "\"}")
.when()
.post("/listTagsForResource")
.then()
.statusCode(200)
.body("tags.find { it.key == 'env' }.value", equalTo("test"));
given()
.contentType("application/json")
.body("{\"resourceARN\": \"" + guardrailArn + "\", \"tagKeys\": [\"env\"]}")
.when()
.post("/untagResource")
.then()
.statusCode(200);
given()
.contentType("application/json")
.body("{\"resourceARN\": \"" + guardrailArn + "\"}")
.when()
.post("/listTagsForResource")
.then()
.statusCode(200)
.body("tags.find { it.key == 'env' }", nullValue())
.body("tags.find { it.key == 'team' }.value", equalTo("ai"));
}
@Test
@Order(7)
void updateGuardrail() {
given()
.contentType("application/json")
.body("""
{
"name": "integration-guardrail",
"description": "now with fewer topics",
"blockedInputMessaging": "input blocked v2",
"blockedOutputsMessaging": "output blocked v2",
"contentPolicyConfig": {
"filtersConfig": [
{"type": "VIOLENCE", "inputStrength": "MEDIUM", "outputStrength": "LOW"}
]
}
}
""")
.when()
.put("/guardrails/" + guardrailId)
.then()
.statusCode(202)
.body("guardrailId", equalTo(guardrailId))
.body("guardrailArn", equalTo(guardrailArn))
.body("version", equalTo("DRAFT"))
.body("updatedAt", notNullValue());
given()
.when()
.get("/guardrails/" + guardrailId)
.then()
.statusCode(200)
.body("description", equalTo("now with fewer topics"))
.body("blockedInputMessaging", equalTo("input blocked v2"))
.body("contentPolicy.filters[0].type", equalTo("VIOLENCE"))
.body("topicPolicy", nullValue())
.body("status", equalTo("READY"));
}
@Test
@Order(8)
void createGuardrailVersion() {
guardrailVersion = given()
.contentType("application/json")
.body("{\"description\": \"first cut\"}")
.when()
.post("/guardrails/" + guardrailId)
.then()
.statusCode(202)
.body("guardrailId", equalTo(guardrailId))
.body("version", equalTo("1"))
.extract().path("version");
given()
.queryParam("guardrailVersion", guardrailVersion)
.when()
.get("/guardrails/" + guardrailId)
.then()
.statusCode(200)
.body("version", equalTo("1"))
.body("status", equalTo("READY"))
.body("description", equalTo("first cut"))
.body("contentPolicy.filters[0].type", equalTo("VIOLENCE"));
}
@Test
@Order(9)
void listGuardrailsByIdentifierReturnsEveryVersion() {
given()
.queryParam("guardrailIdentifier", guardrailId)
.when()
.get("/guardrails")
.then()
.statusCode(200)
.body("guardrails.version", hasItem("DRAFT"))
.body("guardrails.version", hasItem("1"));
}
@Test
@Order(10)
void listGuardrailsHonoursMaxResultsAndNextToken() {
String token = given()
.queryParam("guardrailIdentifier", guardrailId)
.queryParam("maxResults", 1)
.when()
.get("/guardrails")
.then()
.statusCode(200)
.body("guardrails.size()", equalTo(1))
.body("guardrails[0].version", equalTo("1"))
.body("nextToken", notNullValue())
.extract().path("nextToken");
given()
.queryParam("guardrailIdentifier", guardrailId)
.queryParam("maxResults", 1)
.queryParam("nextToken", token)
.when()
.get("/guardrails")
.then()
.statusCode(200)
.body("guardrails.size()", equalTo(1))
.body("guardrails[0].version", equalTo("DRAFT"))
.body("nextToken", nullValue());
}
@Test
@Order(11)
void deletingTheDraftVersionReturnsValidationException() {
given()
.queryParam("guardrailVersion", "DRAFT")
.when()
.delete("/guardrails/" + guardrailId)
.then()
.statusCode(400)
.body("__type", equalTo("ValidationException"));
}
@Test
@Order(12)
void getMissingGuardrailReturnsResourceNotFound() {
given()
.when()
.get("/guardrails/doesnotexist1")
.then()
.statusCode(404)
.body("__type", equalTo("ResourceNotFoundException"));
}
@Test
@Order(13)
void duplicateNameReturnsConflict() {
given()
.contentType("application/json")
.body("""
{
"name": "integration-guardrail",
"blockedInputMessaging": "input blocked",
"blockedOutputsMessaging": "output blocked"
}
""")
.when()
.post("/guardrails")
.then()
.statusCode(400)
.body("__type", equalTo("ConflictException"));
}
@Test
@Order(14)
void createWithoutRequiredMessagingReturnsValidationException() {
given()
.contentType("application/json")
.body("{\"name\": \"missing-messaging\"}")
.when()
.post("/guardrails")
.then()
.statusCode(400)
.body("__type", equalTo("ValidationException"));
}
@Test
@Order(15)
void deleteSingleVersionLeavesTheDraft() {
given()
.queryParam("guardrailVersion", "1")
.when()
.delete("/guardrails/" + guardrailId)
.then()
.statusCode(202);
given()
.queryParam("guardrailVersion", "1")
.when()
.get("/guardrails/" + guardrailId)
.then()
.statusCode(404)
.body("__type", equalTo("ResourceNotFoundException"));
given()
.when()
.get("/guardrails/" + guardrailId)
.then()
.statusCode(200)
.body("version", equalTo("DRAFT"));
}
@Test
@Order(16)
void deleteGuardrail() {
given()
.when()
.delete("/guardrails/" + guardrailId)
.then()
.statusCode(202);
given()
.when()
.get("/guardrails/" + guardrailId)
.then()
.statusCode(404)
.body("__type", equalTo("ResourceNotFoundException"));
}
@Test
@Order(17)
void deleteMissingGuardrailReturnsResourceNotFound() {
given()
.when()
.delete("/guardrails/" + guardrailId)
.then()
.statusCode(404)
.body("__type", equalTo("ResourceNotFoundException"));
}
@Test
@Order(18)
void createRejectsAnOverLongDescriptionAndBlockedMessaging() {
given()
.contentType("application/json")
.body("{\"name\": \"over-long-description\","
+ " \"description\": \"" + "d".repeat(201) + "\","
+ " \"blockedInputMessaging\": \"in\","
+ " \"blockedOutputsMessaging\": \"out\"}")
.when()
.post("/guardrails")
.then()
.statusCode(400)
.body("__type", equalTo("ValidationException"));
given()
.contentType("application/json")
.body("{\"name\": \"over-long-messaging\","
+ " \"blockedInputMessaging\": \"" + "i".repeat(501) + "\","
+ " \"blockedOutputsMessaging\": \"out\"}")
.when()
.post("/guardrails")
.then()
.statusCode(400)
.body("__type", equalTo("ValidationException"));
}
@Test
@Order(19)
void kmsKeyIdIsReadBackAsAFullKeyArn() {
String keyId = given()
.header("X-Amz-Target", "TrentService.CreateKey")
.contentType("application/x-amz-json-1.1")
.body("{\"Description\": \"bedrock-guardrail-key\"}")
.when()
.post("/")
.then()
.statusCode(200)
.extract().path("KeyMetadata.KeyId");
given()
.header("X-Amz-Target", "TrentService.CreateAlias")
.contentType("application/x-amz-json-1.1")
.body("{\"AliasName\": \"alias/bedrock-guardrails\", \"TargetKeyId\": \"" + keyId + "\"}")
.when()
.post("/")
.then()
.statusCode(200);
String expectedArn = "arn:aws:kms:us-east-1:000000000000:key/" + keyId;
// A bare key id, an alias and a full ARN all land on the one KmsKeyArn shape
// that the GetGuardrail response model declares.
for (String submitted : new String[] {keyId, "alias/bedrock-guardrails", expectedArn}) {
String id = given()
.contentType("application/json")
.body("{\"name\": \"kms-" + submitted.hashCode() + "\","
+ " \"blockedInputMessaging\": \"in\","
+ " \"blockedOutputsMessaging\": \"out\","
+ " \"kmsKeyId\": \"" + submitted + "\"}")
.when()
.post("/guardrails")
.then()
.statusCode(202)
.extract().path("guardrailId");
given()
.when()
.get("/guardrails/" + id)
.then()
.statusCode(200)
.body("kmsKeyArn", equalTo(expectedArn));
}
}
@Test
@Order(20)
void createRejectsAKmsKeyThatDoesNotExist() {
given()
.contentType("application/json")
.body("""
{
"name": "kms-unknown",
"blockedInputMessaging": "in",
"blockedOutputsMessaging": "out",
"kmsKeyId": "alias/does-not-exist"
}
""")
.when()
.post("/guardrails")
.then()
.statusCode(400)
.body("__type", equalTo("ValidationException"));
}
@Test
@Order(21)
void createRejectsATagListOverTheModelItemCap() {
given()
.contentType("application/json")
.body("{\"name\": \"tags-over-item-cap\","
+ " \"blockedInputMessaging\": \"in\","
+ " \"blockedOutputsMessaging\": \"out\","
+ " \"tags\": " + tagListJson("key-", 201) + "}")
.when()
.post("/guardrails")
.then()
.statusCode(400)
.body("__type", equalTo("ValidationException"));
}
@Test
@Order(22)
void tagResourceRejectsMoreTagsThanOneResourceMayHold() {
String arn = given()
.contentType("application/json")
.body("{\"name\": \"tags-per-resource\","
+ " \"blockedInputMessaging\": \"in\","
+ " \"blockedOutputsMessaging\": \"out\"}")
.when()
.post("/guardrails")
.then()
.statusCode(202)
.extract().path("guardrailArn");
given()
.contentType("application/json")
.body("{\"resourceARN\": \"" + arn + "\", \"tags\": " + tagListJson("key-", 50) + "}")
.when()
.post("/tagResource")
.then()
.statusCode(200);
given()
.contentType("application/json")
.body("{\"resourceARN\": \"" + arn + "\", \"tags\": [{\"key\": \"one-too-many\", \"value\": \"x\"}]}")
.when()
.post("/tagResource")
.then()
.statusCode(400)
.body("__type", equalTo("TooManyTagsException"))
.body("resourceName", equalTo(arn));
}
private static String tagListJson(String prefix, int count) {
StringBuilder json = new StringBuilder("[");
for (int i = 0; i < count; i++) {
if (i > 0) {
json.append(',');
}
json.append("{\"key\": \"").append(prefix).append(i).append("\", \"value\": \"v").append(i).append("\"}");
}
return json.append(']').toString();
}
}
@@ -0,0 +1,542 @@
package io.github.hectorvent.floci.services.bedrock;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.PaginatedResult;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.bedrock.model.Guardrail;
import io.github.hectorvent.floci.services.kms.KmsService;
import io.github.hectorvent.floci.services.kms.model.KmsKey;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
class BedrockServiceTest {
private static final String REGION = "us-east-1";
private static final String ACCOUNT = "000000000000";
private static final String KEY_ID = "8f2b1c4e-0a7d-4e5f-9b31-6c8d2e4f7a90";
private static final String KEY_ARN = "arn:aws:kms:" + REGION + ":" + ACCOUNT + ":key/" + KEY_ID;
private final ObjectMapper mapper = new ObjectMapper();
private KmsService kmsService;
private BedrockService service;
@BeforeEach
void setUp() {
kmsService = mock(KmsService.class);
service = new BedrockService(new InMemoryStorage<>(),
new RegionResolver(REGION, ACCOUNT), mapper, kmsService);
}
/** Registers one usable KMS key that answers to every form the AWS model accepts. */
private void knownKey(String... forms) {
KmsKey key = new KmsKey();
key.setKeyId(KEY_ID);
key.setArn(KEY_ARN);
key.setEnabled(true);
key.setKeyState("Enabled");
for (String form : forms) {
doReturn(key).when(kmsService).describeKey(form, REGION);
}
}
private ObjectNode createRequest(String name) {
ObjectNode request = mapper.createObjectNode();
request.put("name", name);
request.put("blockedInputMessaging", "input blocked");
request.put("blockedOutputsMessaging", "output blocked");
return request;
}
private Guardrail create(String name) {
return service.createGuardrail(createRequest(name), REGION);
}
@Test
void createProducesADraftWithAModelShapedIdAndArn() {
Guardrail guardrail = create("my-guardrail");
assertTrue(guardrail.getGuardrailId().matches("[a-z0-9]+"), guardrail.getGuardrailId());
assertEquals(BedrockService.DRAFT_VERSION, guardrail.getVersion());
assertEquals("arn:aws:bedrock:" + REGION + ":" + ACCOUNT + ":guardrail/" + guardrail.getGuardrailId(),
guardrail.getGuardrailArn());
assertNotNull(guardrail.getCreatedAt());
assertEquals(guardrail.getCreatedAt(), guardrail.getUpdatedAt());
}
@Test
void createRenamesPolicyConfigMembersToTheirReadShapes() {
ObjectNode request = createRequest("policies");
request.putObject("topicPolicyConfig").putArray("topicsConfig").addObject()
.put("name", "Investments").put("type", "DENY");
request.putObject("contentPolicyConfig").putArray("filtersConfig").addObject()
.put("type", "HATE").put("inputStrength", "HIGH");
request.putObject("wordPolicyConfig").putArray("wordsConfig").addObject().put("text", "forbidden");
request.putObject("sensitiveInformationPolicyConfig").putArray("piiEntitiesConfig").addObject()
.put("type", "EMAIL").put("action", "BLOCK");
Guardrail guardrail = service.createGuardrail(request, REGION);
assertEquals("Investments", guardrail.getTopicPolicy().path("topics").path(0).path("name").asText());
assertEquals("HATE", guardrail.getContentPolicy().path("filters").path(0).path("type").asText());
assertEquals("forbidden", guardrail.getWordPolicy().path("words").path(0).path("text").asText());
assertEquals("EMAIL",
guardrail.getSensitiveInformationPolicy().path("piiEntities").path(0).path("type").asText());
}
@Test
void createRejectsAnEmptyRequiredMember() {
ObjectNode request = mapper.createObjectNode();
request.put("name", "no-messaging");
AwsException error = assertThrows(AwsException.class,
() -> service.createGuardrail(request, REGION));
assertEquals("ValidationException", error.getErrorCode());
assertEquals(400, error.getHttpStatus());
}
@Test
void createRejectsANameOutsideTheModelPattern() {
AwsException error = assertThrows(AwsException.class, () -> create("not a valid name"));
assertEquals("ValidationException", error.getErrorCode());
}
@Test
void createRejectsADuplicateName() {
create("duplicate");
AwsException error = assertThrows(AwsException.class, () -> create("duplicate"));
assertEquals("ConflictException", error.getErrorCode());
assertEquals(400, error.getHttpStatus());
}
@Test
void getResolvesAnArnAsWellAsAnId() {
Guardrail created = create("by-arn");
Guardrail byArn = service.getGuardrail(created.getGuardrailArn(), null, REGION);
assertEquals(created.getGuardrailId(), byArn.getGuardrailId());
}
@Test
void getRejectsAMalformedIdentifier() {
AwsException error = assertThrows(AwsException.class,
() -> service.getGuardrail("arn:aws:bedrock", null, REGION));
assertEquals("ValidationException", error.getErrorCode());
}
@Test
void getMissingGuardrailRaisesResourceNotFound() {
AwsException error = assertThrows(AwsException.class,
() -> service.getGuardrail("doesnotexist", null, REGION));
assertEquals("ResourceNotFoundException", error.getErrorCode());
assertEquals(404, error.getHttpStatus());
}
@Test
void updateWritesTheDraftAndLeavesPublishedVersionsAlone() {
Guardrail created = create("versioned");
service.createGuardrailVersion(created.getGuardrailId(), "first cut", REGION);
ObjectNode update = createRequest("versioned");
update.put("description", "after the update");
service.updateGuardrail(created.getGuardrailId(), update, REGION);
assertEquals("after the update",
service.getGuardrail(created.getGuardrailId(), null, REGION).getDescription());
assertEquals("first cut",
service.getGuardrail(created.getGuardrailId(), "1", REGION).getDescription());
}
@Test
void versionsAreNumberedFromOne() {
Guardrail created = create("counting");
assertEquals("1", service.createGuardrailVersion(created.getGuardrailId(), null, REGION).getVersion());
assertEquals("2", service.createGuardrailVersion(created.getGuardrailId(), null, REGION).getVersion());
}
@Test
void listWithoutAnIdentifierReturnsOneDraftPerGuardrail() {
Guardrail first = create("first");
create("second");
service.createGuardrailVersion(first.getGuardrailId(), null, REGION);
List<Guardrail> listed = service.listGuardrails(null, null, null, REGION).items();
assertEquals(2, listed.size());
assertTrue(listed.stream().allMatch(g -> BedrockService.DRAFT_VERSION.equals(g.getVersion())));
}
@Test
void listWithAnIdentifierReturnsEveryVersion() {
Guardrail created = create("all-versions");
service.createGuardrailVersion(created.getGuardrailId(), null, REGION);
List<Guardrail> listed = service.listGuardrails(created.getGuardrailId(), null, null, REGION).items();
assertEquals(2, listed.size());
assertEquals(List.of("1", BedrockService.DRAFT_VERSION),
listed.stream().map(Guardrail::getVersion).toList());
}
@Test
void listPagesOnMaxResultsAndResumesFromTheToken() {
create("alpha");
create("beta");
create("gamma");
PaginatedResult<Guardrail> firstPage = service.listGuardrails(null, 2, null, REGION);
assertEquals(2, firstPage.items().size());
assertNotNull(firstPage.nextToken());
PaginatedResult<Guardrail> secondPage =
service.listGuardrails(null, 2, firstPage.nextToken(), REGION);
assertEquals(1, secondPage.items().size());
assertNull(secondPage.nextToken());
}
@Test
void listRejectsAMaxResultsOutsideTheModelRange() {
AwsException error = assertThrows(AwsException.class,
() -> service.listGuardrails(null, 0, null, REGION));
assertEquals("ValidationException", error.getErrorCode());
}
@Test
void deleteWithoutAVersionRemovesEveryVersion() {
Guardrail created = create("gone");
service.createGuardrailVersion(created.getGuardrailId(), null, REGION);
service.deleteGuardrail(created.getGuardrailId(), null, REGION);
assertThrows(AwsException.class, () -> service.getGuardrail(created.getGuardrailId(), null, REGION));
assertThrows(AwsException.class, () -> service.getGuardrail(created.getGuardrailId(), "1", REGION));
}
@Test
void deleteRejectsANonNumericalVersion() {
Guardrail created = create("draft-delete");
AwsException error = assertThrows(AwsException.class,
() -> service.deleteGuardrail(created.getGuardrailId(), BedrockService.DRAFT_VERSION, REGION));
assertEquals("ValidationException", error.getErrorCode());
}
@Test
void tagsRoundTripThroughTheArn() {
Guardrail created = create("tagged");
String arn = created.getGuardrailArn();
service.tagResource(arn, Map.of("team", "ai"), REGION);
service.tagResource(arn, Map.of("env", "test"), REGION);
assertEquals(Map.of("team", "ai", "env", "test"), service.listTags(arn, REGION));
service.untagResource(arn, List.of("env"), REGION);
assertEquals(Map.of("team", "ai"), service.listTags(arn, REGION));
}
@Test
void taggingAnUnknownResourceRaisesResourceNotFound() {
AwsException error = assertThrows(AwsException.class,
() -> service.listTags("arn:aws:bedrock:" + REGION + ":" + ACCOUNT + ":guardrail/missing", REGION));
assertEquals("ResourceNotFoundException", error.getErrorCode());
}
// Length constraints from the AWS model
@Test
void createAcceptsADescriptionExactlyAtTheModelCap() {
ObjectNode request = createRequest("description-at-cap");
request.put("description", "d".repeat(200));
assertEquals(200, service.createGuardrail(request, REGION).getDescription().length());
}
@Test
void createRejectsADescriptionOverTheModelCap() {
ObjectNode request = createRequest("description-over-cap");
request.put("description", "d".repeat(201));
AwsException error = assertThrows(AwsException.class,
() -> service.createGuardrail(request, REGION));
assertEquals("ValidationException", error.getErrorCode());
assertEquals(400, error.getHttpStatus());
assertTrue(error.getMessage().contains("description"), error.getMessage());
}
@Test
void createRejectsAnEmptyDescription() {
ObjectNode request = createRequest("empty-description");
request.put("description", "");
AwsException error = assertThrows(AwsException.class,
() -> service.createGuardrail(request, REGION));
assertEquals("ValidationException", error.getErrorCode());
}
@Test
void createAcceptsBlockedMessagingExactlyAtTheModelCap() {
ObjectNode request = createRequest("messaging-at-cap");
request.put("blockedInputMessaging", "i".repeat(500));
request.put("blockedOutputsMessaging", "o".repeat(500));
Guardrail guardrail = service.createGuardrail(request, REGION);
assertEquals(500, guardrail.getBlockedInputMessaging().length());
assertEquals(500, guardrail.getBlockedOutputsMessaging().length());
}
@Test
void createRejectsBlockedInputMessagingOverTheModelCap() {
ObjectNode request = createRequest("input-over-cap");
request.put("blockedInputMessaging", "i".repeat(501));
AwsException error = assertThrows(AwsException.class,
() -> service.createGuardrail(request, REGION));
assertEquals("ValidationException", error.getErrorCode());
assertTrue(error.getMessage().contains("blockedInputMessaging"), error.getMessage());
}
@Test
void createRejectsBlockedOutputsMessagingOverTheModelCap() {
ObjectNode request = createRequest("outputs-over-cap");
request.put("blockedOutputsMessaging", "o".repeat(501));
AwsException error = assertThrows(AwsException.class,
() -> service.createGuardrail(request, REGION));
assertEquals("ValidationException", error.getErrorCode());
assertTrue(error.getMessage().contains("blockedOutputsMessaging"), error.getMessage());
}
@Test
void createAcceptsANameExactlyAtTheModelCap() {
assertEquals(50, create("n".repeat(50)).getName().length());
}
@Test
void createRejectsANameOverTheModelCap() {
AwsException error = assertThrows(AwsException.class, () -> create("n".repeat(51)));
assertEquals("ValidationException", error.getErrorCode());
}
@Test
void updateEnforcesTheSameLengthCapsAsCreate() {
Guardrail created = create("update-caps");
ObjectNode request = createRequest("update-caps");
request.put("description", "d".repeat(201));
AwsException error = assertThrows(AwsException.class,
() -> service.updateGuardrail(created.getGuardrailId(), request, REGION));
assertEquals("ValidationException", error.getErrorCode());
ObjectNode overLong = createRequest("update-caps");
overLong.put("blockedOutputsMessaging", "o".repeat(501));
assertEquals("ValidationException", assertThrows(AwsException.class,
() -> service.updateGuardrail(created.getGuardrailId(), overLong, REGION)).getErrorCode());
}
// Tag limits from the AWS model
private ArrayNode tagArray(int count) {
ArrayNode tags = mapper.createArrayNode();
for (int i = 0; i < count; i++) {
ObjectNode tag = tags.addObject();
tag.put("key", "key-" + i);
tag.put("value", "value-" + i);
}
return tags;
}
private Map<String, String> tagMap(String prefix, int count) {
Map<String, String> tags = new HashMap<>();
for (int i = 0; i < count; i++) {
tags.put(prefix + i, "value-" + i);
}
return tags;
}
@Test
void parseTagListAcceptsATagListExactlyAtTheModelItemCap() {
assertEquals(200, BedrockService.parseTagList(tagArray(200)).size());
}
@Test
void parseTagListRejectsATagListOverTheModelItemCap() {
AwsException error = assertThrows(AwsException.class,
() -> BedrockService.parseTagList(tagArray(201)));
assertEquals("ValidationException", error.getErrorCode());
assertEquals(400, error.getHttpStatus());
assertTrue(error.getMessage().contains("200"), error.getMessage());
}
@Test
void createAcceptsTagsExactlyAtThePerResourceLimit() {
ObjectNode request = createRequest("tags-at-limit");
request.set("tags", tagArray(50));
assertEquals(50, service.createGuardrail(request, REGION).getTags().size());
}
@Test
void createRejectsMoreTagsThanOneResourceMayHold() {
ObjectNode request = createRequest("tags-over-limit");
request.set("tags", tagArray(51));
AwsException error = assertThrows(AwsException.class,
() -> service.createGuardrail(request, REGION));
assertEquals("TooManyTagsException", error.getErrorCode());
assertEquals(400, error.getHttpStatus());
assertNotNull(error.getExtendedData().get("resourceName"));
}
@Test
void createRejectsATagListOverTheModelItemCapBeforeTheResourceLimit() {
ObjectNode request = createRequest("tags-over-item-cap");
request.set("tags", tagArray(201));
assertEquals("ValidationException", assertThrows(AwsException.class,
() -> service.createGuardrail(request, REGION)).getErrorCode());
}
@Test
void tagResourceAcceptsTagsExactlyAtThePerResourceLimit() {
String arn = create("tagging-at-limit").getGuardrailArn();
service.tagResource(arn, tagMap("key-", 50), REGION);
assertEquals(50, service.listTags(arn, REGION).size());
}
@Test
void tagResourceRejectsMoreTagsThanOneResourceMayHold() {
Guardrail created = create("tagging-over-limit");
AwsException error = assertThrows(AwsException.class,
() -> service.tagResource(created.getGuardrailArn(), tagMap("key-", 51), REGION));
assertEquals("TooManyTagsException", error.getErrorCode());
assertEquals(400, error.getHttpStatus());
assertEquals(created.getGuardrailArn(), error.getExtendedData().get("resourceName"));
assertTrue(service.listTags(created.getGuardrailArn(), REGION).isEmpty());
}
@Test
void tagResourceCountsTheTotalLeftOnTheResourceAfterTheMerge() {
String arn = create("tagging-merge").getGuardrailArn();
service.tagResource(arn, tagMap("existing-", 40), REGION);
service.tagResource(arn, tagMap("added-", 10), REGION);
assertEquals(50, service.listTags(arn, REGION).size());
AwsException error = assertThrows(AwsException.class,
() -> service.tagResource(arn, Map.of("one-too-many", "x"), REGION));
assertEquals("TooManyTagsException", error.getErrorCode());
assertEquals(50, service.listTags(arn, REGION).size());
}
@Test
void tagResourceDoesNotCountAKeyItOnlyReplaces() {
String arn = create("tagging-replace").getGuardrailArn();
service.tagResource(arn, tagMap("key-", 50), REGION);
service.tagResource(arn, Map.of("key-0", "replaced"), REGION);
assertEquals(50, service.listTags(arn, REGION).size());
assertEquals("replaced", service.listTags(arn, REGION).get("key-0"));
}
// kmsKeyId normalisation
@Test
void createResolvesABareKeyIdToTheKeyArn() {
knownKey(KEY_ID);
ObjectNode request = createRequest("kms-by-id");
request.put("kmsKeyId", KEY_ID);
assertEquals(KEY_ARN, service.createGuardrail(request, REGION).getKmsKeyArn());
}
@Test
void createResolvesAnAliasToTheKeyArn() {
knownKey("alias/guardrails");
ObjectNode request = createRequest("kms-by-alias");
request.put("kmsKeyId", "alias/guardrails");
assertEquals(KEY_ARN, service.createGuardrail(request, REGION).getKmsKeyArn());
}
@Test
void createKeepsAFullKeyArn() {
knownKey(KEY_ARN);
ObjectNode request = createRequest("kms-by-arn");
request.put("kmsKeyId", KEY_ARN);
assertEquals(KEY_ARN, service.createGuardrail(request, REGION).getKmsKeyArn());
}
@Test
void createWithoutAKmsKeyLeavesTheArnUnset() {
assertNull(create("kms-absent").getKmsKeyArn());
}
@Test
void createRejectsAKmsKeyThatDoesNotResolve() {
doThrow(new AwsException("NotFoundException", "Key not found: missing", 404))
.when(kmsService).describeKey("missing", REGION);
ObjectNode request = createRequest("kms-missing");
request.put("kmsKeyId", "missing");
AwsException error = assertThrows(AwsException.class,
() -> service.createGuardrail(request, REGION));
assertEquals("ValidationException", error.getErrorCode());
assertEquals(400, error.getHttpStatus());
}
@Test
void createRejectsAKmsKeyPendingDeletion() {
KmsKey key = new KmsKey();
key.setKeyId(KEY_ID);
key.setArn(KEY_ARN);
key.setEnabled(false);
key.setKeyState("PendingDeletion");
doReturn(key).when(kmsService).describeKey(KEY_ID, REGION);
ObjectNode request = createRequest("kms-pending");
request.put("kmsKeyId", KEY_ID);
AwsException error = assertThrows(AwsException.class,
() -> service.createGuardrail(request, REGION));
assertEquals("ValidationException", error.getErrorCode());
}
@Test
void updateResolvesTheKeyAndTheVersionSnapshotKeepsIt() {
knownKey(KEY_ID, "alias/guardrails");
Guardrail created = create("kms-on-update");
ObjectNode request = createRequest("kms-on-update");
request.put("kmsKeyId", "alias/guardrails");
assertEquals(KEY_ARN, service.updateGuardrail(created.getGuardrailId(), request, REGION).getKmsKeyArn());
assertEquals(KEY_ARN,
service.createGuardrailVersion(created.getGuardrailId(), null, REGION).getKmsKeyArn());
}
@Test
void guardrailsAreScopedToTheirRegion() {
Guardrail created = create("regional");
assertThrows(AwsException.class,
() -> service.getGuardrail(created.getGuardrailId(), null, "eu-west-1"));
assertTrue(service.listGuardrails(null, null, null, "eu-west-1").items().isEmpty());
}
}
+2
View File
@@ -280,6 +280,8 @@ floci:
enabled: true
ui:
enabled: true
bedrock:
enabled: true
bedrock-runtime:
enabled: true
eks:
+4
View File
@@ -30,6 +30,10 @@ services:
doc: docs/services/athena.md
sources:
- { path: src/main/java/io/github/hectorvent/floci/services/athena/AthenaJsonHandler.java, mode: switch }
- service: bedrock
doc: docs/services/bedrock.md
sources:
- { path: src/main/java/io/github/hectorvent/floci/services/bedrock/BedrockController.java, mode: rest }
- service: bedrock-agentcore-control
doc: docs/services/bedrock-agentcore.md
sources: