fix(verifiedpermissions): resolve action groups from the policy store schema (#9427)

AVP builds the action entities, with their memberOf action-group parents,
from the policy store's schema. Floci sent the sidecar only the entities in
the request, so a policy scoped with `action in NS::Action::"Group"` never
matched a member action and IsAuthorized returned DENY where AWS returns
ALLOW.

IsAuthorized, BatchIsAuthorized and their token variants now merge the
schema's action entities into the request entities before evaluation. The
schema's definition replaces a caller entity with the same identifier, since
IsAuthorized entities cannot include actions and IsAuthorizedWithToken accepts
an action entity with only its identifier. An unreadable stored schema is
logged and the request is evaluated without schema-derived actions.
This commit is contained in:
andrei-fabricdata authored and GitHub committed 2026-11-25 13:51:52 -04:00
1 parent 0d2ef89d0e
commit f1c2c44883
5 files changed
+322 -37

No files matched your search

+6
View File
@@ -105,6 +105,12 @@ JSON and supports booleans, longs, strings, entity references, IP addresses, dec
datetimes, durations, sets, records, entity parents, and entity tags. When duplicate entity
identifiers are supplied in an entity list, the last definition wins.
As in AVP, the action entities come from the policy store schema: each schema action is added to
the request's entities with its `memberOf` action groups as parents, so a policy scoped with
`action in NS::Action::"Group"` matches every member action. The schema's definition replaces an
action entity the caller supplies for the same identifier, such as the identifier-only action entities
that `IsAuthorizedWithToken` accepts.
## Identity sources and tokens
Cognito identity sources derive the OIDC issuer from the user pool ARN, enforce same-Region user
@@ -10,11 +10,14 @@ import io.floci.aws.services.verifiedpermissions.model.Policy;
import io.floci.aws.services.verifiedpermissions.model.PolicyTemplate;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* AVP request adapter for the Cedar sidecar.
@@ -25,6 +28,8 @@ import java.util.Map;
*/
@ApplicationScoped
public class CedarAuthorizationEvaluator {
private static final Logger LOG = Logger.getLogger(CedarAuthorizationEvaluator.class);
private final ObjectMapper objectMapper;
private final CedarSidecarClient cedarClient;
@@ -36,46 +41,130 @@ public class CedarAuthorizationEvaluator {
public ObjectNode appendTokenPrincipal(JsonNode entitiesDefinition, EntityIdentifier principal,
JsonNode identityClaims, List<EntityIdentifier> parents) {
ArrayNode cedarEntities;
try {
if (entitiesDefinition == null || entitiesDefinition.isNull()) {
cedarEntities = objectMapper.createArrayNode();
} else if (entitiesDefinition.has("cedarJson")) {
ArrayNode cedarEntities = requestCedarEntities(entitiesDefinition);
ObjectNode entity = objectMapper.createObjectNode();
entity.set("uid", cedarEntity(principal));
ObjectNode attrs = entity.putObject("attrs");
if (identityClaims != null && identityClaims.isObject()) {
identityClaims.fields().forEachRemaining(entry -> {
if (!isGroupClaim(entry.getKey()) && claimCanBeCedar(entry.getValue())) {
attrs.set(entry.getKey(), entry.getValue().deepCopy());
}
});
}
ArrayNode parentArray = entity.putArray("parents");
parents.forEach(parent -> parentArray.add(cedarEntity(parent)));
cedarEntities.add(entity);
ObjectNode union = objectMapper.createObjectNode();
union.put("cedarJson", cedarEntities.toString());
return union;
}
public EvaluationResult evaluate(JsonNode request, String schema, List<Policy> storedPolicies,
Map<String, PolicyTemplate> templates) {
JsonNode withActions = withSchemaActions(request, schema);
CedarSidecarClient.EvaluationResult result = cedarClient.authorize(withActions, storedPolicies, templates);
return new EvaluationResult(result.decision(), result.determiningPolicyIds(), result.errors());
}
/**
* AVP builds the action entities, and their action-group parents, from the store's schema. The sidecar
* only sees the request, so without this `action in NS::Action::"Group"` never matches a member action.
* The schema's definition replaces a caller entity for the same action: AVP takes actions from the schema,
* and a token request may list an action with only its identifier, which would otherwise drop its groups.
*/
JsonNode withSchemaActions(JsonNode request, String schema) {
ArrayNode actions = schemaActionEntities(schema);
if (actions.isEmpty()) {
return request;
}
Set<String> schemaUids = new HashSet<>();
actions.forEach(action -> schemaUids.add(uidKey(action.path("uid"))));
ArrayNode cedarEntities = objectMapper.createArrayNode();
requestCedarEntities(request.get("entities")).forEach(entity -> {
if (!schemaUids.contains(uidKey(entity.path("uid")))) {
cedarEntities.add(entity);
}
});
cedarEntities.addAll(actions);
ObjectNode out = request.deepCopy();
out.putObject("entities").put("cedarJson", cedarEntities.toString());
return out;
}
private ArrayNode requestCedarEntities(JsonNode entitiesDefinition) {
if (entitiesDefinition == null || entitiesDefinition.isNull()) {
return objectMapper.createArrayNode();
}
if (entitiesDefinition.has("cedarJson")) {
try {
JsonNode parsed = objectMapper.readTree(entitiesDefinition.path("cedarJson").asText());
if (!parsed.isArray()) {
throw VerifiedPermissionsService.validation("entities.cedarJson must encode an array.");
}
cedarEntities = (ArrayNode) parsed.deepCopy();
} else if (entitiesDefinition.has("entityList") && entitiesDefinition.get("entityList").isArray()) {
cedarEntities = toCedarEntities((ArrayNode) entitiesDefinition.get("entityList"));
} else {
throw VerifiedPermissionsService.validation("entities must contain cedarJson or entityList.");
return (ArrayNode) parsed.deepCopy();
} catch (JsonProcessingException e) {
throw VerifiedPermissionsService.validation("entities.cedarJson is invalid JSON.");
}
ObjectNode entity = objectMapper.createObjectNode();
entity.set("uid", cedarEntity(principal));
ObjectNode attrs = entity.putObject("attrs");
if (identityClaims != null && identityClaims.isObject()) {
identityClaims.fields().forEachRemaining(entry -> {
if (!isGroupClaim(entry.getKey()) && claimCanBeCedar(entry.getValue())) {
attrs.set(entry.getKey(), entry.getValue().deepCopy());
}
});
}
ArrayNode parentArray = entity.putArray("parents");
parents.forEach(parent -> parentArray.add(cedarEntity(parent)));
cedarEntities.add(entity);
ObjectNode union = objectMapper.createObjectNode();
union.put("cedarJson", cedarEntities.toString());
return union;
} catch (JsonProcessingException e) {
throw VerifiedPermissionsService.validation("entities.cedarJson is invalid JSON.");
}
if (entitiesDefinition.has("entityList") && entitiesDefinition.get("entityList").isArray()) {
return toCedarEntities((ArrayNode) entitiesDefinition.get("entityList"));
}
throw VerifiedPermissionsService.validation("entities must contain cedarJson or entityList.");
}
public EvaluationResult evaluate(JsonNode request, List<Policy> storedPolicies,
Map<String, PolicyTemplate> templates) {
CedarSidecarClient.EvaluationResult result = cedarClient.authorize(request, storedPolicies, templates);
return new EvaluationResult(result.decision(), result.determiningPolicyIds(), result.errors());
private ArrayNode schemaActionEntities(String schema) {
ArrayNode out = objectMapper.createArrayNode();
if (schema == null || schema.isBlank()) {
return out;
}
JsonNode parsed;
try {
parsed = objectMapper.readTree(schema);
} catch (JsonProcessingException e) {
LOG.warnv(e, "Stored policy store schema is not valid JSON; authorizing without schema-derived action entities");
return out;
}
if (parsed == null || !parsed.isObject()) {
return out;
}
parsed.fields().forEachRemaining(namespace -> {
JsonNode actions = namespace.getValue().path("actions");
if (!actions.isObject()) {
return;
}
String actionType = namespace.getKey().isEmpty() ? "Action" : namespace.getKey() + "::Action";
actions.fields().forEachRemaining(action -> {
ObjectNode entity = objectMapper.createObjectNode();
entity.set("uid", cedarEntity(new EntityIdentifier(actionType, action.getKey())));
entity.putObject("attrs");
ArrayNode parents = entity.putArray("parents");
JsonNode memberOf = action.getValue().path("memberOf");
if (memberOf.isArray()) {
memberOf.forEach(parent -> {
String parentType = parent.hasNonNull("type")
? qualifiedActionType(namespace.getKey(), parent.get("type").asText())
: actionType;
parents.add(cedarEntity(new EntityIdentifier(parentType, parent.path("id").asText())));
});
}
out.add(entity);
});
});
return out;
}
/** A memberOf `type` names an action group in another namespace, e.g. "Other::Action"; a bare "Action" is this one. */
private static String qualifiedActionType(String namespace, String type) {
if (type.contains("::") || namespace.isEmpty()) {
return type;
}
return namespace + "::" + type;
}
private static String uidKey(JsonNode uid) {
JsonNode inner = uid.has("__entity") ? uid.get("__entity") : uid;
return inner.path("type").asText() + "\u0000" + inner.path("id").asText();
}
private static boolean isGroupClaim(String name) {
@@ -257,7 +257,7 @@ public class VerifiedPermissionsJsonHandler {
private ObjectNode batchIsAuthorizedWithToken(JsonNode request, String region) {
String storeIdentifier = VerifiedPermissionsService.requiredText(request, "policyStoreId");
service.getPolicyStore(storeIdentifier, region);
PolicyStore store = service.getPolicyStore(storeIdentifier, region);
JsonNode requests = request.get("requests");
if (requests == null || !requests.isArray() || requests.isEmpty() || requests.size() > 30) {
throw VerifiedPermissionsService.validation("requests must contain between 1 and 30 items.");
@@ -291,6 +291,7 @@ public class VerifiedPermissionsJsonHandler {
principal = prepared.principal();
}
CedarAuthorizationEvaluator.EvaluationResult evaluation = authorizationEvaluator.evaluate(prepared.request(),
store.schema(),
service.policiesForStore(storeIdentifier, region), service.templatesForStore(storeIdentifier, region));
ObjectNode result = authorizationResult(evaluation);
result.set("request", item.deepCopy());
@@ -302,15 +303,16 @@ public class VerifiedPermissionsJsonHandler {
private ObjectNode isAuthorized(JsonNode request, String region) {
String storeIdentifier = VerifiedPermissionsService.requiredText(request, "policyStoreId");
service.getPolicyStore(storeIdentifier, region);
PolicyStore store = service.getPolicyStore(storeIdentifier, region);
CedarAuthorizationEvaluator.EvaluationResult result = authorizationEvaluator.evaluate(request,
store.schema(),
service.policiesForStore(storeIdentifier, region), service.templatesForStore(storeIdentifier, region));
return authorizationResult(result);
}
private ObjectNode batchIsAuthorized(JsonNode request, String region) {
String storeIdentifier = VerifiedPermissionsService.requiredText(request, "policyStoreId");
service.getPolicyStore(storeIdentifier, region);
PolicyStore store = service.getPolicyStore(storeIdentifier, region);
JsonNode requests = request.get("requests");
if (requests == null || !requests.isArray() || requests.isEmpty() || requests.size() > 30) {
throw VerifiedPermissionsService.validation("requests must contain between 1 and 30 items.");
@@ -324,6 +326,7 @@ public class VerifiedPermissionsJsonHandler {
evaluationRequest.set("entities", request.get("entities"));
}
CedarAuthorizationEvaluator.EvaluationResult result = authorizationEvaluator.evaluate(evaluationRequest,
store.schema(),
service.policiesForStore(storeIdentifier, region), service.templatesForStore(storeIdentifier, region));
ObjectNode item = authorizationResult(result);
item.set("request", batchRequest.deepCopy());
@@ -0,0 +1,104 @@
package io.floci.aws.services.verifiedpermissions;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.sameInstance;
import static org.mockito.Mockito.mock;
class CedarAuthorizationEvaluatorTest {
private static final String SCHEMA = """
{"Demo":{"entityTypes":{"User":{}},"actions":{
"Read":{},
"read":{"memberOf":[{"id":"Read"},{"type":"Other::Action","id":"Audit"},{"type":"Action","id":"All"}]}
}}}""";
private final ObjectMapper objectMapper = new ObjectMapper();
private final CedarAuthorizationEvaluator evaluator =
new CedarAuthorizationEvaluator(objectMapper, mock(CedarSidecarClient.class));
@Test
void schemaActionsBecomeEntitiesWithTheirGroupsAsParents() throws Exception {
JsonNode out = evaluator.withSchemaActions(objectMapper.readTree("{}"), SCHEMA);
JsonNode entities = cedarEntities(out);
assertThat(uids(entities), containsInAnyOrder("Demo::Action/Read", "Demo::Action/read"));
JsonNode read = entity(entities, "read");
assertThat(uids(read.get("parents")),
containsInAnyOrder("Demo::Action/Read", "Other::Action/Audit", "Demo::Action/All"));
assertThat(entity(entities, "Read").get("parents").size(), equalTo(0));
}
@Test
void theSchemaDefinitionReplacesACallerEntityForTheSameAction() throws Exception {
String callerEntities = "[{\"uid\":{\"type\":\"Demo::Action\",\"id\":\"read\"},\"attrs\":{},\"parents\":[]}]";
JsonNode request = objectMapper.createObjectNode().set("entities",
objectMapper.createObjectNode().put("cedarJson", callerEntities));
JsonNode entities = cedarEntities(evaluator.withSchemaActions(request, SCHEMA));
assertThat(uids(entities), containsInAnyOrder("Demo::Action/read", "Demo::Action/Read"));
assertThat(uids(entity(entities, "read").get("parents")),
containsInAnyOrder("Demo::Action/Read", "Other::Action/Audit", "Demo::Action/All"));
}
@Test
void entityListInputIsConvertedAndMerged() throws Exception {
JsonNode request = objectMapper.readTree("""
{"entities":{"entityList":[{"identifier":{"entityType":"Demo::User","entityId":"alice"}}]}}""");
JsonNode entities = cedarEntities(evaluator.withSchemaActions(request, SCHEMA));
assertThat(uids(entities), containsInAnyOrder("Demo::User/alice", "Demo::Action/Read", "Demo::Action/read"));
}
@Test
void aRequestIsUnchangedWithoutSchemaActions() throws Exception {
JsonNode request = objectMapper.readTree("{\"principal\":{\"entityType\":\"Demo::User\",\"entityId\":\"alice\"}}");
assertThat(evaluator.withSchemaActions(request, null), sameInstance(request));
assertThat(evaluator.withSchemaActions(request, " "), sameInstance(request));
assertThat(evaluator.withSchemaActions(request, "{not json"), sameInstance(request));
assertThat(evaluator.withSchemaActions(request, "{\"Demo\":{\"entityTypes\":{}}}"), sameInstance(request));
}
@Test
void theEmptyNamespaceUsesBareActionType() throws Exception {
String schema = "{\"\":{\"actions\":{\"view\":{\"memberOf\":[{\"id\":\"All\"}]}}}}";
JsonNode entities = cedarEntities(evaluator.withSchemaActions(objectMapper.readTree("{}"), schema));
assertThat(uids(entities), containsInAnyOrder("Action/view"));
assertThat(uids(entities.get(0).get("parents")), containsInAnyOrder("Action/All"));
}
private JsonNode cedarEntities(JsonNode request) throws Exception {
return objectMapper.readTree(request.path("entities").path("cedarJson").asText());
}
private static JsonNode entity(JsonNode entities, String id) {
for (JsonNode entity : entities) {
if (id.equals(entity.path("uid").path("id").asText())) {
return entity;
}
}
throw new AssertionError("No entity with id " + id + " in " + entities);
}
private static List<String> uids(JsonNode nodes) {
List<String> out = new ArrayList<>();
nodes.forEach(node -> {
JsonNode uid = node.has("uid") ? node.get("uid") : node;
out.add(uid.path("type").asText() + "/" + uid.path("id").asText());
});
return out;
}
}
@@ -250,6 +250,44 @@ class VerifiedPermissionsIntegrationTest {
.body("results[1].decision", equalTo("DENY"));
}
@Test
void isAuthorized_resolvesActionGroupsFromTheSchema() {
String store = createStore("OFF", "DISABLED");
String schema = "{\"Demo\":{\"entityTypes\":{\"User\":{},\"Document\":{}},\"actions\":{"
+ "\"Read\":{\"appliesTo\":{\"principalTypes\":[],\"resourceTypes\":[]}},"
+ "\"Write\":{\"appliesTo\":{\"principalTypes\":[],\"resourceTypes\":[]}},"
+ "\"read\":{\"appliesTo\":{\"principalTypes\":[\"User\"],\"resourceTypes\":[\"Document\"]},\"memberOf\":[{\"id\":\"Read\"}]},"
+ "\"write\":{\"appliesTo\":{\"principalTypes\":[\"User\"],\"resourceTypes\":[\"Document\"]},\"memberOf\":[{\"id\":\"Write\"}]}}}}";
givenAws("PutSchema", objectJson(Map.of("policyStoreId", store, "definition", Map.of("cedarJson", schema))))
.then().statusCode(200);
String templateId = givenAws("CreatePolicyTemplate", objectJson(Map.of("policyStoreId", store,
"statement", "permit(principal == ?principal, action in [Demo::Action::\"Read\", Demo::Action::\"Write\"], resource in ?resource);")))
.then().statusCode(200).extract().path("policyTemplateId");
Map<String,Object> principal = Map.of("entityType", "Demo::User", "entityId", "alice");
Map<String,Object> resource = Map.of("entityType", "Demo::Document", "entityId", "doc1");
givenAws("CreatePolicy", objectJson(Map.of("policyStoreId", store, "definition", Map.of("templateLinked", Map.of(
"policyTemplateId", templateId, "principal", principal, "resource", resource)))))
.then().statusCode(200);
givenAws("CreatePolicy", objectJson(Map.of("policyStoreId", store, "definition", Map.of("static", Map.of(
"statement", "forbid(principal, action in Demo::Action::\"Write\", resource);")))))
.then().statusCode(200);
Map<String,Object> read = Map.of("actionType", "Demo::Action", "actionId", "read");
Map<String,Object> write = Map.of("actionType", "Demo::Action", "actionId", "write");
givenAws("IsAuthorized", objectJson(Map.of("policyStoreId", store, "principal", principal, "action", read,
"resource", resource)))
.then().statusCode(200).body("decision", equalTo("ALLOW"));
givenAws("BatchIsAuthorized", objectJson(Map.of("policyStoreId", store,
"requests", List.of(
Map.of("principal", principal, "action", read, "resource", resource),
Map.of("principal", principal, "action", write, "resource", resource)),
"entities", Map.of("entityList", List.of(Map.of("identifier", principal))))))
.then().statusCode(200)
.body("results[0].decision", equalTo("ALLOW"))
.body("results[1].decision", equalTo("DENY"));
}
@Test
void createOperationsHonorEightHourClientTokenContract() {
String token = "token-123456";
@@ -357,7 +395,7 @@ class VerifiedPermissionsIntegrationTest {
"static", Map.of("statement", "permit(principal, action, resource);")))))
.then().statusCode(200);
Map<String, Object> request = new LinkedHashMap<>();
Map<String,Object> request = new LinkedHashMap<>();
request.put("policyStoreId", store);
request.put("accessToken", accessToken);
request.put("action", Map.of("actionType", "Action", "actionId", "view"));
@@ -365,7 +403,7 @@ class VerifiedPermissionsIntegrationTest {
givenAws("IsAuthorizedWithToken", objectJson(request))
.then().statusCode(200).body("decision", equalTo("ALLOW"));
Map<String, Object> foreignRequest = new LinkedHashMap<>(request);
Map<String,Object> foreignRequest = new LinkedHashMap<>(request);
foreignRequest.put("policyStoreId", foreign);
givenAws("IsAuthorizedWithToken", objectJson(foreignRequest))
.then().statusCode(400).body("__type", containsString("ValidationException"))
@@ -385,6 +423,51 @@ class VerifiedPermissionsIntegrationTest {
.then().statusCode(400).body("__type", containsString("ValidationException"));
}
@Test
void isAuthorizedWithToken_identifierOnlyActionEntityKeepsTheSchemaGroups() throws Exception {
JsonNode pool = cognito("CreateUserPool", "{\"PoolName\":\"avp-action-group-pool\"}");
String poolId = pool.path("UserPool").path("Id").asText();
String clientId = cognito("CreateUserPoolClient", objectJson(Map.of(
"UserPoolId", poolId, "ClientName", "app",
"ExplicitAuthFlows", List.of("ALLOW_ADMIN_USER_PASSWORD_AUTH", "ALLOW_REFRESH_TOKEN_AUTH"))))
.path("UserPoolClient").path("ClientId").asText();
cognito("AdminCreateUser", objectJson(Map.of(
"UserPoolId", poolId, "Username", "bob", "MessageAction", "SUPPRESS")));
cognito("AdminSetUserPassword", objectJson(Map.of(
"UserPoolId", poolId, "Username", "bob", "Password", "Avp-Group-1!", "Permanent", true)));
String accessToken = cognito("AdminInitiateAuth", objectJson(Map.of(
"UserPoolId", poolId, "ClientId", clientId, "AuthFlow", "ADMIN_USER_PASSWORD_AUTH",
"AuthParameters", Map.of("USERNAME", "bob", "PASSWORD", "Avp-Group-1!"))))
.path("AuthenticationResult").path("AccessToken").asText();
String store = createStore("OFF", "DISABLED");
String schema = "{\"\":{\"entityTypes\":{\"User\":{},\"Photo\":{}},\"actions\":{"
+ "\"All\":{},"
+ "\"view\":{\"appliesTo\":{\"principalTypes\":[\"User\"],\"resourceTypes\":[\"Photo\"]},\"memberOf\":[{\"id\":\"All\"}]}}}}";
givenAws("PutSchema", objectJson(Map.of("policyStoreId", store, "definition", Map.of("cedarJson", schema))))
.then().statusCode(200);
givenAws("CreateIdentitySource", objectJson(Map.of(
"policyStoreId", store, "principalEntityType", "User",
"configuration", Map.of("cognitoUserPoolConfiguration", Map.of(
"userPoolArn", pool.path("UserPool").path("Arn").asText(),
"clientIds", List.of(clientId))))))
.then().statusCode(200);
givenAws("CreatePolicy", objectJson(Map.of("policyStoreId", store, "definition", Map.of(
"static", Map.of("statement", "permit(principal, action in Action::\"All\", resource);")))))
.then().statusCode(200);
Map<String,Object> action = Map.of("actionType", "Action", "actionId", "view");
Map<String,Object> request = new LinkedHashMap<>();
request.put("policyStoreId", store);
request.put("accessToken", accessToken);
request.put("action", action);
request.put("resource", Map.of("entityType", "Photo", "entityId", "p1"));
request.put("entities", Map.of("entityList", List.of(Map.of(
"identifier", Map.of("entityType", "Action", "entityId", "view")))));
givenAws("IsAuthorizedWithToken", objectJson(request))
.then().statusCode(200).body("decision", equalTo("ALLOW"));
}
@Test
void deletePolicyAndPolicyStore_areIdempotentForRetries() {
String store = createStore("OFF", "DISABLED");