mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
feat(bedrock): store resource-based policies on guardrail profiles (#7208)
AWS lets a system-defined guardrail profile carry a resource-based
policy as well as a guardrail, and a guardrail with cross-Region
inference is shared only once each destination-Region profile ARN
carries one. The policy is stored in the Region whose endpoint
received PutResourcePolicy, under the ARN passed, so GetResourcePolicy
on a profile ARN through an endpoint that stored nothing returns {}.
A profile policy may allow only bedrock:ApplyGuardrail:
https://docs.aws.amazon.com/bedrock/latest/userguide/guardrails-resource-based-policies.html
PutResourcePolicy, GetResourcePolicy and DeleteResourcePolicy now
accept a guardrail-profile ARN. Its policy is stored per calling Region
and profile ARN, GetResourcePolicy returns {} when that pair holds
none, and DeleteResourcePolicy clears only that pair. PutResourcePolicy
holds the policy to the guardrail language with bedrock:ApplyGuardrail
as the only action. A profile ARN of another account or partition, or
whose profile id is not of the form <prefix>.guardrail.v<N>:<M>, is
ResourceNotFoundException. Which destination Regions are valid for the
calling Region is not checked, and the policy is not evaluated against
callers.
Closes #6671
This commit is contained in:
1 parent
0260a54ee2
commit
a69b3621a0
4 files changed
+166
-22
No files matched your search
@@ -17,9 +17,9 @@ that shares the same signing name: see [Bedrock Runtime](bedrock-runtime.md).
|
||||
| `CreateGuardrailVersion` | Snapshot the `DRAFT` under the next numerical version |
|
||||
| `DeleteGuardrail` | Delete one numerical version, or the guardrail and all its versions |
|
||||
| `ListGuardrails` | List every guardrail's `DRAFT`, or every version of one guardrail |
|
||||
| `PutResourcePolicy` | Attach a resource-based policy to a guardrail (`POST /resource-policy`) |
|
||||
| `GetResourcePolicy` | Read a guardrail's resource-based policy |
|
||||
| `DeleteResourcePolicy` | Remove a guardrail's resource-based policy |
|
||||
| `PutResourcePolicy` | Attach a resource-based policy to a guardrail or a guardrail profile (`POST /resource-policy`) |
|
||||
| `GetResourcePolicy` | Read the resource-based policy of a guardrail or a guardrail profile |
|
||||
| `DeleteResourcePolicy` | Remove the resource-based policy of a guardrail or a guardrail profile |
|
||||
| `TagResource` | Tag a guardrail (`POST /tagResource`) |
|
||||
| `UntagResource` | Remove tags from a guardrail (`POST /untagResource`) |
|
||||
| `ListTagsForResource` | List a guardrail's tags (`POST /listTagsForResource`) |
|
||||
@@ -70,11 +70,13 @@ request, so `CreateGuardrail` and `TagResource` both raise `TooManyTagsException
|
||||
the resulting total would pass 50. Replacing the value of a tag key the guardrail
|
||||
already carries does not add to that total.
|
||||
|
||||
A resource-based policy is attached to a guardrail by its full ARN. The policy is held to the restricted language the
|
||||
A resource-based policy is attached to a guardrail or a system-defined guardrail profile
|
||||
by its full ARN. The policy is held to the restricted language the
|
||||
[Bedrock user guide](https://docs.aws.amazon.com/bedrock/latest/userguide/guardrails-resource-based-policies.html)
|
||||
documents, and anything else is rejected with `ValidationException`: it is one JSON object
|
||||
of 1 to 20480 characters with nothing after it, every statement is an `Allow` on the ARN the policy is attached to,
|
||||
its actions are `bedrock:ApplyGuardrail` and `bedrock:GetGuardrail`, and its principal is either the
|
||||
its actions are `bedrock:ApplyGuardrail` and `bedrock:GetGuardrail` (only
|
||||
`bedrock:ApplyGuardrail` on a guardrail profile), and its principal is either the
|
||||
account root (`{"AWS": "arn:aws:iam::<account>:root"}` and no other principal) or `*` under a `StringEquals` condition on
|
||||
`aws:PrincipalOrgID`. The only conditions accepted are that one and
|
||||
`ForAnyValue:StringLike` on `aws:PrincipalOrgPaths`, each with a string or an array of strings. The policy is stored as given; it is
|
||||
@@ -82,8 +84,14 @@ not evaluated against callers.
|
||||
|
||||
A guardrail's policy lives on the guardrail. `GetResourcePolicy` on a guardrail with no
|
||||
policy returns a response without `resourcePolicy`, and deleting the guardrail deletes
|
||||
its policy. An ARN that names no guardrail of the caller's account and Region, including
|
||||
a guardrail profile ARN or another Bedrock resource, returns `ResourceNotFoundException`.
|
||||
its policy. An ARN that names no guardrail of the caller's account and Region returns
|
||||
`ResourceNotFoundException`. A guardrail profile has one ARN per destination Region, and
|
||||
its policy is stored under the Region whose endpoint received `PutResourcePolicy`, as
|
||||
AWS stores it, so the same profile ARN can hold a different policy in each calling
|
||||
Region. `GetResourcePolicy` on a profile ARN that holds no policy in the calling Region
|
||||
returns the empty policy `{}`. A profile ARN of another account or partition returns
|
||||
`ResourceNotFoundException`; whether the profile's Region is a destination of the
|
||||
calling Region is not checked.
|
||||
|
||||
With IAM enforcement on, `PutResourcePolicy`, `GetResourcePolicy` and
|
||||
`DeleteResourcePolicy` are authorized as `bedrock:PutResourcePolicy`,
|
||||
|
||||
@@ -96,13 +96,31 @@ public class BedrockService implements ResourceProvider {
|
||||
/** {@code ResourcePolicyDocument} from the AWS model: min 1, max 20480. */
|
||||
private static final int RESOURCE_POLICY_MAX = 20480;
|
||||
|
||||
private static final String GUARDRAIL_RESOURCE_PREFIX = "guardrail/";
|
||||
/** {@code GuardrailCrossRegionGuardrailProfileId} from the AWS model, e.g. {@code us.guardrail.v1:0}. */
|
||||
private static final Pattern GUARDRAIL_PROFILE_ID_PATTERN =
|
||||
Pattern.compile("[a-z0-9-]+[.]guardrail[.]v[0-9:]+");
|
||||
|
||||
/** The actions the Bedrock user guide lets a guardrail resource-based policy grant. */
|
||||
private static final String GUARDRAIL_RESOURCE_PREFIX = "guardrail/";
|
||||
private static final String GUARDRAIL_PROFILE_RESOURCE_PREFIX = "guardrail-profile/";
|
||||
|
||||
/**
|
||||
* The actions the Bedrock user guide lets a guardrail resource-based policy grant. A guardrail
|
||||
* profile's policy may grant only {@code bedrock:ApplyGuardrail}.
|
||||
*/
|
||||
private static final Set<String> GUARDRAIL_POLICY_ACTIONS =
|
||||
Set.of("bedrock:ApplyGuardrail", "bedrock:GetGuardrail");
|
||||
private static final Set<String> GUARDRAIL_PROFILE_POLICY_ACTIONS = Set.of("bedrock:ApplyGuardrail");
|
||||
|
||||
/** What {@code GetResourcePolicy} answers for a guardrail profile holding no policy under the called Region. */
|
||||
private static final String EMPTY_POLICY = "{}";
|
||||
|
||||
private final StorageBackend<String, Guardrail> guardrails;
|
||||
/**
|
||||
* Guardrail-profile policies, keyed by the Region whose endpoint stored them and the profile ARN. A
|
||||
* system-defined profile has one ARN per destination Region, and AWS keeps each policy under the
|
||||
* Region that received {@code PutResourcePolicy}, so one ARN can hold a different policy per Region.
|
||||
*/
|
||||
private final StorageBackend<String, String> guardrailProfilePolicies;
|
||||
private final RegionResolver regionResolver;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final KmsService kmsService;
|
||||
@@ -111,12 +129,17 @@ public class BedrockService implements ResourceProvider {
|
||||
public BedrockService(StorageFactory storageFactory, RegionResolver regionResolver,
|
||||
ObjectMapper objectMapper, KmsService kmsService) {
|
||||
this(storageFactory.create("bedrock", "bedrock-guardrails.json",
|
||||
new TypeReference<Map<String, Guardrail>>() {}), regionResolver, objectMapper, kmsService);
|
||||
new TypeReference<Map<String, Guardrail>>() {}),
|
||||
storageFactory.create("bedrock", "bedrock-guardrail-profile-policies.json",
|
||||
new TypeReference<Map<String, String>>() {}),
|
||||
regionResolver, objectMapper, kmsService);
|
||||
}
|
||||
|
||||
BedrockService(StorageBackend<String, Guardrail> guardrails, RegionResolver regionResolver,
|
||||
BedrockService(StorageBackend<String, Guardrail> guardrails,
|
||||
StorageBackend<String, String> guardrailProfilePolicies, RegionResolver regionResolver,
|
||||
ObjectMapper objectMapper, KmsService kmsService) {
|
||||
this.guardrails = guardrails;
|
||||
this.guardrailProfilePolicies = guardrailProfilePolicies;
|
||||
this.regionResolver = regionResolver;
|
||||
this.objectMapper = objectMapper;
|
||||
this.kmsService = kmsService;
|
||||
@@ -261,9 +284,16 @@ public class BedrockService implements ResourceProvider {
|
||||
|
||||
// Resource policies
|
||||
|
||||
/** The policy attached to a guardrail, or null when it holds none. */
|
||||
/**
|
||||
* The policy attached to a guardrail, or null when it holds none. A guardrail profile that holds
|
||||
* none under {@code region} reads as the empty policy {@code {}}.
|
||||
*/
|
||||
public String getResourcePolicy(String resourceArn, String region) {
|
||||
requireResourcePolicyArn(resourceArn);
|
||||
if (isGuardrailProfileArn(resourceArn)) {
|
||||
requireOwnGuardrailProfile(resourceArn);
|
||||
return guardrailProfilePolicies.get(profilePolicyKey(region, resourceArn)).orElse(EMPTY_POLICY);
|
||||
}
|
||||
return findGuardrailForPolicy(resourceArn, region).getResourcePolicy();
|
||||
}
|
||||
|
||||
@@ -273,7 +303,14 @@ public class BedrockService implements ResourceProvider {
|
||||
throw new AwsException("ValidationException",
|
||||
"resourcePolicy must be between 1 and " + RESOURCE_POLICY_MAX + " characters.", 400);
|
||||
}
|
||||
validateResourcePolicy(policy, resourceArn);
|
||||
boolean profile = isGuardrailProfileArn(resourceArn);
|
||||
validateResourcePolicy(policy, resourceArn,
|
||||
profile ? GUARDRAIL_PROFILE_POLICY_ACTIONS : GUARDRAIL_POLICY_ACTIONS);
|
||||
if (profile) {
|
||||
requireOwnGuardrailProfile(resourceArn);
|
||||
guardrailProfilePolicies.put(profilePolicyKey(region, resourceArn), policy);
|
||||
return;
|
||||
}
|
||||
Guardrail guardrail = findGuardrailForPolicy(resourceArn, region);
|
||||
guardrail.setResourcePolicy(policy);
|
||||
guardrails.put(storageKey(region, guardrail.getGuardrailId(), DRAFT_VERSION), guardrail);
|
||||
@@ -282,6 +319,11 @@ public class BedrockService implements ResourceProvider {
|
||||
|
||||
public synchronized void deleteResourcePolicy(String resourceArn, String region) {
|
||||
requireResourcePolicyArn(resourceArn);
|
||||
if (isGuardrailProfileArn(resourceArn)) {
|
||||
requireOwnGuardrailProfile(resourceArn);
|
||||
guardrailProfilePolicies.delete(profilePolicyKey(region, resourceArn));
|
||||
return;
|
||||
}
|
||||
Guardrail guardrail = findGuardrailForPolicy(resourceArn, region);
|
||||
guardrail.setResourcePolicy(null);
|
||||
guardrails.put(storageKey(region, guardrail.getGuardrailId(), DRAFT_VERSION), guardrail);
|
||||
@@ -477,13 +519,37 @@ public class BedrockService implements ResourceProvider {
|
||||
return findByArn(resourceArn, region);
|
||||
}
|
||||
|
||||
private static boolean isGuardrailProfileArn(String resourceArn) {
|
||||
return AwsArnUtils.isArnFor(resourceArn, "bedrock")
|
||||
&& AwsArnUtils.parse(resourceArn).resource().startsWith(GUARDRAIL_PROFILE_RESOURCE_PREFIX);
|
||||
}
|
||||
|
||||
/**
|
||||
* A guardrail profile is system-defined, so any well-formed profile ARN in the caller's own account and
|
||||
* partition names one. Whether its Region is a destination of the calling Region is not checked.
|
||||
*/
|
||||
private void requireOwnGuardrailProfile(String resourceArn) {
|
||||
AwsArnUtils.Arn parsed = AwsArnUtils.parse(resourceArn);
|
||||
String profileId = parsed.resource().substring(GUARDRAIL_PROFILE_RESOURCE_PREFIX.length());
|
||||
if (parsed.region().isEmpty() || !GUARDRAIL_PROFILE_ID_PATTERN.matcher(profileId).matches()
|
||||
|| !parsed.partition().equals(regionResolver.getPartition())
|
||||
|| !parsed.partition().equals(regionResolver.partitionForRegion(parsed.region()))
|
||||
|| !parsed.accountId().equals(regionResolver.getAccountId())) {
|
||||
throw new AwsException("ResourceNotFoundException", "Resource " + resourceArn + " does not exist.", 404);
|
||||
}
|
||||
}
|
||||
|
||||
private static String profilePolicyKey(String region, String resourceArn) {
|
||||
return region + "::" + resourceArn;
|
||||
}
|
||||
|
||||
/**
|
||||
* Holds a policy to the restricted language the Bedrock user guide gives guardrail resource-based
|
||||
* policies: Allow statements on the resource the policy is attached to, granting only the supported
|
||||
* actions, either to the account's root or to {@code *} under an {@code aws:PrincipalOrgID} condition,
|
||||
* with no condition but that one and {@code aws:PrincipalOrgPaths}.
|
||||
*/
|
||||
private void validateResourcePolicy(String policy, String resourceArn) {
|
||||
private void validateResourcePolicy(String policy, String resourceArn, Set<String> allowedActions) {
|
||||
JsonNode document;
|
||||
try {
|
||||
document = objectMapper.reader().with(DeserializationFeature.FAIL_ON_TRAILING_TOKENS).readTree(policy);
|
||||
@@ -509,9 +575,9 @@ public class BedrockService implements ResourceProvider {
|
||||
}
|
||||
List<JsonNode> actions = elements(statement.path("Action"));
|
||||
if (actions.isEmpty()
|
||||
|| actions.stream().anyMatch(action -> !GUARDRAIL_POLICY_ACTIONS.contains(action.asText()))) {
|
||||
|| actions.stream().anyMatch(action -> !allowedActions.contains(action.asText()))) {
|
||||
throw invalidResourcePolicy("Every statement's Action must be among "
|
||||
+ String.join(", ", GUARDRAIL_POLICY_ACTIONS.stream().sorted().toList()) + ".");
|
||||
+ String.join(", ", allowedActions.stream().sorted().toList()) + ".");
|
||||
}
|
||||
validatePrincipalAndCondition(statement.path("Principal"), statement.path("Condition"), accountRoot);
|
||||
}
|
||||
|
||||
+27
-3
@@ -107,9 +107,6 @@ class BedrockResourcePolicyIntegrationTest {
|
||||
() -> 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 {
|
||||
@@ -142,6 +139,33 @@ class BedrockResourcePolicyIntegrationTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aGuardrailProfilePolicyIsKeptUnderTheCallingRegion() {
|
||||
String profile = "arn:aws:bedrock:us-west-2:" + ACCOUNT + ":guardrail-profile/us.guardrail.v1:0";
|
||||
try (BedrockClient source = client(ACCOUNT, Region.US_EAST_1);
|
||||
BedrockClient destination = client(ACCOUNT, Region.US_WEST_2);
|
||||
BedrockClient otherAccount = client(OTHER_ACCOUNT, Region.US_EAST_1)) {
|
||||
String policy = rootPolicy(profile, "\"bedrock:ApplyGuardrail\"");
|
||||
try {
|
||||
assertEquals("{}", source.getResourcePolicy(r -> r.resourceArn(profile)).resourcePolicy());
|
||||
|
||||
source.putResourcePolicy(r -> r.resourceArn(profile).resourcePolicy(policy));
|
||||
|
||||
assertEquals(policy, source.getResourcePolicy(r -> r.resourceArn(profile)).resourcePolicy());
|
||||
assertEquals("{}", destination.getResourcePolicy(r -> r.resourceArn(profile)).resourcePolicy());
|
||||
assertThrows(ValidationException.class, () -> source.putResourcePolicy(r -> r.resourceArn(profile)
|
||||
.resourcePolicy(rootPolicy(profile, "\"bedrock:GetGuardrail\""))));
|
||||
assertThrows(ResourceNotFoundException.class,
|
||||
() -> otherAccount.getResourcePolicy(r -> r.resourceArn(profile)));
|
||||
|
||||
source.deleteResourcePolicy(r -> r.resourceArn(profile));
|
||||
assertEquals("{}", source.getResourcePolicy(r -> r.resourceArn(profile)).resourcePolicy());
|
||||
} finally {
|
||||
source.deleteResourcePolicy(r -> r.resourceArn(profile));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static CreateGuardrailResponse create(BedrockClient client) {
|
||||
return create(client, "rp-" + UUID.randomUUID());
|
||||
}
|
||||
|
||||
@@ -40,7 +40,7 @@ class BedrockServiceTest {
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
kmsService = mock(KmsService.class);
|
||||
service = new BedrockService(new InMemoryStorage<>(),
|
||||
service = new BedrockService(new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
new RegionResolver(REGION, ACCOUNT), mapper, kmsService);
|
||||
}
|
||||
|
||||
@@ -562,6 +562,9 @@ class BedrockServiceTest {
|
||||
assertTrue(service.listGuardrails(null, null, null, "eu-west-1").items().isEmpty());
|
||||
}
|
||||
|
||||
private static final String PROFILE_ARN_US_EAST_2 =
|
||||
"arn:aws:bedrock:us-east-2:" + ACCOUNT + ":guardrail-profile/us.guardrail.v1:0";
|
||||
|
||||
private static String rootPolicy(String resourceArn, String action) {
|
||||
return """
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
|
||||
@@ -591,8 +594,7 @@ class BedrockServiceTest {
|
||||
|
||||
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")) {
|
||||
created.getGuardrailArn().replace(":guardrail/", ":custom-model/"))) {
|
||||
AwsException e = assertThrows(AwsException.class, () -> service.getResourcePolicy(other, REGION));
|
||||
assertEquals("ResourceNotFoundException", e.getErrorCode(), other);
|
||||
}
|
||||
@@ -600,4 +602,48 @@ class BedrockServiceTest {
|
||||
() -> service.putResourcePolicy(created.getGuardrailArn(), policy, "eu-west-1"));
|
||||
assertEquals("ResourceNotFoundException", otherRegion.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void guardrailProfilePolicyIsKeptUnderTheRegionThatStoredIt() {
|
||||
String policy = rootPolicy(PROFILE_ARN_US_EAST_2, "bedrock:ApplyGuardrail");
|
||||
|
||||
service.putResourcePolicy(PROFILE_ARN_US_EAST_2, policy, REGION);
|
||||
|
||||
assertEquals(policy, service.getResourcePolicy(PROFILE_ARN_US_EAST_2, REGION));
|
||||
assertEquals("{}", service.getResourcePolicy(PROFILE_ARN_US_EAST_2, "us-east-2"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletingAGuardrailProfilePolicyLeavesTheEmptyPolicy() {
|
||||
assertEquals("{}", service.getResourcePolicy(PROFILE_ARN_US_EAST_2, REGION));
|
||||
service.putResourcePolicy(PROFILE_ARN_US_EAST_2, rootPolicy(PROFILE_ARN_US_EAST_2, "bedrock:ApplyGuardrail"),
|
||||
REGION);
|
||||
|
||||
service.deleteResourcePolicy(PROFILE_ARN_US_EAST_2, REGION);
|
||||
|
||||
assertEquals("{}", service.getResourcePolicy(PROFILE_ARN_US_EAST_2, REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void guardrailProfilePolicyAllowsOnlyApplyGuardrail() {
|
||||
AwsException e = assertThrows(AwsException.class, () -> service.putResourcePolicy(PROFILE_ARN_US_EAST_2,
|
||||
rootPolicy(PROFILE_ARN_US_EAST_2, "bedrock:GetGuardrail"), REGION));
|
||||
assertEquals("ValidationException", e.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void guardrailProfileOfAnotherAccountOrPartitionOrWithAMalformedIdIsNotFound() {
|
||||
String chinaProfile = "arn:aws-cn:bedrock:cn-north-1:" + ACCOUNT + ":guardrail-profile/cn.guardrail.v1:0";
|
||||
for (String arn : List.of(PROFILE_ARN_US_EAST_2.replace(ACCOUNT, "111122223333"),
|
||||
PROFILE_ARN_US_EAST_2.replace(":" + ACCOUNT + ":", "::"),
|
||||
PROFILE_ARN_US_EAST_2.replace("us.guardrail.v1:0", "not-a-profile"),
|
||||
chinaProfile,
|
||||
chinaProfile.replace("arn:aws-cn:", "arn:aws:"))) {
|
||||
AwsException e = assertThrows(AwsException.class, () -> service.getResourcePolicy(arn, REGION));
|
||||
assertEquals("ResourceNotFoundException", e.getErrorCode(), arn);
|
||||
AwsException put = assertThrows(AwsException.class, () -> service.putResourcePolicy(arn,
|
||||
rootPolicy(arn, "bedrock:ApplyGuardrail"), REGION));
|
||||
assertEquals("ResourceNotFoundException", put.getErrorCode(), arn);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user