diff --git a/docs/services/bedrock.md b/docs/services/bedrock.md index 1c67471453..dedc9a3731 100644 --- a/docs/services/bedrock.md +++ b/docs/services/bedrock.md @@ -6,6 +6,21 @@ 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). +## Account-level guardrail configurations + +`PUT /enforcedGuardrailsConfiguration` creates a configuration, or replaces the +configuration named by `configId`. It references an existing numerical guardrail +version and records the caller identity. `GET /enforcedGuardrailsConfiguration` +returns one configuration per page, with an opaque `nextToken` when another page +exists. `DELETE /enforcedGuardrailsConfiguration/{configId}` removes it. + +Configuration storage is scoped to the calling account and Region. These are +control-plane records: inference-time enforcement is not implemented. Model ID +patterns, conflicts between multiple configurations in one Region, and cascading +deletion of a referenced guardrail version are not implemented. Deleting a referenced +guardrail version, or its whole guardrail, is rejected until callers remove or replace +every configuration that references it. + ## Supported Actions @@ -26,6 +41,9 @@ that shares the same signing name: see [Bedrock Runtime](bedrock-runtime.md). | `PutResourcePolicy` | Attach a resource-based policy to a guardrail or a guardrail profile (`POST /resource-policy`) | | `GetResourcePolicy` | Read the resource-based policy of a guardrail or a guardrail profile | | `DeleteResourcePolicy` | Remove the resource-based policy of a guardrail or a guardrail profile | +| `PutEnforcedGuardrailConfiguration` | Create or replace an account and Region configuration referencing a numerical guardrail version | +| `ListEnforcedGuardrailsConfiguration` | List the calling account and Region's configurations, one per page | +| `DeleteEnforcedGuardrailConfiguration` | Delete a configuration by its `configId` | | `TagResource` | Tag a guardrail or application inference profile (`POST /tagResource`) | | `UntagResource` | Remove tags from a guardrail or application inference profile (`POST /untagResource`) | | `ListTagsForResource` | List a guardrail's or application inference profile's tags (`POST /listTagsForResource`) | diff --git a/docs/services/index.md b/docs/services/index.md index 0d0dc16c03..da6c3d3448 100644 --- a/docs/services/index.md +++ b/docs/services/index.md @@ -119,7 +119,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac | [AppConfig](appconfig.md) | `/applications/...`, `/deploymentstrategies/...` | REST JSON | 29 | | [AppConfigData](appconfig.md#data-plane) | `/configurationsessions`, `/configuration` | REST JSON | 2 | | [AppSync](appsync.md) | `/v1/apis/...` | REST JSON | 58 | -| [Amazon Bedrock](bedrock.md) | `/guardrails`, `/guardrails/{guardrailIdentifier}`, `/foundation-models`, `/foundation-models/{modelIdentifier}`, `/inference-profiles`, `/inference-profiles/{inferenceProfileIdentifier}`, `/resource-policy`, `/resource-policy/{resourceArn}`, `/tagResource`, `/untagResource`, `/listTagsForResource` | REST JSON | 18 | +| [Amazon Bedrock](bedrock.md) | `/guardrails`, `/guardrails/{guardrailIdentifier}`, `/foundation-models`, `/foundation-models/{modelIdentifier}`, `/inference-profiles`, `/inference-profiles/{inferenceProfileIdentifier}`, `/resource-policy`, `/resource-policy/{resourceArn}`, `/tagResource`, `/untagResource`, `/listTagsForResource`, `/enforcedGuardrailsConfiguration`, `/enforcedGuardrailsConfiguration/{configId}` | REST JSON | 21 | | [Bedrock Runtime](bedrock-runtime.md) | `/model/{modelId}/converse`, `/model/{modelId}/converse-stream`, `/model/{modelId}/invoke` | REST JSON | 3 (`InvokeModelWithResponseStream` answers 501) | | [Bedrock AgentCore Control](bedrock-agentcore.md) | `/runtimes/*`, `/gateways/*`, `/memories/*`, `/identities/*`, `/browsers*`, `/browser-profiles*`, `/code-interpreters*`, `/harnesses*`, `/resourcepolicy/*`, `/tags/{resourceArn}` | REST JSON | 71 (+ 3 tagging via shared `/tags/{arn}` route) | | [Bedrock AgentCore](bedrock-agentcore.md#data-plane-invokeagentruntime) | `/runtimes/{agentRuntimeArn}/invocations` | REST JSON (binary payload) | 1 (canned-response stub) | diff --git a/src/main/java/io/floci/aws/services/bedrock/BedrockController.java b/src/main/java/io/floci/aws/services/bedrock/BedrockController.java index 7dc3a20c50..5e5555e94f 100644 --- a/src/main/java/io/floci/aws/services/bedrock/BedrockController.java +++ b/src/main/java/io/floci/aws/services/bedrock/BedrockController.java @@ -8,8 +8,11 @@ import io.floci.aws.core.common.JsonErrorResponseUtils; import io.floci.aws.core.common.PaginatedResult; import io.floci.aws.core.common.Pagination; import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.common.RequestContext; import io.floci.aws.services.bedrock.model.ApplicationInferenceProfile; +import io.floci.aws.services.bedrock.model.EnforcedGuardrailConfiguration; import io.floci.aws.services.bedrock.model.Guardrail; +import io.floci.aws.services.iam.IamService; import jakarta.inject.Inject; import jakarta.ws.rs.Consumes; import jakarta.ws.rs.DELETE; @@ -47,13 +50,17 @@ public class BedrockController { private final BedrockService bedrockService; private final RegionResolver regionResolver; private final ObjectMapper objectMapper; + private final RequestContext requestContext; + private final IamService iamService; @Inject public BedrockController(BedrockService bedrockService, RegionResolver regionResolver, - ObjectMapper objectMapper) { + ObjectMapper objectMapper, RequestContext requestContext, IamService iamService) { this.bedrockService = bedrockService; this.regionResolver = regionResolver; this.objectMapper = objectMapper; + this.requestContext = requestContext; + this.iamService = iamService; } // Guardrails @@ -263,6 +270,45 @@ public class BedrockController { return Response.ok().build(); } + // Account-level enforced guardrail configurations + + @PUT + @Path("/enforcedGuardrailsConfiguration") + public Response putEnforcedGuardrailConfiguration(@Context HttpHeaders headers, String body) { + EnforcedGuardrailConfiguration configuration = bedrockService.putEnforcedGuardrailConfiguration( + readTree(body), callerArn(), regionResolver.resolveRegion(headers)); + + ObjectNode response = objectMapper.createObjectNode(); + response.put("configId", configuration.getConfigId()); + response.put("updatedAt", iso8601(configuration.getUpdatedAt())); + response.put("updatedBy", configuration.getUpdatedBy()); + return Response.ok(response).build(); + } + + @GET + @Path("/enforcedGuardrailsConfiguration") + public Response listEnforcedGuardrailsConfiguration(@Context HttpHeaders headers, + @QueryParam("nextToken") String nextToken) { + PaginatedResult page = bedrockService.listEnforcedGuardrailConfigurations( + nextToken, regionResolver.resolveRegion(headers)); + + ObjectNode response = objectMapper.createObjectNode(); + ArrayNode configurations = response.putArray("guardrailsConfig"); + page.items().forEach(configuration -> configurations.add(enforcedGuardrailConfigurationNode(configuration))); + if (page.nextToken() != null) { + response.put("nextToken", page.nextToken()); + } + return Response.ok(response).build(); + } + + @DELETE + @Path("/enforcedGuardrailsConfiguration/{configId}") + public Response deleteEnforcedGuardrailConfiguration(@Context HttpHeaders headers, + @PathParam("configId") String configId) { + bedrockService.deleteEnforcedGuardrailConfiguration(configId, regionResolver.resolveRegion(headers)); + return Response.ok().build(); + } + // Tags @POST @@ -391,6 +437,29 @@ public class BedrockController { return node; } + /** {@code owner} is always {@code ACCOUNT}: the only {@code ConfigurationOwner} in the AWS model. */ + private ObjectNode enforcedGuardrailConfigurationNode(EnforcedGuardrailConfiguration configuration) { + ObjectNode node = objectMapper.createObjectNode(); + node.put("configId", configuration.getConfigId()); + node.put("guardrailArn", configuration.getGuardrailArn()); + node.put("guardrailId", configuration.getGuardrailId()); + node.put("guardrailVersion", configuration.getGuardrailVersion()); + setIfPresent(node, "selectiveContentGuarding", configuration.getSelectiveContentGuarding()); + setIfPresent(node, "modelEnforcement", configuration.getModelEnforcement()); + node.put("createdAt", iso8601(configuration.getCreatedAt())); + node.put("createdBy", configuration.getCreatedBy()); + node.put("updatedAt", iso8601(configuration.getUpdatedAt())); + node.put("updatedBy", configuration.getUpdatedBy()); + node.put("owner", "ACCOUNT"); + return node; + } + + /** The calling identity's ARN, or the account root when the access key belongs to no IAM identity. */ + private String callerArn() { + return iamService.resolveCallerArn(requestContext.getAccessKeyId()) + .orElseGet(() -> regionResolver.buildGlobalArn("iam", "root")); + } + private void setIfPresent(ObjectNode node, String field, JsonNode value) { if (value != null && !value.isNull()) { node.set(field, value); diff --git a/src/main/java/io/floci/aws/services/bedrock/BedrockService.java b/src/main/java/io/floci/aws/services/bedrock/BedrockService.java index d1d1c7ea67..151ebe2e23 100644 --- a/src/main/java/io/floci/aws/services/bedrock/BedrockService.java +++ b/src/main/java/io/floci/aws/services/bedrock/BedrockService.java @@ -19,6 +19,7 @@ import io.floci.aws.core.storage.AccountAwareStorageBackend; import io.floci.aws.core.storage.StorageBackend; import io.floci.aws.core.storage.StorageFactory; import io.floci.aws.services.bedrock.model.ApplicationInferenceProfile; +import io.floci.aws.services.bedrock.model.EnforcedGuardrailConfiguration; import io.floci.aws.services.bedrock.model.Guardrail; import io.floci.aws.services.kms.KmsService; import io.floci.aws.services.kms.model.KmsKey; @@ -132,6 +133,18 @@ public class BedrockService implements ResourceProvider { /** What {@code GetResourcePolicy} answers for a guardrail profile holding no policy under the called Region. */ private static final String EMPTY_POLICY = "{}"; + /** {@code AccountEnforcedGuardrailConfigurationId} from the AWS model. */ + private static final Pattern ENFORCED_CONFIG_ID_PATTERN = Pattern.compile("[a-z0-9]+"); + + /** + * {@code AccountEnforcedGuardrailsOutputConfiguration} lists at most one item, so + * {@code ListEnforcedGuardrailsConfiguration} returns one configuration per page. + */ + private static final int ENFORCED_CONFIGS_PER_PAGE = 1; + + /** {@code SelectiveGuardingMode} from the AWS model. */ + private static final Set SELECTIVE_GUARDING_MODES = Set.of("SELECTIVE", "COMPREHENSIVE"); + private final StorageBackend guardrails; /** * Guardrail-profile policies, keyed by the Region whose endpoint stored them and the profile ARN. A @@ -140,6 +153,7 @@ public class BedrockService implements ResourceProvider { */ private final StorageBackend guardrailProfilePolicies; private final StorageBackend applicationInferenceProfiles; + private final StorageBackend enforcedGuardrailConfigurations; private final RegionResolver regionResolver; private final ObjectMapper objectMapper; private final KmsService kmsService; @@ -153,17 +167,21 @@ public class BedrockService implements ResourceProvider { new TypeReference>() {}), storageFactory.create("bedrock", "bedrock-application-inference-profiles.json", new TypeReference>() {}), + storageFactory.create("bedrock", "bedrock-enforced-guardrail-configurations.json", + new TypeReference>() {}), regionResolver, objectMapper, kmsService); } BedrockService(StorageBackend guardrails, StorageBackend guardrailProfilePolicies, StorageBackend applicationInferenceProfiles, + StorageBackend enforcedGuardrailConfigurations, RegionResolver regionResolver, ObjectMapper objectMapper, KmsService kmsService) { this.guardrails = guardrails; this.guardrailProfilePolicies = guardrailProfilePolicies; this.applicationInferenceProfiles = applicationInferenceProfiles; + this.enforcedGuardrailConfigurations = enforcedGuardrailConfigurations; this.regionResolver = regionResolver; this.objectMapper = objectMapper; this.kmsService = kmsService; @@ -253,6 +271,7 @@ public class BedrockService implements ResourceProvider { "guardrailVersion must be a numerical version.", 400); } getGuardrail(guardrailId, version, region); + rejectEnforcedGuardrailDeletion(guardrailId, version, region); guardrails.delete(storageKey(region, guardrailId, version)); LOG.infov("Deleted Bedrock guardrail {0} version {1}", guardrailId, version); return; @@ -262,12 +281,24 @@ public class BedrockService implements ResourceProvider { throw new AwsException("ResourceNotFoundException", "Guardrail " + guardrailId + " does not exist.", 404); } + rejectEnforcedGuardrailDeletion(guardrailId, null, region); for (Guardrail guardrail : versions) { guardrails.delete(storageKey(region, guardrailId, guardrail.getVersion())); } LOG.infov("Deleted Bedrock guardrail: {0}", guardrailId); } + private void rejectEnforcedGuardrailDeletion(String guardrailId, String version, String region) { + boolean enforced = enforcedGuardrailConfigurations.scan(key -> key.startsWith(region + "::")).stream() + .anyMatch(configuration -> guardrailId.equals(configuration.getGuardrailId()) + && (version == null || version.equals(configuration.getGuardrailVersion()))); + if (enforced) { + throw new AwsException("ValidationException", + "The guardrail cannot be deleted because it is associated with an account-level " + + "or organization-level default guardrail configuration.", 400); + } + } + /** * 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. @@ -647,6 +678,136 @@ public class BedrockService implements ResourceProvider { LOG.infov("Deleted resource policy of Bedrock guardrail: {0}", guardrail.getGuardrailId()); } + // Account-level enforced guardrail configurations + + /** + * Creates a configuration when {@code configId} is absent and replaces the named one when it is + * present. The guardrail must hold the numerical version the request names; a DRAFT cannot be + * enforced because {@code guardrailVersion} is a {@code GuardrailNumericalVersion}. + * + * @param callerArn the identity making the call, recorded as {@code updatedBy}, and as + * {@code createdBy} when the configuration is new + */ + public synchronized EnforcedGuardrailConfiguration putEnforcedGuardrailConfiguration(JsonNode request, String callerArn, + String region) { + JsonNode inferenceConfig = request.path("guardrailInferenceConfig").deepCopy(); + if (!inferenceConfig.isObject()) { + throw new AwsException("ValidationException", "guardrailInferenceConfig is required", 400); + } + String version = requiredText(inferenceConfig, "guardrailVersion"); + if (!NUMERICAL_VERSION_PATTERN.matcher(version).matches()) { + throw new AwsException("ValidationException", + "guardrailVersion must be a numerical version.", 400); + } + String identifier = requiredText(inferenceConfig, "guardrailIdentifier"); + Guardrail guardrail = getGuardrail(identifier, version, region); + if (AwsArnUtils.looksLikeArn(identifier) && !identifier.equals(guardrail.getGuardrailArn())) { + throw new AwsException("ResourceNotFoundException", + "Guardrail " + identifier + " version " + version + " does not exist.", 404); + } + JsonNode selectiveContentGuarding = selectiveContentGuarding(inferenceConfig.get("selectiveContentGuarding")); + JsonNode modelEnforcement = modelEnforcement(inferenceConfig.get("modelEnforcement")); + + String configId = textOrNull(request, "configId"); + EnforcedGuardrailConfiguration configuration = configId == null + ? newEnforcedGuardrailConfiguration(callerArn) + : copyOf(getEnforcedGuardrailConfiguration(configId, region, + "Enforced guardrail configuration " + configId + " does not exist.")); + configuration.setGuardrailId(guardrail.getGuardrailId()); + configuration.setGuardrailArn(guardrail.getGuardrailArn()); + configuration.setGuardrailVersion(version); + configuration.setSelectiveContentGuarding(selectiveContentGuarding); + configuration.setModelEnforcement(modelEnforcement); + configuration.setUpdatedAt(Instant.now()); + configuration.setUpdatedBy(callerArn); + + enforcedGuardrailConfigurations.put(enforcedConfigKey(region, configuration.getConfigId()), configuration); + LOG.infov("Put Bedrock enforced guardrail configuration {0} for guardrail {1} version {2}", + configuration.getConfigId(), guardrail.getGuardrailId(), version); + return copyOf(configuration); + } + + public PaginatedResult listEnforcedGuardrailConfigurations(String nextToken, + String region) { + String prefix = region + "::"; + List configurations = + enforcedGuardrailConfigurations.scan(key -> key.startsWith(prefix)).stream() + .map(this::copyOf).toList(); + return Pagination.paginate(configurations, EnforcedGuardrailConfiguration::getConfigId, null, nextToken, + ENFORCED_CONFIGS_PER_PAGE, "ValidationException"); + } + + public synchronized void deleteEnforcedGuardrailConfiguration(String configId, String region) { + getEnforcedGuardrailConfiguration(configId, region, + "No default guardrail configuration found for the specified config identifier."); + enforcedGuardrailConfigurations.delete(enforcedConfigKey(region, configId)); + LOG.infov("Deleted Bedrock enforced guardrail configuration {0}", configId); + } + + private EnforcedGuardrailConfiguration newEnforcedGuardrailConfiguration(String callerArn) { + EnforcedGuardrailConfiguration configuration = new EnforcedGuardrailConfiguration(); + configuration.setConfigId(newGuardrailId()); + configuration.setCreatedAt(Instant.now()); + configuration.setCreatedBy(callerArn); + return configuration; + } + + private EnforcedGuardrailConfiguration getEnforcedGuardrailConfiguration(String configId, String region, + String missingMessage) { + if (!ENFORCED_CONFIG_ID_PATTERN.matcher(configId).matches()) { + throw new AwsException("ValidationException", "configId must match [a-z0-9]+.", 400); + } + return enforcedGuardrailConfigurations.get(enforcedConfigKey(region, configId)) + .orElseThrow(() -> new AwsException("ResourceNotFoundException", + missingMessage, 404)); + } + + private JsonNode selectiveContentGuarding(JsonNode guarding) { + if (guarding == null || guarding.isNull()) { + return null; + } + if (!guarding.isObject()) { + throw new AwsException("ValidationException", "selectiveContentGuarding must be an object.", 400); + } + for (String member : List.of("system", "messages")) { + JsonNode mode = guarding.get(member); + if (mode != null && !mode.isNull() && !SELECTIVE_GUARDING_MODES.contains(mode.asText())) { + throw new AwsException("ValidationException", + "selectiveContentGuarding." + member + " must be SELECTIVE or COMPREHENSIVE.", 400); + } + } + return guarding; + } + + /** + * {@code ModelEnforcement} requires both lists, and {@code includedModels} holds at least one + * entry. Leaving the structure out records the default all-model selection. + */ + private JsonNode modelEnforcement(JsonNode enforcement) { + if (enforcement == null || enforcement.isNull()) { + return null; + } + JsonNode included = enforcement.get("includedModels"); + JsonNode excluded = enforcement.get("excludedModels"); + if (included == null || !included.isArray() || included.isEmpty() + || excluded == null || !excluded.isArray()) { + throw new AwsException("ValidationException", + "modelEnforcement needs a non-empty includedModels list and an excludedModels list.", 400); + } + for (JsonNode models : List.of(included, excluded)) { + for (JsonNode model : models) { + if (!model.isTextual()) { + throw new AwsException("ValidationException", "modelEnforcement model lists must contain strings.", 400); + } + } + } + return enforcement; + } + + private static String enforcedConfigKey(String region, String configId) { + return region + "::" + configId; + } + // Tags public Map listTags(String resourceArn, String region) { @@ -833,6 +994,23 @@ public class BedrockService implements ResourceProvider { return details; } + private EnforcedGuardrailConfiguration copyOf(EnforcedGuardrailConfiguration source) { + EnforcedGuardrailConfiguration copy = new EnforcedGuardrailConfiguration(); + copy.setConfigId(source.getConfigId()); + copy.setGuardrailId(source.getGuardrailId()); + copy.setGuardrailArn(source.getGuardrailArn()); + copy.setGuardrailVersion(source.getGuardrailVersion()); + copy.setSelectiveContentGuarding(source.getSelectiveContentGuarding() == null + ? null : source.getSelectiveContentGuarding().deepCopy()); + copy.setModelEnforcement(source.getModelEnforcement() == null + ? null : source.getModelEnforcement().deepCopy()); + copy.setCreatedAt(source.getCreatedAt()); + copy.setCreatedBy(source.getCreatedBy()); + copy.setUpdatedAt(source.getUpdatedAt()); + copy.setUpdatedBy(source.getUpdatedBy()); + return copy; + } + private Guardrail copyOf(Guardrail source) { Guardrail copy = new Guardrail(); copy.setGuardrailId(source.getGuardrailId()); diff --git a/src/main/java/io/floci/aws/services/bedrock/model/EnforcedGuardrailConfiguration.java b/src/main/java/io/floci/aws/services/bedrock/model/EnforcedGuardrailConfiguration.java new file mode 100644 index 0000000000..b93279a0b6 --- /dev/null +++ b/src/main/java/io/floci/aws/services/bedrock/model/EnforcedGuardrailConfiguration.java @@ -0,0 +1,95 @@ +package io.floci.aws.services.bedrock.model; + +import com.fasterxml.jackson.databind.JsonNode; +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.time.Instant; + +/** + * A stored account-level guardrail control-plane configuration, recording a numerical guardrail + * version and optional model selection. + */ +@RegisterForReflection +public class EnforcedGuardrailConfiguration { + + private String configId; + private String guardrailId; + private String guardrailArn; + private String guardrailVersion; + private JsonNode selectiveContentGuarding; + private JsonNode modelEnforcement; + private Instant createdAt; + private String createdBy; + private Instant updatedAt; + private String updatedBy; + + public String getConfigId() { + return configId; + } + public void setConfigId(String configId) { + this.configId = configId; + } + + 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 getGuardrailVersion() { + return guardrailVersion; + } + public void setGuardrailVersion(String guardrailVersion) { + this.guardrailVersion = guardrailVersion; + } + + public JsonNode getSelectiveContentGuarding() { + return selectiveContentGuarding; + } + public void setSelectiveContentGuarding(JsonNode selectiveContentGuarding) { + this.selectiveContentGuarding = selectiveContentGuarding; + } + + public JsonNode getModelEnforcement() { + return modelEnforcement; + } + public void setModelEnforcement(JsonNode modelEnforcement) { + this.modelEnforcement = modelEnforcement; + } + + public Instant getCreatedAt() { + return createdAt; + } + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + + public String getCreatedBy() { + return createdBy; + } + public void setCreatedBy(String createdBy) { + this.createdBy = createdBy; + } + + public Instant getUpdatedAt() { + return updatedAt; + } + public void setUpdatedAt(Instant updatedAt) { + this.updatedAt = updatedAt; + } + + public String getUpdatedBy() { + return updatedBy; + } + public void setUpdatedBy(String updatedBy) { + this.updatedBy = updatedBy; + } +} diff --git a/src/test/java/io/floci/aws/services/bedrock/BedrockApplicationInferenceProfileServiceTest.java b/src/test/java/io/floci/aws/services/bedrock/BedrockApplicationInferenceProfileServiceTest.java index 833522d89d..d1b756215c 100644 --- a/src/test/java/io/floci/aws/services/bedrock/BedrockApplicationInferenceProfileServiceTest.java +++ b/src/test/java/io/floci/aws/services/bedrock/BedrockApplicationInferenceProfileServiceTest.java @@ -30,7 +30,7 @@ class BedrockApplicationInferenceProfileServiceTest { private final BedrockService service = serviceFor(ACCOUNT); private BedrockService serviceFor(String account) { - return new BedrockService(new InMemoryStorage<>(), new InMemoryStorage<>(), profiles, + return new BedrockService(new InMemoryStorage<>(), new InMemoryStorage<>(), profiles, new InMemoryStorage<>(), new RegionResolver(REGION, account), new ObjectMapper(), mock(KmsService.class)); } diff --git a/src/test/java/io/floci/aws/services/bedrock/BedrockEnforcedGuardrailEdgesTest.java b/src/test/java/io/floci/aws/services/bedrock/BedrockEnforcedGuardrailEdgesTest.java new file mode 100644 index 0000000000..c88fdebff7 --- /dev/null +++ b/src/test/java/io/floci/aws/services/bedrock/BedrockEnforcedGuardrailEdgesTest.java @@ -0,0 +1,254 @@ +package io.floci.aws.services.bedrock; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.floci.aws.core.common.AwsException; +import io.floci.aws.core.common.PaginatedResult; +import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.storage.InMemoryStorage; +import io.floci.aws.services.bedrock.model.EnforcedGuardrailConfiguration; +import io.floci.aws.services.kms.KmsService; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.ValueSource; + +import java.util.HashSet; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +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.mock; + +class BedrockEnforcedGuardrailEdgesTest { + + private static final String REGION = "us-east-1"; + private static final String CALLER = "arn:aws:iam::000000000000:root"; + + private final ObjectMapper mapper = new ObjectMapper(); + private BedrockService service; + private String guardrail; + + @BeforeEach + void prepareGuardrail() { + service = new BedrockService(new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), + new RegionResolver(REGION, "000000000000"), mapper, mock(KmsService.class)); + guardrail = BedrockEnforcedGuardrailFixtures.publish(service, REGION, + BedrockEnforcedGuardrailFixtures.guardrailRequest(mapper, "edges", "blocked", "blocked")).getGuardrailId(); + } + + @Test + void paginationContinuesAfterDeletingTheCursorRecord() { + Set expected = new HashSet<>(); + for (int i = 0; i < 3; i++) { + expected.add(service.putEnforcedGuardrailConfiguration(request(), CALLER, REGION).getConfigId()); + } + PaginatedResult first = service.listEnforcedGuardrailConfigurations(null, REGION); + assertEquals(1, first.items().size()); + assertNotNull(first.nextToken()); + String deleted = first.items().getFirst().getConfigId(); + expected.remove(deleted); + service.deleteEnforcedGuardrailConfiguration(deleted, REGION); + Set seen = new HashSet<>(); + String token = first.nextToken(); + for (int i = 0; i < 2; i++) { + PaginatedResult page = service.listEnforcedGuardrailConfigurations(token, REGION); + assertEquals(1, page.items().size()); + assertTrue(seen.add(page.items().getFirst().getConfigId())); + token = page.nextToken(); + } + assertNull(token); + assertEquals(expected, seen); + assertFalse(seen.contains(deleted)); + } + + @Test + void malformedCursorIsRejected() { + AwsException error = assertThrows(AwsException.class, + () -> service.listEnforcedGuardrailConfigurations("!!!!", REGION)); + assertEquals("ValidationException", error.getErrorCode()); + } + + @Test + void invalidNumericalVersionBoundsAreRejectedWithoutWriting() { + for (String version : new String[]{"0", "01", "100000000"}) { + ObjectNode request = request(); + ((ObjectNode) request.get("guardrailInferenceConfig")).put("guardrailVersion", version); + AwsException error = assertThrows(AwsException.class, + () -> service.putEnforcedGuardrailConfiguration(request, CALLER, REGION)); + assertEquals("ValidationException", error.getErrorCode()); + } + assertTrue(service.listEnforcedGuardrailConfigurations(null, REGION).items().isEmpty()); + } + + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void selectiveContentGuardingRejectsNonObjectValues(boolean array) { + ObjectNode request = request(); + ObjectNode config = (ObjectNode) request.get("guardrailInferenceConfig"); + if (array) { + config.putArray("selectiveContentGuarding").add("SELECTIVE"); + } else { + config.put("selectiveContentGuarding", "SELECTIVE"); + } + assertInvalidAndUnstored(request); + } + + @ParameterizedTest + @ValueSource(strings = {"includedModels", "excludedModels"}) + void modelListsRejectNonStringMembers(String member) { + ObjectNode request = request(); + ObjectNode config = (ObjectNode) request.get("guardrailInferenceConfig"); + ObjectNode enforcement = config.putObject("modelEnforcement"); + enforcement.putArray("includedModels").add("ALL"); + enforcement.putArray("excludedModels"); + enforcement.putArray(member).add(42); + assertInvalidAndUnstored(request); + } + + @ParameterizedTest + @CsvSource({ + "partition,false", "region,false", "account,false", "service,false", "resource,false", + "partition,true", "region,true", "account,true", "service,true", "resource,true" + }) + void mismatchedGuardrailArnIsRejectedWithoutMutation(String component, boolean replace) { + String arn = service.getGuardrail(guardrail, "1", REGION).getGuardrailArn(); + String mismatchedArn = switch (component) { + case "partition" -> arn.replace("arn:aws:", "arn:aws-cn:"); + case "region" -> arn.replace(":us-east-1:", ":us-west-2:"); + case "account" -> arn.replace(":000000000000:", ":111111111111:"); + case "service" -> arn.replace(":bedrock:", ":sagemaker:"); + case "resource" -> arn.replace(":guardrail/", ":guardrail-profile/"); + default -> throw new IllegalArgumentException(component); + }; + ObjectNode invalid = request(); + String configId = replace + ? service.putEnforcedGuardrailConfiguration(request(), CALLER, REGION).getConfigId() : null; + if (replace) { + invalid.put("configId", configId); + } + ((ObjectNode) invalid.get("guardrailInferenceConfig")).put("guardrailIdentifier", mismatchedArn); + ObjectNode originalRequest = invalid.deepCopy(); + EnforcedGuardrailConfiguration before = configId == null ? null + : service.listEnforcedGuardrailConfigurations(null, REGION).items().getFirst(); + + AwsException error = assertThrows(AwsException.class, + () -> service.putEnforcedGuardrailConfiguration(invalid, "changed", REGION)); + + assertEquals("ResourceNotFoundException", error.getErrorCode()); + assertEquals(404, error.getHttpStatus()); + assertEquals(originalRequest, invalid); + if (replace) { + EnforcedGuardrailConfiguration after = + service.listEnforcedGuardrailConfigurations(null, REGION).items().getFirst(); + assertEquals(before.getConfigId(), after.getConfigId()); + assertEquals(before.getGuardrailId(), after.getGuardrailId()); + assertEquals(before.getGuardrailArn(), after.getGuardrailArn()); + assertEquals(before.getGuardrailVersion(), after.getGuardrailVersion()); + assertEquals(before.getSelectiveContentGuarding(), after.getSelectiveContentGuarding()); + assertEquals(before.getModelEnforcement(), after.getModelEnforcement()); + assertEquals(before.getCreatedAt(), after.getCreatedAt()); + assertEquals(before.getCreatedBy(), after.getCreatedBy()); + assertEquals(before.getUpdatedAt(), after.getUpdatedAt()); + assertEquals(before.getUpdatedBy(), after.getUpdatedBy()); + } else { + assertTrue(service.listEnforcedGuardrailConfigurations(null, REGION).items().isEmpty()); + } + } + + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void exactGuardrailArnAndIdRemainAccepted(boolean useArn) { + String arn = service.getGuardrail(guardrail, "1", REGION).getGuardrailArn(); + ObjectNode valid = request(); + ((ObjectNode) valid.get("guardrailInferenceConfig")).put("guardrailIdentifier", useArn ? arn : guardrail); + EnforcedGuardrailConfiguration created = service.putEnforcedGuardrailConfiguration(valid, CALLER, REGION); + assertEquals(guardrail, created.getGuardrailId()); + assertEquals(arn, created.getGuardrailArn()); + valid.put("configId", created.getConfigId()); + EnforcedGuardrailConfiguration replaced = service.putEnforcedGuardrailConfiguration(valid, "changed", REGION); + assertEquals(created.getConfigId(), replaced.getConfigId()); + assertEquals(arn, replaced.getGuardrailArn()); + assertEquals("changed", replaced.getUpdatedBy()); + } + + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void configuredGuardrailCannotBeDeletedWithoutMutation(boolean wholeGuardrail) { + EnforcedGuardrailConfiguration configuration = + service.putEnforcedGuardrailConfiguration(request(), CALLER, REGION); + String version = wholeGuardrail ? null : "1"; + + AwsException error = assertThrows(AwsException.class, + () -> service.deleteGuardrail(guardrail, version, REGION)); + + assertEquals("ValidationException", error.getErrorCode()); + assertEquals(400, error.getHttpStatus()); + assertEquals("The guardrail cannot be deleted because it is associated with an account-level " + + "or organization-level default guardrail configuration.", error.getMessage()); + assertEquals(guardrail, service.getGuardrail(guardrail, "DRAFT", REGION).getGuardrailId()); + assertEquals(guardrail, service.getGuardrail(guardrail, "1", REGION).getGuardrailId()); + assertEquals(configuration.getConfigId(), + service.listEnforcedGuardrailConfigurations(null, REGION).items().getFirst().getConfigId()); + } + + @Test + void unrelatedVersionCanBeDeletedWhileConfiguredVersionRemains() { + EnforcedGuardrailConfiguration configuration = + service.putEnforcedGuardrailConfiguration(request(), CALLER, REGION); + service.createGuardrailVersion(guardrail, null, REGION); + + service.deleteGuardrail(guardrail, "2", REGION); + + assertEquals(guardrail, service.getGuardrail(guardrail, "1", REGION).getGuardrailId()); + assertEquals(configuration.getConfigId(), + service.listEnforcedGuardrailConfigurations(null, REGION).items().getFirst().getConfigId()); + AwsException missing = assertThrows(AwsException.class, + () -> service.getGuardrail(guardrail, "2", REGION)); + assertEquals("ResourceNotFoundException", missing.getErrorCode()); + } + + @Test + void guardrailCanBeDeletedAfterItsConfigurationIsRemoved() { + String configId = service.putEnforcedGuardrailConfiguration(request(), CALLER, REGION).getConfigId(); + service.deleteEnforcedGuardrailConfiguration(configId, REGION); + + service.deleteGuardrail(guardrail, null, REGION); + + assertTrue(service.listEnforcedGuardrailConfigurations(null, REGION).items().isEmpty()); + AwsException missing = assertThrows(AwsException.class, + () -> service.getGuardrail(guardrail, "1", REGION)); + assertEquals("ResourceNotFoundException", missing.getErrorCode()); + } + + @Test + void deletingUnknownConfigurationUsesTheModeledMessageWithoutMutation() { + String configId = service.putEnforcedGuardrailConfiguration(request(), CALLER, REGION).getConfigId(); + + AwsException error = assertThrows(AwsException.class, + () -> service.deleteEnforcedGuardrailConfiguration("missingconfiguration", REGION)); + + assertEquals("ResourceNotFoundException", error.getErrorCode()); + assertEquals(404, error.getHttpStatus()); + assertEquals("No default guardrail configuration found for the specified config identifier.", + error.getMessage()); + assertEquals(configId, + service.listEnforcedGuardrailConfigurations(null, REGION).items().getFirst().getConfigId()); + } + + private void assertInvalidAndUnstored(ObjectNode request) { + AwsException error = assertThrows(AwsException.class, + () -> service.putEnforcedGuardrailConfiguration(request, CALLER, REGION)); + assertEquals("ValidationException", error.getErrorCode()); + assertTrue(service.listEnforcedGuardrailConfigurations(null, REGION).items().isEmpty()); + } + + private ObjectNode request() { + return BedrockEnforcedGuardrailFixtures.request(mapper, guardrail, "1"); + } +} diff --git a/src/test/java/io/floci/aws/services/bedrock/BedrockEnforcedGuardrailFixtures.java b/src/test/java/io/floci/aws/services/bedrock/BedrockEnforcedGuardrailFixtures.java new file mode 100644 index 0000000000..9314a18a0a --- /dev/null +++ b/src/test/java/io/floci/aws/services/bedrock/BedrockEnforcedGuardrailFixtures.java @@ -0,0 +1,37 @@ +package io.floci.aws.services.bedrock; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.floci.aws.services.bedrock.model.Guardrail; + +final class BedrockEnforcedGuardrailFixtures { + + private BedrockEnforcedGuardrailFixtures() { + } + + static Guardrail publish(BedrockService service, String region, ObjectNode request) { + Guardrail draft = service.createGuardrail(request, region); + return service.createGuardrailVersion(draft.getGuardrailId(), null, region); + } + + static ObjectNode guardrailRequest(ObjectMapper mapper, String name, String inputMessage, String outputMessage) { + return mapper.createObjectNode().put("name", name).put("blockedInputMessaging", inputMessage) + .put("blockedOutputsMessaging", outputMessage); + } + + static ObjectNode request(ObjectMapper mapper, String identifier, String version) { + ObjectNode request = mapper.createObjectNode(); + request.putObject("guardrailInferenceConfig").put("guardrailIdentifier", identifier).put("guardrailVersion", version); + return request; + } + + static ObjectNode selectiveRequest(ObjectMapper mapper, String identifier, String version) { + ObjectNode request = request(mapper, identifier, version); + ObjectNode config = (ObjectNode) request.get("guardrailInferenceConfig"); + config.putObject("selectiveContentGuarding").put("system", "SELECTIVE"); + ObjectNode enforcement = config.putObject("modelEnforcement"); + enforcement.putArray("includedModels").add("ALL"); + enforcement.putArray("excludedModels"); + return request; + } +} diff --git a/src/test/java/io/floci/aws/services/bedrock/BedrockEnforcedGuardrailIsolationTest.java b/src/test/java/io/floci/aws/services/bedrock/BedrockEnforcedGuardrailIsolationTest.java new file mode 100644 index 0000000000..ddd9a38056 --- /dev/null +++ b/src/test/java/io/floci/aws/services/bedrock/BedrockEnforcedGuardrailIsolationTest.java @@ -0,0 +1,114 @@ +package io.floci.aws.services.bedrock; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.floci.aws.core.common.AwsException; +import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.storage.InMemoryStorage; +import io.floci.aws.services.bedrock.model.EnforcedGuardrailConfiguration; +import io.floci.aws.services.kms.KmsService; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.mock; + +class BedrockEnforcedGuardrailIsolationTest { + + private static final String REGION = "us-east-1"; + private static final String CALLER = "arn:aws:iam::000000000000:user/first"; + + private final ObjectMapper mapper = new ObjectMapper(); + private BedrockService service; + private String guardrail; + + @BeforeEach + void prepareGuardrail() { + service = new BedrockService(new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), + new RegionResolver(REGION, "000000000000"), mapper, mock(KmsService.class)); + guardrail = BedrockEnforcedGuardrailFixtures.publish(service, REGION, + BedrockEnforcedGuardrailFixtures.guardrailRequest(mapper, "isolation", "blocked", "blocked")).getGuardrailId(); + } + + @Test + void mutatingTheRequestAfterPutCannotChangeTheSavedConfiguration() { + ObjectNode request = request(); + service.putEnforcedGuardrailConfiguration(request, CALLER, REGION); + ObjectNode inference = (ObjectNode) request.get("guardrailInferenceConfig"); + ((ObjectNode) inference.get("selectiveContentGuarding")).put("system", "COMPREHENSIVE"); + ((ObjectNode) inference.get("modelEnforcement")).putArray("includedModels").add("changed"); + assertSavedConfiguration(); + } + + @Test + void mutatingThePutResponseCannotChangeTheSavedConfiguration() { + EnforcedGuardrailConfiguration returned = service.putEnforcedGuardrailConfiguration(request(), CALLER, REGION); + returned.setUpdatedBy("changed"); + ((ObjectNode) returned.getSelectiveContentGuarding()).put("system", "COMPREHENSIVE"); + assertSavedConfiguration(); + } + + @Test + void mutatingAListItemCannotChangeTheSavedConfiguration() { + service.putEnforcedGuardrailConfiguration(request(), CALLER, REGION); + EnforcedGuardrailConfiguration returned = saved(); + returned.setGuardrailVersion("9"); + ((ObjectNode) returned.getModelEnforcement()).putArray("includedModels").add("changed"); + assertSavedConfiguration(); + } + + @Test + void concurrentUpdatesKeepEachReturnedCallerSnapshot() throws Exception { + String id = service.putEnforcedGuardrailConfiguration(request(), CALLER, REGION).getConfigId(); + List returned = new ArrayList<>(); + try (ExecutorService executor = Executors.newFixedThreadPool(4)) { + List> futures = new ArrayList<>(); + for (int i = 0; i < 8; i++) { + String caller = CALLER + i; + futures.add(executor.submit(() -> service.putEnforcedGuardrailConfiguration( + request().put("configId", id), caller, REGION))); + } + for (Future future : futures) { + returned.add(future.get()); + } + } + for (int i = 0; i < returned.size(); i++) { + assertEquals(CALLER + i, returned.get(i).getUpdatedBy()); + assertEquals(id, returned.get(i).getConfigId()); + } + } + + @Test + void aRejectedReplacementLeavesTheStoredConfigurationIntact() { + String id = service.putEnforcedGuardrailConfiguration(request(), CALLER, REGION).getConfigId(); + ObjectNode invalid = request().put("configId", id); + ((ObjectNode) invalid.get("guardrailInferenceConfig")).put("guardrailVersion", "DRAFT"); + AwsException error = assertThrows(AwsException.class, + () -> service.putEnforcedGuardrailConfiguration(invalid, "changed", REGION)); + assertEquals("ValidationException", error.getErrorCode()); + assertSavedConfiguration(); + } + + private void assertSavedConfiguration() { + EnforcedGuardrailConfiguration stored = saved(); + assertEquals("1", stored.getGuardrailVersion()); + assertEquals(CALLER, stored.getUpdatedBy()); + assertEquals("SELECTIVE", stored.getSelectiveContentGuarding().path("system").asText()); + assertEquals("ALL", stored.getModelEnforcement().path("includedModels").get(0).asText()); + } + + private EnforcedGuardrailConfiguration saved() { + return service.listEnforcedGuardrailConfigurations(null, REGION).items().getFirst(); + } + + private ObjectNode request() { + return BedrockEnforcedGuardrailFixtures.selectiveRequest(mapper, guardrail, "1"); + } +} diff --git a/src/test/java/io/floci/aws/services/bedrock/BedrockEnforcedGuardrailSdkIntegrationTest.java b/src/test/java/io/floci/aws/services/bedrock/BedrockEnforcedGuardrailSdkIntegrationTest.java new file mode 100644 index 0000000000..60dd49be6c --- /dev/null +++ b/src/test/java/io/floci/aws/services/bedrock/BedrockEnforcedGuardrailSdkIntegrationTest.java @@ -0,0 +1,248 @@ +package io.floci.aws.services.bedrock; + +import io.floci.aws.testing.AwsTestClients; +import io.floci.aws.testing.EnforcementFixtures; +import io.floci.aws.testing.IamEnforcementProfile; +import io.floci.aws.testing.PartitionCleanup; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; +import io.restassured.RestAssured; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.bedrock.BedrockClient; +import software.amazon.awssdk.services.bedrock.model.AccountEnforcedGuardrailInferenceInputConfiguration; +import software.amazon.awssdk.services.bedrock.model.AccountEnforcedGuardrailOutputConfiguration; +import software.amazon.awssdk.services.bedrock.model.BedrockException; +import software.amazon.awssdk.services.bedrock.model.CreateGuardrailResponse; +import software.amazon.awssdk.services.bedrock.model.ListEnforcedGuardrailsConfigurationRequest; +import software.amazon.awssdk.services.bedrock.model.ListEnforcedGuardrailsConfigurationResponse; +import software.amazon.awssdk.services.bedrock.model.PutEnforcedGuardrailConfigurationResponse; + +import java.util.HashSet; +import java.util.Set; +import java.util.UUID; + +import static io.floci.aws.testing.EnforcementFixtures.auth; +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; + +@QuarkusTest +@TestProfile(IamEnforcementProfile.class) +class BedrockEnforcedGuardrailSdkIntegrationTest { + + private static final String ACCOUNT = "000000000000"; + + @RegisterExtension + final PartitionCleanup cleanup = new PartitionCleanup(); + + @Test + void sdkRoundTripRecordsTheUserAndReplacesTheExistingConfiguration() { + try (BedrockClient root = client(ACCOUNT, Region.US_EAST_1)) { + CreateGuardrailResponse guardrail = create(root); + String userName = "enforced-sdk-" + UUID.randomUUID(); + EnforcementFixtures.UserCredentials credentials = EnforcementFixtures.createUser( + cleanup, RestAssured.port, auth(ACCOUNT, "iam"), userName); + EnforcementFixtures.putUserPolicy(RestAssured.port, auth(ACCOUNT, "iam"), userName, "p", """ + {"Version":"2012-10-17","Statement":[ + {"Effect":"Allow","Action":"bedrock:*","Resource":"*"}]} + """); + try (BedrockClient user = client(credentials.accessKeyId(), Region.US_EAST_1)) { + PutEnforcedGuardrailConfigurationResponse created = user.putEnforcedGuardrailConfiguration(r -> + r.guardrailInferenceConfig(config(guardrail.guardrailArn()))); + String id = created.configId(); + try { + String userArn = "arn:aws:iam::" + ACCOUNT + ":user/" + userName; + assertEquals(userArn, created.updatedBy()); + assertNotNull(created.updatedAt()); + AccountEnforcedGuardrailOutputConfiguration first = find(user, id); + assertEquals(userArn, first.createdBy()); + assertEquals(userArn, first.updatedBy()); + assertEquals(guardrail.guardrailArn(), first.guardrailArn()); + assertEquals(guardrail.guardrailId(), first.guardrailId()); + assertEquals("1", first.guardrailVersion()); + assertEquals("ACCOUNT", first.ownerAsString()); + assertNotNull(first.createdAt()); + assertNotNull(first.updatedAt()); + PutEnforcedGuardrailConfigurationResponse replaced = root.putEnforcedGuardrailConfiguration(r -> + r.configId(id).guardrailInferenceConfig(config(guardrail.guardrailId()))); + assertEquals(id, replaced.configId()); + AccountEnforcedGuardrailOutputConfiguration second = find(user, id); + assertEquals(first.createdAt(), second.createdAt()); + assertEquals(userArn, second.createdBy()); + assertEquals("arn:aws:iam::" + ACCOUNT + ":root", second.updatedBy()); + user.deleteEnforcedGuardrailConfiguration(r -> r.configId(id)); + assertTrue(user.listEnforcedGuardrailsConfiguration(ListEnforcedGuardrailsConfigurationRequest.builder().build()).guardrailsConfig().stream() + .noneMatch(c -> c.configId().equals(id))); + BedrockException missing = assertThrows(BedrockException.class, + () -> user.deleteEnforcedGuardrailConfiguration(r -> r.configId(id))); + assertEquals("ResourceNotFoundException", missing.awsErrorDetails().errorCode()); + } finally { + if (root.listEnforcedGuardrailsConfiguration(ListEnforcedGuardrailsConfigurationRequest.builder().build()).guardrailsConfig().stream() + .anyMatch(c -> c.configId().equals(id))) { + root.deleteEnforcedGuardrailConfiguration(r -> r.configId(id)); + } + } + } finally { + root.deleteGuardrail(r -> r.guardrailIdentifier(guardrail.guardrailId())); + } + } + } + + @Test + void sdkConfigurationsStayInTheirAccountAndRegion() { + try (BedrockClient root = client(ACCOUNT, Region.US_EAST_1); + BedrockClient otherAccount = client("111111111111", Region.US_EAST_1); + BedrockClient otherRegion = client(ACCOUNT, Region.EU_WEST_1)) { + CreateGuardrailResponse guardrail = create(root); + String id = root.putEnforcedGuardrailConfiguration(r -> + r.guardrailInferenceConfig(config(guardrail.guardrailId()))).configId(); + try { + for (BedrockClient other : new BedrockClient[]{otherAccount, otherRegion}) { + assertTrue(other.listEnforcedGuardrailsConfiguration(ListEnforcedGuardrailsConfigurationRequest.builder().build()).guardrailsConfig().isEmpty()); + BedrockException missing = assertThrows(BedrockException.class, + () -> other.deleteEnforcedGuardrailConfiguration(r -> r.configId(id))); + assertEquals("ResourceNotFoundException", missing.awsErrorDetails().errorCode()); + } + assertEquals(id, find(root, id).configId()); + } finally { + root.deleteEnforcedGuardrailConfiguration(r -> r.configId(id)); + root.deleteGuardrail(r -> r.guardrailIdentifier(guardrail.guardrailId())); + } + } + } + + @ParameterizedTest + @ValueSource(strings = {"PutEnforcedGuardrailConfiguration", "ListEnforcedGuardrailsConfiguration", + "DeleteEnforcedGuardrailConfiguration"}) + void eachSdkActionHonorsItsExplicitDeny(String action) { + try (BedrockClient root = client(ACCOUNT, Region.US_EAST_1)) { + CreateGuardrailResponse guardrail = create(root); + String id = root.putEnforcedGuardrailConfiguration(r -> + r.guardrailInferenceConfig(config(guardrail.guardrailId()))).configId(); + try { + String userName = "enforced-deny-" + UUID.randomUUID(); + EnforcementFixtures.UserCredentials credentials = EnforcementFixtures.createUser( + cleanup, RestAssured.port, auth(ACCOUNT, "iam"), userName); + EnforcementFixtures.putUserPolicy(RestAssured.port, auth(ACCOUNT, "iam"), userName, "p", """ + {"Version":"2012-10-17","Statement":[ + {"Effect":"Allow","Action":"bedrock:*","Resource":"*"}, + {"Effect":"Deny","Action":"bedrock:%s","Resource":"*"}]} + """.formatted(action)); + try (BedrockClient user = client(credentials.accessKeyId(), Region.US_EAST_1)) { + BedrockException denied = assertThrows(BedrockException.class, () -> { + switch (action) { + case "PutEnforcedGuardrailConfiguration" -> user.putEnforcedGuardrailConfiguration(r -> + r.configId(id).guardrailInferenceConfig(config(guardrail.guardrailId()))); + case "ListEnforcedGuardrailsConfiguration" -> user.listEnforcedGuardrailsConfiguration(ListEnforcedGuardrailsConfigurationRequest.builder().build()); + case "DeleteEnforcedGuardrailConfiguration" -> user.deleteEnforcedGuardrailConfiguration(r -> + r.configId(id)); + default -> throw new IllegalArgumentException(action); + } + }); + assertEquals("AccessDeniedException", denied.awsErrorDetails().errorCode()); + assertEquals(id, find(root, id).configId()); + } + } finally { + root.deleteEnforcedGuardrailConfiguration(r -> r.configId(id)); + root.deleteGuardrail(r -> r.guardrailIdentifier(guardrail.guardrailId())); + } + } + } + + @Test + void sdkPaginationReturnsEveryConfigurationOnce() { + try (BedrockClient root = client(ACCOUNT, Region.US_EAST_1)) { + CreateGuardrailResponse guardrail = create(root); + Set expected = new HashSet<>(); + try { + for (int i = 0; i < 3; i++) { + expected.add(root.putEnforcedGuardrailConfiguration(r -> + r.guardrailInferenceConfig(config(guardrail.guardrailId()))).configId()); + } + Set seen = new HashSet<>(); + String token = null; + for (int i = 0; i < 3; i++) { + ListEnforcedGuardrailsConfigurationResponse page = root.listEnforcedGuardrailsConfiguration( + ListEnforcedGuardrailsConfigurationRequest.builder().nextToken(token).build()); + assertEquals(1, page.guardrailsConfig().size()); + assertTrue(seen.add(page.guardrailsConfig().getFirst().configId())); + token = page.nextToken(); + } + assertNull(token); + assertEquals(expected, seen); + } finally { + for (String id : expected) { + root.deleteEnforcedGuardrailConfiguration(r -> r.configId(id)); + } + root.deleteGuardrail(r -> r.guardrailIdentifier(guardrail.guardrailId())); + } + } + } + + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void configuredGuardrailDeletionReturnsTheModeledErrorOverTheSdk(boolean wholeGuardrail) { + try (BedrockClient root = client(ACCOUNT, Region.US_EAST_1)) { + CreateGuardrailResponse guardrail = create(root); + String id = root.putEnforcedGuardrailConfiguration(r -> + r.guardrailInferenceConfig(config(guardrail.guardrailArn()))).configId(); + try { + BedrockException error = assertThrows(BedrockException.class, + () -> root.deleteGuardrail(r -> r.guardrailIdentifier(guardrail.guardrailArn()) + .guardrailVersion(wholeGuardrail ? null : "1"))); + assertEquals("ValidationException", error.awsErrorDetails().errorCode()); + assertEquals(400, error.statusCode()); + assertEquals("The guardrail cannot be deleted because it is associated with an account-level " + + "or organization-level default guardrail configuration.", error.awsErrorDetails().errorMessage()); + assertEquals(guardrail.guardrailId(), root.getGuardrail(r -> + r.guardrailIdentifier(guardrail.guardrailId()).guardrailVersion("1")).guardrailId()); + assertEquals(guardrail.guardrailId(), root.getGuardrail(r -> + r.guardrailIdentifier(guardrail.guardrailId()).guardrailVersion("DRAFT")).guardrailId()); + assertEquals(id, find(root, id).configId()); + } finally { + root.deleteEnforcedGuardrailConfiguration(r -> r.configId(id)); + root.deleteGuardrail(r -> r.guardrailIdentifier(guardrail.guardrailId())); + } + } + } + + @Test + void unknownConfigurationDeletionReturnsTheModeledMessageOverTheSdk() { + try (BedrockClient root = client(ACCOUNT, Region.US_EAST_1)) { + String missingId = UUID.randomUUID().toString().replace("-", ""); + BedrockException error = assertThrows(BedrockException.class, + () -> root.deleteEnforcedGuardrailConfiguration(r -> r.configId(missingId))); + assertEquals("ResourceNotFoundException", error.awsErrorDetails().errorCode()); + assertEquals(404, error.statusCode()); + assertEquals("No default guardrail configuration found for the specified config identifier.", + error.awsErrorDetails().errorMessage()); + } + } + + private static BedrockClient client(String accessKey, Region region) { + return AwsTestClients.create(BedrockClient.builder(), accessKey, region); + } + + private static CreateGuardrailResponse create(BedrockClient client) { + CreateGuardrailResponse created = client.createGuardrail(r -> r.name("enforced-sdk-" + UUID.randomUUID()) + .blockedInputMessaging("blocked").blockedOutputsMessaging("blocked")); + client.createGuardrailVersion(r -> r.guardrailIdentifier(created.guardrailId())); + return created; + } + + private static AccountEnforcedGuardrailInferenceInputConfiguration config(String identifier) { + return AccountEnforcedGuardrailInferenceInputConfiguration.builder() + .guardrailIdentifier(identifier).guardrailVersion("1").build(); + } + + private static AccountEnforcedGuardrailOutputConfiguration find(BedrockClient client, String id) { + return client.listEnforcedGuardrailsConfiguration(ListEnforcedGuardrailsConfigurationRequest.builder().build()).guardrailsConfig().stream() + .filter(c -> c.configId().equals(id)).findFirst().orElseThrow(); + } +} diff --git a/src/test/java/io/floci/aws/services/bedrock/BedrockEnforcedGuardrailWalTest.java b/src/test/java/io/floci/aws/services/bedrock/BedrockEnforcedGuardrailWalTest.java new file mode 100644 index 0000000000..26cc9b33a1 --- /dev/null +++ b/src/test/java/io/floci/aws/services/bedrock/BedrockEnforcedGuardrailWalTest.java @@ -0,0 +1,204 @@ +package io.floci.aws.services.bedrock; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.storage.AccountAwareStorageBackend; +import io.floci.aws.core.storage.InMemoryStorage; +import io.floci.aws.core.storage.WalStorage; +import io.floci.aws.services.bedrock.model.EnforcedGuardrailConfiguration; +import io.floci.aws.services.bedrock.model.Guardrail; +import io.floci.aws.services.kms.KmsService; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Instant; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; + +class BedrockEnforcedGuardrailWalTest { + + private static final String ACCOUNT = "741623800038"; + private static final String REGION = "us-east-1"; + private static final String OTHER_REGION = "eu-west-1"; + private static final String CALLER = "arn:aws:iam::" + ACCOUNT + ":user/first"; + private static final String OTHER_CALLER = "arn:aws:iam::" + ACCOUNT + ":user/second"; + private static final String SNAPSHOT = "bedrock-enforced-guardrail-configurations.json"; + private static final String LOG = "bedrock-enforced-guardrail-configurations.wal"; + + @TempDir + Path directory; + + private final ObjectMapper mapper = new ObjectMapper(); + private final InMemoryStorage guardrails = new InMemoryStorage<>(); + + @Test + void gracefulReopenPreservesReplacementMetadataAndDeletion() { + WalStorage raw = open(directory); + String id; + Instant created; + try { + BedrockService service = service(raw, ACCOUNT); + String guardrail = versionedGuardrail(service); + EnforcedGuardrailConfiguration configuration = service.putEnforcedGuardrailConfiguration( + request(guardrail, "1"), CALLER, REGION); + id = configuration.getConfigId(); + created = configuration.getCreatedAt(); + service.createGuardrailVersion(guardrail, null, REGION); + service.putEnforcedGuardrailConfiguration(request(guardrail, "2").put("configId", id), OTHER_CALLER, REGION); + } finally { + raw.shutdown(); + } + raw = open(directory); + try { + BedrockService service = service(raw, ACCOUNT); + EnforcedGuardrailConfiguration recovered = configurations(service, REGION).getFirst(); + assertEquals(id, recovered.getConfigId()); + assertEquals("2", recovered.getGuardrailVersion()); + assertEquals(created, recovered.getCreatedAt()); + assertEquals(CALLER, recovered.getCreatedBy()); + assertEquals(OTHER_CALLER, recovered.getUpdatedBy()); + assertEquals("ALL", recovered.getModelEnforcement().path("includedModels").get(0).asText()); + assertEquals("SELECTIVE", recovered.getSelectiveContentGuarding().path("system").asText()); + service.deleteEnforcedGuardrailConfiguration(id, REGION); + } finally { + raw.shutdown(); + } + raw = open(directory); + try { + assertTrue(configurations(service(raw, ACCOUNT), REGION).isEmpty()); + assertFalse(raw.get(ACCOUNT + "/" + REGION + "::" + id).isPresent()); + } finally { + raw.shutdown(); + } + } + + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void copiedSnapshotAndLogRecoverUpdatesAndDeletesWithoutCompactingTheSource(boolean snapshotFirst) throws Exception { + Path recoveredDirectory = directory.resolve("recovered"); + Files.createDirectory(recoveredDirectory); + WalStorage raw = open(directory); + String retained; + String deleted; + String otherRegion; + String guardrail; + try { + BedrockService service = service(raw, ACCOUNT); + guardrail = versionedGuardrail(service); + retained = service.putEnforcedGuardrailConfiguration(request(guardrail, "1"), CALLER, REGION).getConfigId(); + deleted = service.putEnforcedGuardrailConfiguration(request(guardrail, "1"), CALLER, REGION).getConfigId(); + if (snapshotFirst) { + raw.flush(); + } + service.createGuardrailVersion(guardrail, null, REGION); + service.putEnforcedGuardrailConfiguration(request(guardrail, "2").put("configId", retained), OTHER_CALLER, REGION); + service.deleteEnforcedGuardrailConfiguration(deleted, REGION); + EnforcedGuardrailConfiguration foreign = new EnforcedGuardrailConfiguration(); + foreign.setConfigId("foreign1"); + raw.put("111122223333/" + REGION + "::foreign1", foreign); + service.createGuardrail(requestForGuardrail("west"), OTHER_REGION); + Guardrail west = service.listGuardrails(null, null, null, OTHER_REGION).items().getFirst(); + service.createGuardrailVersion(west.getGuardrailId(), null, OTHER_REGION); + otherRegion = service.putEnforcedGuardrailConfiguration(request(west.getGuardrailId(), "1"), CALLER, + OTHER_REGION).getConfigId(); + for (String name : List.of(SNAPSHOT, LOG)) { + Path source = directory.resolve(name); + if (Files.exists(source)) { + Files.copy(source, recoveredDirectory.resolve(name)); + } + } + assertTrue(Files.size(recoveredDirectory.resolve(LOG)) > 0); + } finally { + raw.shutdown(); + } + raw = open(recoveredDirectory); + try { + BedrockService service = service(raw, ACCOUNT); + List east = configurations(service, REGION); + assertEquals(1, east.size()); + assertEquals(retained, east.getFirst().getConfigId()); + assertEquals("2", east.getFirst().getGuardrailVersion()); + assertEquals(OTHER_CALLER, east.getFirst().getUpdatedBy()); + assertEquals(otherRegion, configurations(service, OTHER_REGION).getFirst().getConfigId()); + assertEquals("foreign1", configurations(service(raw, "111122223333"), REGION).getFirst().getConfigId()); + assertFalse(raw.get(ACCOUNT + "/" + REGION + "::" + deleted).isPresent()); + } finally { + raw.shutdown(); + } + } + + @Test + void originalActJsonSnapshotKeepsItsIdentifiersAndCanBeDeletedAcrossReopen() throws Exception { + Files.writeString(directory.resolve(SNAPSHOT), """ + {"741623800038/us-east-1::legacy123": { + "configId":"legacy123", "guardrailId":"guardrail123", + "guardrailArn":"arn:aws:bedrock:us-east-1:741623800038:guardrail/guardrail123", + "guardrailVersion":"3", "selectiveContentGuarding":{"system":"SELECTIVE"}, + "modelEnforcement":{"includedModels":["ALL"],"excludedModels":[]}, + "createdAt":"2026-01-01T00:00:00Z", "createdBy":"arn:aws:iam::741623800038:user/first", + "updatedAt":"2026-01-02T00:00:00Z", "updatedBy":"arn:aws:iam::741623800038:user/second" + }} + """); + WalStorage raw = open(directory); + try { + BedrockService service = service(raw, ACCOUNT); + EnforcedGuardrailConfiguration old = configurations(service, REGION).getFirst(); + assertEquals("legacy123", old.getConfigId()); + assertEquals("guardrail123", old.getGuardrailId()); + assertEquals("3", old.getGuardrailVersion()); + assertEquals(Instant.parse("2026-01-01T00:00:00Z"), old.getCreatedAt()); + assertEquals(CALLER, old.getCreatedBy()); + assertEquals(OTHER_CALLER, old.getUpdatedBy()); + assertTrue(configurations(service, OTHER_REGION).isEmpty()); + assertTrue(configurations(service(raw, "111122223333"), REGION).isEmpty()); + service.deleteEnforcedGuardrailConfiguration("legacy123", REGION); + } finally { + raw.shutdown(); + } + raw = open(directory); + try { + assertTrue(configurations(service(raw, ACCOUNT), REGION).isEmpty()); + } finally { + raw.shutdown(); + } + } + + private WalStorage open(Path path) { + WalStorage raw = new WalStorage<>(path.resolve(SNAPSHOT), + path.resolve(LOG), new TypeReference<>() {}, 600000); + raw.load(); + return raw; + } + + private BedrockService service(WalStorage raw, String account) { + return new BedrockService(guardrails, new InMemoryStorage<>(), new InMemoryStorage<>(), + new AccountAwareStorageBackend<>(raw, null, account), new RegionResolver(REGION, account), + mapper, mock(KmsService.class)); + } + + private String versionedGuardrail(BedrockService service) { + return BedrockEnforcedGuardrailFixtures.publish(service, REGION, requestForGuardrail("east")).getGuardrailId(); + } + + private ObjectNode requestForGuardrail(String name) { + return BedrockEnforcedGuardrailFixtures.guardrailRequest(mapper, name, "blocked", "blocked"); + } + + private ObjectNode request(String identifier, String version) { + return BedrockEnforcedGuardrailFixtures.selectiveRequest(mapper, identifier, version); + } + + private static List configurations(BedrockService service, String region) { + return service.listEnforcedGuardrailConfigurations(null, region).items(); + } +} diff --git a/src/test/java/io/floci/aws/services/bedrock/BedrockGuardrailCreateNameConcurrencyTest.java b/src/test/java/io/floci/aws/services/bedrock/BedrockGuardrailCreateNameConcurrencyTest.java index f7b7378091..7a71e1e2ab 100644 --- a/src/test/java/io/floci/aws/services/bedrock/BedrockGuardrailCreateNameConcurrencyTest.java +++ b/src/test/java/io/floci/aws/services/bedrock/BedrockGuardrailCreateNameConcurrencyTest.java @@ -33,7 +33,7 @@ class BedrockGuardrailCreateNameConcurrencyTest { private static void overlappingCreates(boolean sameName) throws Exception { ParkingStore storage = new ParkingStore<>(); ObjectMapper mapper = new ObjectMapper(); - BedrockService service = new BedrockService(storage, new InMemoryStorage<>(), new InMemoryStorage<>(), + BedrockService service = new BedrockService(storage, new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new RegionResolver("us-east-1", "000000000000"), mapper, mock(KmsService.class)); AtomicReference firstResult = new AtomicReference<>(); AtomicReference secondResult = new AtomicReference<>(); diff --git a/src/test/java/io/floci/aws/services/bedrock/BedrockGuardrailLifecycleConcurrencyTest.java b/src/test/java/io/floci/aws/services/bedrock/BedrockGuardrailLifecycleConcurrencyTest.java index c47ecad6ba..68624d4432 100644 --- a/src/test/java/io/floci/aws/services/bedrock/BedrockGuardrailLifecycleConcurrencyTest.java +++ b/src/test/java/io/floci/aws/services/bedrock/BedrockGuardrailLifecycleConcurrencyTest.java @@ -43,7 +43,7 @@ class BedrockGuardrailLifecycleConcurrencyTest { private static void overlappingWrite(Write operation) throws Exception { ParkingStore storage = new ParkingStore<>(); ObjectMapper mapper = new ObjectMapper(); - BedrockService service = new BedrockService(storage, new InMemoryStorage<>(), new InMemoryStorage<>(), + BedrockService service = new BedrockService(storage, new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new RegionResolver(REGION, "000000000000"), mapper, mock(KmsService.class)); ObjectNode request = mapper.createObjectNode().put("name", "lifecycle") .put("blockedInputMessaging", "blocked").put("blockedOutputsMessaging", "blocked"); diff --git a/src/test/java/io/floci/aws/services/bedrock/BedrockOriginalEnforcedGuardrailIntegrationTest.java b/src/test/java/io/floci/aws/services/bedrock/BedrockOriginalEnforcedGuardrailIntegrationTest.java new file mode 100644 index 0000000000..444f0e2ea4 --- /dev/null +++ b/src/test/java/io/floci/aws/services/bedrock/BedrockOriginalEnforcedGuardrailIntegrationTest.java @@ -0,0 +1,143 @@ +package io.floci.aws.services.bedrock; + +import io.floci.aws.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.specification.RequestSpecification; +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.empty; +import static org.hamcrest.Matchers.endsWith; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.matchesPattern; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; + +@QuarkusTest +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class BedrockOriginalEnforcedGuardrailIntegrationTest { + + /** ISO-8601 date-time: the {@code Timestamp} shape of the Bedrock model. */ + private static final String ISO_8601 = "\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z"; + + private static String guardrailId; + private static String guardrailArn; + private static String configId; + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + /** Signs as the same access key in the given Region, so only the Region differs between calls. */ + private static RequestSpecification inRegion(String region) { + return given() + .contentType("application/json") + .header("Authorization", "AWS4-HMAC-SHA256 Credential=test/20260101/" + region + + "/bedrock/aws4_request, SignedHeaders=host, Signature=abc"); + } + + @Test + @Order(1) + void createGuardrailWithAVersion() { + guardrailId = inRegion("us-east-1") + .body(""" + {"name": "enforced-port-1532", "blockedInputMessaging": "no", "blockedOutputsMessaging": "no"} + """) + .when() + .post("/guardrails") + .then() + .statusCode(202) + .extract().path("guardrailId"); + guardrailArn = inRegion("us-east-1").when().get("/guardrails/" + guardrailId).then().extract().path("guardrailArn"); + + inRegion("us-east-1").body("{}").when().post("/guardrails/" + guardrailId).then().statusCode(202) + .body("version", equalTo("1")); + } + + @Test + @Order(2) + void putCreatesAConfiguration() { + configId = inRegion("us-east-1") + .body(""" + {"guardrailInferenceConfig": { + "guardrailIdentifier": "%s", + "guardrailVersion": "1", + "selectiveContentGuarding": {"system": "SELECTIVE", "messages": "COMPREHENSIVE"}, + "modelEnforcement": {"includedModels": ["ALL"], "excludedModels": []} + }} + """.formatted(guardrailArn)) + .when() + .put("/enforcedGuardrailsConfiguration") + .then() + .statusCode(200) + .body("configId", matchesPattern("[a-z0-9]+")) + .body("updatedAt", matchesPattern(ISO_8601)) + .body("updatedBy", endsWith(":root")) + .extract().path("configId"); + } + + @Test + @Order(3) + void listReturnsTheConfigurationWithTheUnversionedGuardrailArn() { + inRegion("us-east-1") + .when() + .get("/enforcedGuardrailsConfiguration") + .then() + .statusCode(200) + .body("guardrailsConfig", hasSize(1)) + .body("guardrailsConfig[0].configId", equalTo(configId)) + .body("guardrailsConfig[0].guardrailArn", equalTo(guardrailArn)) + .body("guardrailsConfig[0].guardrailId", equalTo(guardrailId)) + .body("guardrailsConfig[0].guardrailVersion", equalTo("1")) + .body("guardrailsConfig[0].selectiveContentGuarding.system", equalTo("SELECTIVE")) + .body("guardrailsConfig[0].modelEnforcement.includedModels[0]", equalTo("ALL")) + .body("guardrailsConfig[0].modelEnforcement.excludedModels", empty()) + .body("guardrailsConfig[0].createdAt", matchesPattern(ISO_8601)) + .body("guardrailsConfig[0].createdBy", notNullValue()) + .body("guardrailsConfig[0].updatedAt", matchesPattern(ISO_8601)) + .body("guardrailsConfig[0].owner", equalTo("ACCOUNT")) + .body("nextToken", nullValue()); + } + + @Test + @Order(4) + void anotherRegionListsNoConfiguration() { + inRegion("eu-west-1") + .when() + .get("/enforcedGuardrailsConfiguration") + .then() + .statusCode(200) + .body("guardrailsConfig", empty()); + } + + @Test + @Order(5) + void putRejectsTheDraftVersion() { + inRegion("us-east-1") + .body(""" + {"guardrailInferenceConfig": {"guardrailIdentifier": "%s", "guardrailVersion": "DRAFT"}} + """.formatted(guardrailId)) + .when() + .put("/enforcedGuardrailsConfiguration") + .then() + .statusCode(400) + .body("__type", equalTo("ValidationException")); + } + + @Test + @Order(6) + void deleteRemovesTheConfigurationOnce() { + inRegion("us-east-1").when().delete("/enforcedGuardrailsConfiguration/" + configId).then().statusCode(200); + + inRegion("us-east-1").when().get("/enforcedGuardrailsConfiguration").then() + .body("guardrailsConfig", empty()); + inRegion("us-east-1").when().delete("/enforcedGuardrailsConfiguration/" + configId).then() + .statusCode(404); + } +} diff --git a/src/test/java/io/floci/aws/services/bedrock/BedrockServiceTest.java b/src/test/java/io/floci/aws/services/bedrock/BedrockServiceTest.java index 0c8a401119..3ee652ccc5 100644 --- a/src/test/java/io/floci/aws/services/bedrock/BedrockServiceTest.java +++ b/src/test/java/io/floci/aws/services/bedrock/BedrockServiceTest.java @@ -7,6 +7,7 @@ import io.floci.aws.core.common.AwsException; import io.floci.aws.core.common.PaginatedResult; import io.floci.aws.core.common.RegionResolver; import io.floci.aws.core.storage.InMemoryStorage; +import io.floci.aws.services.bedrock.model.EnforcedGuardrailConfiguration; import io.floci.aws.services.bedrock.model.Guardrail; import io.floci.aws.services.kms.KmsService; import io.floci.aws.services.kms.model.KmsKey; @@ -18,6 +19,7 @@ import java.util.List; import java.util.Map; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; @@ -40,7 +42,7 @@ class BedrockServiceTest { @BeforeEach void setUp() { kmsService = mock(KmsService.class); - service = new BedrockService(new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), + service = new BedrockService(new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new RegionResolver(REGION, ACCOUNT), mapper, kmsService); } @@ -646,4 +648,153 @@ class BedrockServiceTest { assertEquals("ResourceNotFoundException", put.getErrorCode(), arn); } } + private static final String CALLER = "arn:aws:iam::" + ACCOUNT + ":user/admin"; + + private ObjectNode enforcedConfigRequest(String guardrailIdentifier, String version) { + return BedrockEnforcedGuardrailFixtures.request(mapper, guardrailIdentifier, version); + } + + private Guardrail publishedGuardrail(String name) { + return BedrockEnforcedGuardrailFixtures.publish(service, REGION, createRequest(name)); + } + + @Test + void enforcedConfigurationRecordsTheGuardrailVersionAndCaller() { + Guardrail version = publishedGuardrail("enforced"); + ObjectNode request = enforcedConfigRequest(version.getGuardrailId(), "1"); + ObjectNode inferenceConfig = (ObjectNode) request.get("guardrailInferenceConfig"); + inferenceConfig.putObject("selectiveContentGuarding").put("system", "SELECTIVE").put("messages", "COMPREHENSIVE"); + ObjectNode modelEnforcement = inferenceConfig.putObject("modelEnforcement"); + modelEnforcement.putArray("includedModels").add("ALL"); + modelEnforcement.putArray("excludedModels").add("anthropic.claude-v2"); + + EnforcedGuardrailConfiguration created = service.putEnforcedGuardrailConfiguration(request, CALLER, REGION); + + assertTrue(created.getConfigId().matches("[a-z0-9]+"), created.getConfigId()); + List listed = service.listEnforcedGuardrailConfigurations(null, REGION).items(); + assertEquals(1, listed.size()); + EnforcedGuardrailConfiguration stored = listed.get(0); + assertEquals(created.getConfigId(), stored.getConfigId()); + assertEquals(version.getGuardrailId(), stored.getGuardrailId()); + assertEquals(version.getGuardrailArn(), stored.getGuardrailArn()); + assertEquals("1", stored.getGuardrailVersion()); + assertEquals("SELECTIVE", stored.getSelectiveContentGuarding().get("system").asText()); + assertEquals("ALL", stored.getModelEnforcement().get("includedModels").get(0).asText()); + assertEquals(CALLER, stored.getCreatedBy()); + assertEquals(CALLER, stored.getUpdatedBy()); + assertNotNull(stored.getCreatedAt()); + } + + @Test + void enforcedConfigurationAcceptsTheGuardrailArnAsIdentifier() { + Guardrail version = publishedGuardrail("enforced-by-arn"); + + EnforcedGuardrailConfiguration created = service.putEnforcedGuardrailConfiguration( + enforcedConfigRequest(version.getGuardrailArn(), "1"), CALLER, REGION); + + assertEquals(version.getGuardrailId(), created.getGuardrailId()); + } + + @Test + void putWithAConfigIdReplacesThatConfigurationAndKeepsItsCreator() { + Guardrail version = publishedGuardrail("enforced-update"); + service.createGuardrailVersion(version.getGuardrailId(), null, REGION); + EnforcedGuardrailConfiguration created = service.putEnforcedGuardrailConfiguration( + enforcedConfigRequest(version.getGuardrailId(), "1"), CALLER, REGION); + + ObjectNode update = enforcedConfigRequest(version.getGuardrailId(), "2"); + update.put("configId", created.getConfigId()); + String otherCaller = "arn:aws:iam::" + ACCOUNT + ":role/ops"; + service.putEnforcedGuardrailConfiguration(update, otherCaller, REGION); + + List listed = service.listEnforcedGuardrailConfigurations(null, REGION).items(); + assertEquals(1, listed.size()); + assertEquals("2", listed.get(0).getGuardrailVersion()); + assertEquals(CALLER, listed.get(0).getCreatedBy()); + assertEquals(otherCaller, listed.get(0).getUpdatedBy()); + } + + @Test + void enforcedConfigurationRejectsTheDraftVersion() { + Guardrail draft = create("enforced-draft"); + + AwsException e = assertThrows(AwsException.class, () -> service.putEnforcedGuardrailConfiguration( + enforcedConfigRequest(draft.getGuardrailId(), BedrockService.DRAFT_VERSION), CALLER, REGION)); + assertEquals("ValidationException", e.getErrorCode()); + } + + @Test + void enforcedConfigurationRejectsAVersionTheGuardrailDoesNotHold() { + Guardrail version = publishedGuardrail("enforced-missing-version"); + + AwsException e = assertThrows(AwsException.class, () -> service.putEnforcedGuardrailConfiguration( + enforcedConfigRequest(version.getGuardrailId(), "7"), CALLER, REGION)); + assertEquals("ResourceNotFoundException", e.getErrorCode()); + } + + @Test + void putWithAnUnknownConfigIdIsNotFound() { + Guardrail version = publishedGuardrail("enforced-unknown-config"); + ObjectNode request = enforcedConfigRequest(version.getGuardrailId(), "1"); + request.put("configId", "doesnotexist"); + + AwsException e = assertThrows(AwsException.class, + () -> service.putEnforcedGuardrailConfiguration(request, CALLER, REGION)); + assertEquals("ResourceNotFoundException", e.getErrorCode()); + } + + @Test + void enforcedConfigurationRejectsAnIncompleteModelEnforcementAndAnUnknownGuardingMode() { + Guardrail version = publishedGuardrail("enforced-invalid"); + ObjectNode noIncludedModels = enforcedConfigRequest(version.getGuardrailId(), "1"); + ((ObjectNode) noIncludedModels.get("guardrailInferenceConfig")).putObject("modelEnforcement") + .putArray("excludedModels"); + ObjectNode unknownMode = enforcedConfigRequest(version.getGuardrailId(), "1"); + ((ObjectNode) unknownMode.get("guardrailInferenceConfig")).putObject("selectiveContentGuarding") + .put("system", "SOMETIMES"); + + assertEquals("ValidationException", assertThrows(AwsException.class, + () -> service.putEnforcedGuardrailConfiguration(noIncludedModels, CALLER, REGION)).getErrorCode()); + assertEquals("ValidationException", assertThrows(AwsException.class, + () -> service.putEnforcedGuardrailConfiguration(unknownMode, CALLER, REGION)).getErrorCode()); + } + + @Test + void enforcedConfigurationsAreScopedToTheirRegion() { + Guardrail version = publishedGuardrail("enforced-regional"); + service.putEnforcedGuardrailConfiguration(enforcedConfigRequest(version.getGuardrailId(), "1"), CALLER, REGION); + + assertTrue(service.listEnforcedGuardrailConfigurations(null, "eu-west-1").items().isEmpty()); + } + + @Test + void enforcedConfigurationsAreListedOnePerPage() { + Guardrail version = publishedGuardrail("enforced-paged"); + service.putEnforcedGuardrailConfiguration(enforcedConfigRequest(version.getGuardrailId(), "1"), CALLER, REGION); + service.putEnforcedGuardrailConfiguration(enforcedConfigRequest(version.getGuardrailId(), "1"), CALLER, REGION); + + PaginatedResult first = service.listEnforcedGuardrailConfigurations(null, REGION); + PaginatedResult second = + service.listEnforcedGuardrailConfigurations(first.nextToken(), REGION); + + assertEquals(1, first.items().size()); + assertNotNull(first.nextToken()); + assertEquals(1, second.items().size()); + assertNull(second.nextToken()); + assertNotEquals(first.items().get(0).getConfigId(), second.items().get(0).getConfigId()); + } + + @Test + void deletingAnEnforcedConfigurationRemovesItOnce() { + Guardrail version = publishedGuardrail("enforced-delete"); + String configId = service.putEnforcedGuardrailConfiguration( + enforcedConfigRequest(version.getGuardrailId(), "1"), CALLER, REGION).getConfigId(); + + service.deleteEnforcedGuardrailConfiguration(configId, REGION); + + assertTrue(service.listEnforcedGuardrailConfigurations(null, REGION).items().isEmpty()); + AwsException e = assertThrows(AwsException.class, + () -> service.deleteEnforcedGuardrailConfiguration(configId, REGION)); + assertEquals("ResourceNotFoundException", e.getErrorCode()); + } }