feat(bedrock): add PutResourcePolicy, GetResourcePolicy and DeleteResourcePolicy for guardrails (#7188)

This commit is contained in:
galsuchetzky-act authored and GitHub committed 2026-11-01 08:23:49 -04:00
1 parent 6b3f482510
commit b987e822be
14 files changed
+612 -5

No files matched your search

@@ -0,0 +1,90 @@
package io.github.hectorvent.floci.services.bedrock;
import io.github.hectorvent.floci.testing.AwsTestClients;
import io.github.hectorvent.floci.testing.EnforcementFixtures;
import io.github.hectorvent.floci.testing.IamEnforcementProfile;
import io.github.hectorvent.floci.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.api.function.Executable;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.bedrock.BedrockClient;
import software.amazon.awssdk.services.bedrock.model.BedrockException;
import software.amazon.awssdk.services.bedrock.model.CreateGuardrailResponse;
import java.util.List;
import java.util.UUID;
import static io.github.hectorvent.floci.testing.EnforcementFixtures.auth;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
/** The resource policy actions are checked against the guardrail their {@code resourceArn} names. */
@QuarkusTest
@TestProfile(IamEnforcementProfile.class)
class BedrockResourcePolicyIamEnforcementIntegrationTest {
private static final String ACCOUNT = "000000000000";
@RegisterExtension
final PartitionCleanup cleanup = new PartitionCleanup();
@Test
void aDenyOnOneGuardrailRefusesThePolicyActionsOnItAndNotOnAnother() {
try (BedrockClient root = AwsTestClients.create(BedrockClient.builder(), ACCOUNT, Region.US_EAST_1)) {
CreateGuardrailResponse denied = create(root);
CreateGuardrailResponse allowed = create(root);
try {
String userName = "bedrock-policy-" + 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:PutResourcePolicy","bedrock:GetResourcePolicy",
"bedrock:DeleteResourcePolicy"],"Resource":"%s"}]}"""
.formatted(denied.guardrailArn()));
try (BedrockClient user = AwsTestClients.create(BedrockClient.builder(), credentials.accessKeyId(),
Region.US_EAST_1)) {
String allowedArn = allowed.guardrailArn();
String allowedPolicy = policy(allowedArn);
assertDoesNotThrow(() -> user.putResourcePolicy(r -> r.resourceArn(allowedArn)
.resourcePolicy(allowedPolicy)));
assertEquals(allowedPolicy, user.getResourcePolicy(r -> r.resourceArn(allowedArn)).resourcePolicy());
assertDoesNotThrow(() -> user.deleteResourcePolicy(r -> r.resourceArn(allowedArn)));
String deniedArn = denied.guardrailArn();
String deniedPolicy = policy(deniedArn);
root.putResourcePolicy(r -> r.resourceArn(deniedArn).resourcePolicy(deniedPolicy));
List<Executable> refused = List.of(
() -> user.putResourcePolicy(r -> r.resourceArn(deniedArn).resourcePolicy(deniedPolicy)),
() -> user.getResourcePolicy(r -> r.resourceArn(deniedArn)),
() -> user.deleteResourcePolicy(r -> r.resourceArn(deniedArn)));
for (Executable call : refused) {
BedrockException error = assertThrows(BedrockException.class, call);
assertEquals("AccessDeniedException", error.awsErrorDetails().errorCode());
}
assertEquals(deniedPolicy, root.getResourcePolicy(r -> r.resourceArn(deniedArn)).resourcePolicy());
}
} finally {
root.deleteGuardrail(r -> r.guardrailIdentifier(denied.guardrailId()));
root.deleteGuardrail(r -> r.guardrailIdentifier(allowed.guardrailId()));
}
}
}
private static CreateGuardrailResponse create(BedrockClient client) {
return client.createGuardrail(r -> r.name("iam-rp-" + UUID.randomUUID())
.blockedInputMessaging("blocked").blockedOutputsMessaging("blocked"));
}
private static String policy(String guardrailArn) {
return """
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"AWS":"arn:aws:iam::%s:root"},\
"Action":"bedrock:ApplyGuardrail","Resource":"%s"}]}""".formatted(ACCOUNT, guardrailArn);
}
}
@@ -0,0 +1,172 @@
package io.github.hectorvent.floci.services.bedrock;
import io.github.hectorvent.floci.testing.AwsTestClients;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.Test;
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.BedrockException;
import software.amazon.awssdk.services.bedrock.model.CreateGuardrailResponse;
import software.amazon.awssdk.services.bedrock.model.PutResourcePolicyResponse;
import software.amazon.awssdk.services.bedrock.model.ResourceNotFoundException;
import software.amazon.awssdk.services.bedrock.model.ValidationException;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
@QuarkusTest
class BedrockResourcePolicyIntegrationTest {
private static final String ACCOUNT = "741623800011";
private static final String OTHER_ACCOUNT = "741623800012";
@Test
void putGetAndDeleteRoundTripOnAGuardrail() {
try (BedrockClient client = client(ACCOUNT, Region.US_EAST_1)) {
CreateGuardrailResponse created = create(client);
String arn = created.guardrailArn();
try {
assertNull(client.getResourcePolicy(r -> r.resourceArn(arn)).resourcePolicy());
String policy = rootPolicy(arn, "\"bedrock:ApplyGuardrail\",\"bedrock:GetGuardrail\"");
PutResourcePolicyResponse put =
client.putResourcePolicy(r -> r.resourceArn(arn).resourcePolicy(policy));
assertEquals(201, put.sdkHttpResponse().statusCode());
assertEquals(arn, put.resourceArn());
assertEquals(policy, client.getResourcePolicy(r -> r.resourceArn(arn)).resourcePolicy());
String organizationPolicy = organizationPolicy(arn);
client.putResourcePolicy(r -> r.resourceArn(arn).resourcePolicy(organizationPolicy));
assertEquals(organizationPolicy, client.getResourcePolicy(r -> r.resourceArn(arn)).resourcePolicy());
assertEquals(200, client.deleteResourcePolicy(r -> r.resourceArn(arn)).sdkHttpResponse().statusCode());
assertNull(client.getResourcePolicy(r -> r.resourceArn(arn)).resourcePolicy());
} finally {
client.deleteGuardrail(r -> r.guardrailIdentifier(created.guardrailId()));
}
}
}
@ParameterizedTest
@ValueSource(strings = {"not-json", "empty", "too-long", "no-statement", "deny", "other-resource",
"unsupported-action", "public-principal", "wildcard-organization", "other-account-principal",
"unsupported-condition", "trailing-content", "extra-principal", "org-paths-object"})
void aPolicyOutsideTheGuardrailPolicyLanguageIsRejected(String invalid) {
try (BedrockClient client = client(ACCOUNT, Region.US_EAST_1)) {
CreateGuardrailResponse created = create(client);
String arn = created.guardrailArn();
try {
String valid = rootPolicy(arn, "\"bedrock:ApplyGuardrail\"");
String policy = switch (invalid) {
case "not-json" -> "not json";
case "empty" -> "";
case "too-long" -> valid + " ".repeat(20481 - valid.length());
case "no-statement" -> "{\"Version\":\"2012-10-17\",\"Statement\":[]}";
case "deny" -> valid.replace("\"Allow\"", "\"Deny\"");
case "other-resource" -> valid.replace("\"Resource\":\"" + arn + "\"",
"\"Resource\":\"" + arn + "-other\"");
case "unsupported-action" -> rootPolicy(arn, "\"bedrock:InvokeModel\"");
case "public-principal" ->
valid.replace("{\"AWS\":\"arn:aws:iam::" + ACCOUNT + ":root\"}", "\"*\"");
case "wildcard-organization" -> organizationPolicy(arn).replace("o-exampleorgid", "o-*");
case "other-account-principal" -> valid.replace(ACCOUNT + ":root", OTHER_ACCOUNT + ":root");
case "trailing-content" -> valid + " {}";
case "extra-principal" -> valid.replace(ACCOUNT + ":root\"}",
ACCOUNT + ":root\",\"Service\":\"lambda.amazonaws.com\"}");
case "org-paths-object" -> organizationPolicy(arn).replace(
"[\"o-exampleorgid/*/ou-ab12-cdefgh34/*\"]", "{}");
default -> valid.replace("\"Resource\"",
"\"Condition\":{\"Bool\":{\"aws:SecureTransport\":\"true\"}},\"Resource\"");
};
ValidationException error = assertThrows(ValidationException.class,
() -> client.putResourcePolicy(r -> r.resourceArn(arn).resourcePolicy(policy)));
assertEquals(400, error.statusCode());
assertNull(client.getResourcePolicy(r -> r.resourceArn(arn)).resourcePolicy());
} finally {
client.deleteGuardrail(r -> r.guardrailIdentifier(created.guardrailId()));
}
}
}
@Test
void anArnNamingNoGuardrailIsNotFound() {
try (BedrockClient client = client(ACCOUNT, Region.US_EAST_1);
BedrockClient otherAccount = client(OTHER_ACCOUNT, Region.US_EAST_1)) {
String unknown = "arn:aws:bedrock:us-east-1:" + ACCOUNT + ":guardrail/0123456789ab";
String policy = rootPolicy(unknown, "\"bedrock:ApplyGuardrail\"");
assertEquals(404, assertThrows(ResourceNotFoundException.class,
() -> client.getResourcePolicy(r -> r.resourceArn(unknown))).statusCode());
assertEquals(404, assertThrows(ResourceNotFoundException.class,
() -> client.deleteResourcePolicy(r -> r.resourceArn(unknown))).statusCode());
BedrockException put = assertThrows(BedrockException.class,
() -> client.putResourcePolicy(r -> r.resourceArn(unknown).resourcePolicy(policy)));
assertEquals(404, put.statusCode());
assertEquals("ResourceNotFoundException", put.awsErrorDetails().errorCode());
String profile = "arn:aws:bedrock:us-east-1:" + ACCOUNT + ":guardrail-profile/us.guardrail.v1:0";
assertEquals(404, assertThrows(ResourceNotFoundException.class,
() -> client.getResourcePolicy(r -> r.resourceArn(profile))).statusCode());
CreateGuardrailResponse created = create(client);
try {
assertThrows(ResourceNotFoundException.class,
() -> otherAccount.getResourcePolicy(r -> r.resourceArn(created.guardrailArn())));
} finally {
client.deleteGuardrail(r -> r.guardrailIdentifier(created.guardrailId()));
}
}
}
@Test
void deletingTheGuardrailDeletesItsPolicy() {
try (BedrockClient client = client(ACCOUNT, Region.US_EAST_1)) {
String name = "rp-" + UUID.randomUUID();
CreateGuardrailResponse created = create(client, name);
String arn = created.guardrailArn();
String policy = rootPolicy(arn, "\"bedrock:ApplyGuardrail\"");
client.putResourcePolicy(r -> r.resourceArn(arn).resourcePolicy(policy));
client.deleteGuardrail(r -> r.guardrailIdentifier(created.guardrailId()));
assertThrows(ResourceNotFoundException.class, () -> client.getResourcePolicy(r -> r.resourceArn(arn)));
CreateGuardrailResponse recreated = create(client, name);
try {
assertNull(client.getResourcePolicy(r -> r.resourceArn(recreated.guardrailArn())).resourcePolicy());
} finally {
client.deleteGuardrail(r -> r.guardrailIdentifier(recreated.guardrailId()));
}
}
}
private static CreateGuardrailResponse create(BedrockClient client) {
return create(client, "rp-" + UUID.randomUUID());
}
private static CreateGuardrailResponse create(BedrockClient client, String name) {
return client.createGuardrail(r -> r.name(name)
.blockedInputMessaging("blocked").blockedOutputsMessaging("blocked"));
}
private static String rootPolicy(String resourceArn, String actions) {
return """
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"AWS":"arn:aws:iam::%s:root"},\
"Action":[%s],"Resource":"%s"}]}""".formatted(ACCOUNT, actions, resourceArn);
}
private static String organizationPolicy(String resourceArn) {
return """
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":"*",\
"Action":["bedrock:ApplyGuardrail","bedrock:GetGuardrail"],"Resource":"%s",\
"Condition":{"StringEquals":{"aws:PrincipalOrgID":"o-exampleorgid"},\
"ForAnyValue:StringLike":{"aws:PrincipalOrgPaths":["o-exampleorgid/*/ou-ab12-cdefgh34/*"]}}}]}"""
.formatted(resourceArn);
}
private static BedrockClient client(String account, Region region) {
return AwsTestClients.create(BedrockClient.builder(), account, region);
}
}
@@ -561,4 +561,43 @@ class BedrockServiceTest {
() -> service.getGuardrail(created.getGuardrailId(), null, "eu-west-1"));
assertTrue(service.listGuardrails(null, null, null, "eu-west-1").items().isEmpty());
}
private static String rootPolicy(String resourceArn, String action) {
return """
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
"Principal":{"AWS":"arn:aws:iam::%s:root"},"Action":"%s","Resource":"%s"}]}
""".formatted(ACCOUNT, action, resourceArn);
}
@Test
void guardrailResourcePolicyLivesOnTheDraftAndNotOnItsVersions() {
Guardrail created = create("with-policy");
String policy = rootPolicy(created.getGuardrailArn(), "bedrock:ApplyGuardrail");
assertNull(service.getResourcePolicy(created.getGuardrailArn(), REGION));
service.putResourcePolicy(created.getGuardrailArn(), policy, REGION);
Guardrail version = service.createGuardrailVersion(created.getGuardrailId(), null, REGION);
assertEquals(policy, service.getResourcePolicy(created.getGuardrailArn(), REGION));
assertNull(version.getResourcePolicy());
service.deleteResourcePolicy(created.getGuardrailArn(), REGION);
assertNull(service.getResourcePolicy(created.getGuardrailArn(), REGION));
}
@Test
void guardrailResourcePolicyIsFoundByItsExactArnOnly() {
Guardrail created = create("exact-arn");
String policy = rootPolicy(created.getGuardrailArn(), "bedrock:ApplyGuardrail");
for (String other : List.of(created.getGuardrailId(),
created.getGuardrailArn().replace(ACCOUNT, "111122223333"),
created.getGuardrailArn().replace(":guardrail/", ":custom-model/"),
"arn:aws:bedrock:" + REGION + ":" + ACCOUNT + ":guardrail-profile/us.guardrail.v1:0")) {
AwsException e = assertThrows(AwsException.class, () -> service.getResourcePolicy(other, REGION));
assertEquals("ResourceNotFoundException", e.getErrorCode(), other);
}
AwsException otherRegion = assertThrows(AwsException.class,
() -> service.putResourcePolicy(created.getGuardrailArn(), policy, "eu-west-1"));
assertEquals("ResourceNotFoundException", otherRegion.getErrorCode());
}
}
@@ -367,6 +367,21 @@ class IamActionRegistryTest {
assertEquals("lambda:DeleteResourcePolicy", lambdaAction("DELETE", "/2025-03-07/resource-policy/" + arn));
}
@Test
void bedrockResourcePolicyRoutesResolveToTheirActions() {
String arn = "arn%3Aaws%3Abedrock%3Aus-east-1%3A000000000000%3Aguardrail%2Fabc123def456";
assertEquals("bedrock:PutResourcePolicy", bedrockAction("POST", "/resource-policy"));
assertEquals("bedrock:GetResourcePolicy", bedrockAction("GET", "/resource-policy/" + arn));
assertEquals("bedrock:DeleteResourcePolicy", bedrockAction("DELETE", "/resource-policy/" + arn));
assertNull(bedrockAction("GET", "/resource-policy"));
assertNull(bedrockAction("POST", "/resource-policy/" + arn));
}
private String bedrockAction(String method, String path) {
return registry.resolveRoute("bedrock",
mockCtx(method, path, new MultivaluedHashMap<>(), MediaType.APPLICATION_JSON_TYPE, "{}"));
}
private String lambdaAction(String method, String path) {
return registry.resolveRoute("lambda",
mockCtx(method, path, new MultivaluedHashMap<>(), MediaType.APPLICATION_JSON_TYPE, "{}"));
@@ -1931,6 +1931,28 @@ class ResourceArnBuilderTest {
builder.buildResources("dsql", ctx, "polygondwanaland-west-1", "000000000000", "aws-cn"));
}
@Test
void bedrockResourcePolicyRoutesResolveTheArnTheyCarry() {
String guardrail = "arn:aws:bedrock:us-east-1:000000000000:guardrail/abc123def456";
for (String method : List.of("GET", "DELETE")) {
when(ctx.getMethod()).thenReturn(method);
when(uriInfo.getPath()).thenReturn("/resource-policy/" + guardrail);
assertEquals(List.of(guardrail), builder.buildResources("bedrock", ctx, "us-east-1", ACCOUNT), method);
}
when(ctx.getMethod()).thenReturn("POST");
when(uriInfo.getPath()).thenReturn("/resource-policy");
setJsonBody("{\"resourceArn\":\"" + guardrail + "\",\"resourcePolicy\":\"{}\"}");
assertEquals(List.of(guardrail), builder.buildResources("bedrock", ctx, "us-east-1", ACCOUNT));
// A value that is not an ARN, and every other Bedrock route, name no resource.
setJsonBody("{\"resourceArn\":\"abc123def456\",\"resourcePolicy\":\"{}\"}");
assertEquals(List.of("*"), builder.buildResources("bedrock", ctx, "us-east-1", ACCOUNT));
when(ctx.getMethod()).thenReturn("GET");
when(uriInfo.getPath()).thenReturn("/resource-policy/abc123def456");
assertEquals(List.of("*"), builder.buildResources("bedrock", ctx, "us-east-1", ACCOUNT));
when(uriInfo.getPath()).thenReturn("/guardrails/abc123def456");
assertEquals(List.of("*"), builder.buildResources("bedrock", ctx, "us-east-1", ACCOUNT));
}
@Test
void apiGatewayRoutesResolveThePathTheyNameWithNoAccount() {
request("/restapis/abc123/stages");