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

@@ -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());
}
}