Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CedarJava/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ dependencies {
compileOnly 'com.github.spotbugs:spotbugs-annotations:4.8.6'
testImplementation 'net.jqwik:jqwik:1.9.2'
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.11.4'
testImplementation 'org.skyscreamer:jsonassert:2.0-rc1'
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.11.4'
}

Expand Down
48 changes: 44 additions & 4 deletions CedarJava/src/main/java/com/cedarpolicy/AuthorizationEngine.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,21 @@

package com.cedarpolicy;

import com.cedarpolicy.model.*;
import java.util.Set;

import com.cedarpolicy.model.AuthorizationRequest;
import com.cedarpolicy.model.AuthorizationResponse;
import com.cedarpolicy.model.EntityValidationRequest;
import com.cedarpolicy.model.PartialAuthorizationRequest;
import com.cedarpolicy.model.PartialAuthorizationResponse;
import com.cedarpolicy.model.ValidationRequest;
import com.cedarpolicy.model.ValidationResponse;
import com.cedarpolicy.model.entity.Entities;
import com.cedarpolicy.model.entity.Entity;
import com.cedarpolicy.model.exception.AuthException;
import com.cedarpolicy.model.exception.BadRequestException;
import com.cedarpolicy.model.entity.Entity;
import com.cedarpolicy.model.policy.PolicySet;

import java.util.Set;

/**
* Implementations of the AuthorizationEngine interface invoke Cedar to respond to an authorization
* or validation request. For authorization, the input includes the relevant policies and entities for
Expand Down Expand Up @@ -51,6 +58,21 @@ public interface AuthorizationEngine {
*/
AuthorizationResponse isAuthorized(AuthorizationRequest request, PolicySet policySet, Set<Entity> entities) throws AuthException;

/**
* Asks whether the given AuthorizationRequest <code>q</code> is approved by the <code>policySet</code> and
* <code>entities</code> hierarchy given. Overloaded method to accept Entities object.
*
* @param request The request to evaluate
* @param policySet The policy set to evaluate against
* @param entities The entities to evaluate against
* @return The result of the request evaluation
* @throws BadRequestException if any errors were found in the syntax of the policies.
* @throws AuthException On failure to make the authorization request. Note that errors inside the
* authorization engine are included in the <code>errors</code> field on the
* AuthorizationResponse.
*/
AuthorizationResponse isAuthorized(AuthorizationRequest request, PolicySet policySet, Entities entities) throws AuthException;

/**
* Asks whether the given AuthorizationRequest <code>q</code> is approved by the <code>policySet</code> and
* <code>entities</code> given. If information required to answer is missing, residual policies are returned.
Expand All @@ -68,6 +90,24 @@ public interface AuthorizationEngine {
PartialAuthorizationResponse isAuthorizedPartial(PartialAuthorizationRequest request,
PolicySet policySet, Set<Entity> entities) throws AuthException;

/**
* Asks whether the given AuthorizationRequest <code>q</code> is approved by the <code>policySet</code> and
* <code>entities</code> given. If information required to answer is missing, residual policies are returned.
* Overloaded method to accept Entities object.
*
* @param request The request to evaluate
* @param policySet The policy set to evaluate against
* @param entities The entities to evaluate against
* @return The result of the request evaluation
* @throws BadRequestException if any errors were found in the syntax of the policies.
* @throws AuthException On failure to make the authorization request. Note that errors inside the
* authorization engine are included in the <code>errors</code> field on the
* AuthorizationResponse.
*/
@Experimental(ExperimentalFeature.PARTIAL_EVALUATION)
PartialAuthorizationResponse isAuthorizedPartial(PartialAuthorizationRequest request,
PolicySet policySet, Entities entities) throws AuthException;

/**
* Asks whether the policies in the given {@link ValidationRequest} <code>q</code> are correct
* when validated against the schema it describes.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,25 +20,30 @@
import static com.cedarpolicy.CedarJson.objectWriter;

import java.io.IOException;
import java.util.List;
import java.util.Set;

import com.cedarpolicy.loader.LibraryLoader;
import com.cedarpolicy.model.*;
import com.cedarpolicy.model.AuthorizationResponse;
import com.cedarpolicy.model.EntityValidationRequest;
import com.cedarpolicy.model.PartialAuthorizationResponse;
import com.cedarpolicy.model.ValidationRequest;
import com.cedarpolicy.model.ValidationResponse;
import com.cedarpolicy.model.entity.Entities;
import com.cedarpolicy.model.entity.Entity;
import com.cedarpolicy.model.exception.AuthException;
import com.cedarpolicy.model.exception.BadRequestException;
import com.cedarpolicy.model.exception.InternalException;
import com.cedarpolicy.model.exception.MissingExperimentalFeatureException;
import com.cedarpolicy.model.entity.Entity;
import com.cedarpolicy.model.policy.PolicySet;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;

import java.util.List;
import java.util.Set;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;

/** An authorization engine that is compiled in process. Communicated with via JNI. */
public final class BasicAuthorizationEngine implements AuthorizationEngine {
Expand All @@ -57,6 +62,15 @@ public AuthorizationResponse isAuthorized(com.cedarpolicy.model.AuthorizationReq
return call("AuthorizationOperation", AuthorizationResponse.class, request);
}

/**
* Overloaded method to accept Entities object
*/
@Override
public AuthorizationResponse isAuthorized(com.cedarpolicy.model.AuthorizationRequest q,
PolicySet policySet, Entities entities) throws AuthException {
return isAuthorized(q, policySet, entities.getEntities());
}

@Experimental(ExperimentalFeature.PARTIAL_EVALUATION)
@Override
public PartialAuthorizationResponse isAuthorizedPartial(com.cedarpolicy.model.PartialAuthorizationRequest q,
Expand All @@ -73,6 +87,16 @@ public PartialAuthorizationResponse isAuthorizedPartial(com.cedarpolicy.model.Pa
}
}

/**
* Overloaded method to accept Entities object
*/
@Experimental(ExperimentalFeature.PARTIAL_EVALUATION)
@Override
public PartialAuthorizationResponse isAuthorizedPartial(com.cedarpolicy.model.PartialAuthorizationRequest q,
PolicySet policySet, Entities entities) throws AuthException {
return isAuthorizedPartial(q, policySet, entities.getEntities());
}

@Override
public ValidationResponse validate(ValidationRequest q) throws AuthException {
return call("ValidateOperation", ValidationResponse.class, q);
Expand Down
93 changes: 93 additions & 0 deletions CedarJava/src/main/java/com/cedarpolicy/model/entity/Entities.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
/*
* Copyright Cedar Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.cedarpolicy.model.entity;

import static com.cedarpolicy.CedarJson.objectReader;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Set;
import java.util.HashSet;

/**
* A class representing a collection of Cedar policy entities.
*/
public class Entities {
private Set<Entity> entities;

/**
* Constructs a new empty Entities collection. Creates a new HashSet to store Entity objects.
*/
public Entities() {
this.entities = new HashSet<>();
}

/**
* Constructs a new Entities collection from a given Set of Entity objects.
*
* @param entities The Set of Entity objects to initialize this collection with
*/
public Entities(Set<Entity> entities) {
this.entities = new HashSet<>(entities);
}

/**
* Returns a copy of the set of entities in this collection.
*
* @return A new HashSet containing all Entity objects in this collection
*/
public Set<Entity> getEntities() {
return new HashSet<>(entities);
}

/**
* Parses a JSON string representation into an Entities collection.
*
* @param jsonString The JSON string containing entity data to parse
*
* @return A new Entities instance containing the parsed entities
* @throws JsonProcessingException If the JSON string cannot be parsed into valid entities
*/
public static Entities parse(String jsonString) throws JsonProcessingException {
return new Entities(objectReader().forType(new TypeReference<Set<Entity>>() {
}).readValue(jsonString));
}

/**
* Parses a JSON file at the specified path into an Entities collection.
*
* @param filePath The path to the JSON file containing entity data to parse
*
* @return A new Entities instance containing the parsed entities
* @throws IOException If there is an error reading the file
* @throws JsonProcessingException If the JSON content cannot be parsed into valid entities
*/
public static Entities parse(Path filePath) throws IOException, JsonProcessingException {
String jsonString = Files.readString(filePath);
return new Entities(objectReader().forType(new TypeReference<Set<Entity>>() {
}).readValue(jsonString));
}

@Override
public String toString() {
return String.join("\n", this.entities.stream().map(Entity::toString).toList());
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does this style match the behavior in Rust where each is printed on a new line?

Copy link
Contributor Author

@muditchaudhary muditchaudhary Feb 24, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No. The default behavior in Rust is to display the JSON representation of Entities and Entity. .toString() for Entities continues to follow the same display format which was implemented for Entity

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It seems like this format for displaying Entity was introduced in CedarJava 2.x. Maybe we can make the behavior similar to Rust in the next major version update as this will change the behavior of an existing public API

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ public Entity(EntityUID uid, Map<String, Value> attributes, Set<EntityUID> paren
* Get the value for the given attribute, or null if not present.
*
* @param attribute Attribute key
*
*
* @return Attribute value for the given key or null if not present
* @throws IllegalArgumentException if attribute is null
*/
Expand Down
33 changes: 33 additions & 0 deletions CedarJava/src/test/java/com/cedarpolicy/AuthTests.java
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
import com.cedarpolicy.value.Unknown;
import com.cedarpolicy.value.Value;
import com.cedarpolicy.value.PrimBool;
import com.cedarpolicy.model.entity.Entities;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.Executable;
Expand All @@ -47,6 +48,14 @@ public class AuthTests {

private void assertAllowed(AuthorizationRequest q, PolicySet policySet, Set<Entity> entities) {
assertDoesNotThrow(() -> {
// Using Entities object
Entities entitiesObj = new Entities(entities);
final var responseWithEntities = new BasicAuthorizationEngine().isAuthorized(q, policySet, entitiesObj);
assertEquals(responseWithEntities.type, SuccessOrFailure.Success);
final var successWithEntities = responseWithEntities.success.get();
assertTrue(successWithEntities.isAllowed());

// Backward compatible using Set<Entities>
final var response = new BasicAuthorizationEngine().isAuthorized(q, policySet, entities);
assertEquals(response.type, SuccessOrFailure.Success);
final var success = response.success.get();
Expand Down Expand Up @@ -197,6 +206,30 @@ public void partialAuthConcreteWithContextObject() {
});
}

@Test
public void partialAuthConcreteWithEntitiesObject() {
var auth = new BasicAuthorizationEngine();
var alice = new EntityUID(EntityTypeName.parse("User").get(), "alice");
var view = new EntityUID(EntityTypeName.parse("Action").get(), "view");
Map<String, Value> contextMap = new HashMap<>();
contextMap.put("authenticated", new PrimBool(true));
Context context = new Context(contextMap);
var q = PartialAuthorizationRequest.builder().principal(alice).action(view).resource(alice).context(context).build();
var policies = new HashSet<Policy>();
policies.add(new Policy("permit(principal == User::\"alice\",action,resource) when {context.authenticated == true};", "p0"));
var policySet = new PolicySet(policies);
assumePartialEvaluation(() -> {
try {
final PartialAuthorizationResponse response = auth.isAuthorizedPartial(q, policySet, new Entities());
assertEquals(Decision.Allow, response.success.orElseThrow().getDecision());
assertEquals(response.success.orElseThrow().getMustBeDetermining().iterator().next(), "p0");
assertTrue(response.success.orElseThrow().getNontrivialResiduals().isEmpty());
} catch (Exception e) {
fail("error: " + e.toString());
}
});
}

@Test
public void residual() {
var auth = new BasicAuthorizationEngine();
Expand Down
Loading