diff --git a/src/main/java/io/permit/sdk/Permit.java b/src/main/java/io/permit/sdk/Permit.java index 295755a..8912e68 100644 --- a/src/main/java/io/permit/sdk/Permit.java +++ b/src/main/java/io/permit/sdk/Permit.java @@ -4,16 +4,14 @@ import com.google.gson.GsonBuilder; import io.permit.sdk.api.ApiClient; import io.permit.sdk.api.ElementsApi; -import io.permit.sdk.enforcement.Enforcer; -import io.permit.sdk.enforcement.IEnforcerApi; -import io.permit.sdk.enforcement.Resource; -import io.permit.sdk.enforcement.User; +import io.permit.sdk.enforcement.*; import io.permit.sdk.util.Context; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; +import java.util.List; /** * The {@code Permit} class represents the main entry point for interacting with the Permit.io SDK. @@ -133,6 +131,11 @@ public boolean checkUrl(User user, String httpMethod, String url, String tenant, return this.enforcer.checkUrl(user, httpMethod, url, tenant, context); } + @Override + public boolean[] bulkCheck(List checks) throws IOException { + return this.enforcer.bulkCheck(checks); + } + @Override public boolean checkUrl(User user, String httpMethod, String url, String tenant) throws IOException { return this.enforcer.checkUrl(user, httpMethod, url, tenant); diff --git a/src/main/java/io/permit/sdk/enforcement/CheckQuery.java b/src/main/java/io/permit/sdk/enforcement/CheckQuery.java new file mode 100644 index 0000000..afe6067 --- /dev/null +++ b/src/main/java/io/permit/sdk/enforcement/CheckQuery.java @@ -0,0 +1,19 @@ +package io.permit.sdk.enforcement; + +import io.permit.sdk.util.Context; + +import java.util.HashMap; + +/** + * The {@code CheckQuery} class represents a single permit.check() request (query) + * It is used by the bulk APIs to call many checks at once. + */ +public final class CheckQuery extends EnforcerInput { + public CheckQuery(User user, String action, Resource resource, Context context) { + super(user, action, resource, context); + } + + public CheckQuery(User user, String action, Resource resource) { + this(user, action, resource, new Context()); + } +} diff --git a/src/main/java/io/permit/sdk/enforcement/Enforcer.java b/src/main/java/io/permit/sdk/enforcement/Enforcer.java index d975daf..1cad0fe 100644 --- a/src/main/java/io/permit/sdk/enforcement/Enforcer.java +++ b/src/main/java/io/permit/sdk/enforcement/Enforcer.java @@ -1,13 +1,19 @@ package io.permit.sdk.enforcement; +import com.google.common.primitives.Booleans; import com.google.gson.Gson; import io.permit.sdk.PermitConfig; import io.permit.sdk.api.HttpLoggingInterceptor; +import io.permit.sdk.openapi.models.RoleRead; import io.permit.sdk.util.Context; import io.permit.sdk.util.ContextStore; import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; import java.util.HashMap; +import java.util.List; +import java.util.stream.Collectors; import okhttp3.MediaType; import okhttp3.OkHttpClient; @@ -26,7 +32,7 @@ class EnforcerInput { public final User user; public final String action; public final Resource resource; - public final HashMap context; + public final Context context; /** * Constructs a new instance of the {@code EnforcerInput} class with the specified data. @@ -36,7 +42,7 @@ class EnforcerInput { * @param resource The resource on which the action is performed. * @param context The context for the authorization check. */ - EnforcerInput(User user, String action, Resource resource, HashMap context) { + EnforcerInput(User user, String action, Resource resource, Context context) { this.user = user; this.action = action; this.resource = resource; @@ -76,6 +82,22 @@ class OpaResult { } } +/** + * The {@code OpaBulkResult} class represents the result of a Permit bulk enforcement check returned by the policy agent. + */ +class OpaBulkResult { + public final List allow; + + /** + * Constructs a new instance of the {@code OpaResult} class with the specified result. + * + * @param allow {@code true} if the action is allowed, {@code false} otherwise. + */ + OpaBulkResult(List allow) { + this.allow = allow; + } +} + /** * The {@code Enforcer} class is responsible for performing permission checks against the PDP. * It implements the {@link IEnforcerApi} interface. @@ -257,8 +279,85 @@ public boolean checkUrl(User user, String httpMethod, String url, String tenant, } } + @Override + public boolean[] bulkCheck(List checks) throws IOException { + List inputs = new ArrayList<>(); + + for (CheckQuery check: checks) { + Resource normalizedResource = check.resource.normalize(this.config); + inputs.add(new EnforcerInput(check.user, check.action, normalizedResource, check.context)); + } + + // request body + Gson gson = new Gson(); + String requestBody = gson.toJson(inputs); + RequestBody body = RequestBody.create(requestBody, MediaType.parse("application/json")); + + // create the request + String url = String.format("%s/allowed/bulk", this.config.getPdpAddress()); + Request request = new Request.Builder() + .url(url) + .post(body) + .addHeader("Content-Type", "application/json") + .addHeader("Authorization", String.format("Bearer %s", this.config.getToken())) + .addHeader("X-Permit-SDK-Version", String.format("java:%s", this.config.version)) + .build(); + + try (Response response = client.newCall(request).execute()) { + if (!response.isSuccessful()) { + String errorMessage = String.format( + "Error in %s: got unexpected status code %d", + bulkCheckRepr(inputs), + response.code() + ); + logger.error(errorMessage); + throw new IOException(errorMessage); + } + ResponseBody responseBody = response.body(); + if (responseBody == null) { + String errorMessage = String.format( + "Error in %s: got empty response", + bulkCheckRepr(inputs) + ); + logger.error(errorMessage); + throw new IOException(errorMessage); + } + + String responseString = responseBody.string(); + OpaBulkResult result = gson.fromJson(responseString, OpaBulkResult.class); + if (this.config.isDebugMode()) { + for (int i = 0; i < result.allow.size(); i++) { + logger.info(String.format( + "permit.bulkCheck[%d/%d](%s, %s, %s) = %s", + i + 1, + result.allow.size(), + inputs.get(i).user, + inputs.get(i).action, + inputs.get(i).resource, + result.allow.get(i).allow + )); + } + + } + return Booleans.toArray(result.allow.stream().map(r -> r.allow).collect(Collectors.toList())); + } + } + @Override public boolean checkUrl(User user, String httpMethod, String url, String tenant) throws IOException { return this.checkUrl(user, httpMethod, url, tenant, new Context()); } + + private String bulkCheckRepr(List inputs) { + return String.format( + "permit.bulkCheck(%s)", + inputs.stream().map(i -> String.format( + "%s, %s, %s, %s", + i.user, + i.action, + i.resource, + i.context + )).collect(Collectors.toList()) + ); + } } \ No newline at end of file diff --git a/src/main/java/io/permit/sdk/enforcement/IEnforcerApi.java b/src/main/java/io/permit/sdk/enforcement/IEnforcerApi.java index 1db5ed6..b2e14e2 100644 --- a/src/main/java/io/permit/sdk/enforcement/IEnforcerApi.java +++ b/src/main/java/io/permit/sdk/enforcement/IEnforcerApi.java @@ -3,10 +3,68 @@ import io.permit.sdk.util.Context; import java.io.IOException; +import java.util.List; public interface IEnforcerApi { + /** + * Checks if a `user` is authorized to perform an `action` on a `resource` within the specified context. + * + * @param user The user object representing the user. + * @param action The action to be performed on the resource. + * @param resource The resource object representing the resource. + * @param context The context object representing the context in which the action is performed. + * @return `true` if the user is authorized, `false` otherwise. + * @throws IOException if an error occurs while sending the authorization request to the PDP. + */ boolean check(User user, String action, Resource resource, Context context) throws IOException; + + /** + * Checks if a `user` is authorized to perform an `action` on a `resource` without additional context + * + * @param user The user object representing the user. + * @param action The action to be performed on the resource. + * @param resource The resource object representing the resource. + * @return `true` if the user is authorized, `false` otherwise. + * @throws IOException if an error occurs while sending the authorization request to the PDP. + */ boolean check(User user, String action, Resource resource) throws IOException; + + /** + * Performs a permission check on a (resource, action) pair that are represented by an HTTP endpoint. + * The resource and actions are extracted from the HTTP url and method. + * A tenant must be provided to determine the scope of the permission check. + * + * @param user The user object representing the user. + * @param httpMethod the HTTP method the user is calling, typically determines the action. + * @param url the url the user is calling, typically determines the resource. + * @param tenant the tenant determines the scope of the permission check. + * @return `true` if the user is authorized, `false` otherwise. + * @throws IOException if an error occurs while sending the authorization request to the PDP. + */ boolean checkUrl(User user, String httpMethod, String url, String tenant) throws IOException; + + /** + * Performs a permission check on a (resource, action) pair that are represented by an HTTP endpoint. + * The resource and actions are extracted from the HTTP url and method. + * A tenant must be provided to determine the scope of the permission check. + * Receives additional context + * + * @param user The user object representing the user. + * @param httpMethod the HTTP method the user is calling, typically determines the action. + * @param url the url the user is calling, typically determines the resource. + * @param tenant the tenant determines the scope of the permission check. + * @param context The context object representing the context in which the action is performed. + * @return `true` if the user is authorized, `false` otherwise. + * @throws IOException if an error occurs while sending the authorization request to the PDP. + */ boolean checkUrl(User user, String httpMethod, String url, String tenant, Context context) throws IOException; + + /** + * Runs multiple permission checks in a single HTTP Request (Bulk Check). + * + * @param checks The check requests, each containing user, action, resource and context. + * @return array containing `true` if the user is authorized, `false` otherwise for each check request. + * @throws IOException if an error occurs while sending the authorization request to the PDP. + */ + boolean[] bulkCheck(List checks) throws IOException; } diff --git a/src/test/java/io/permit/sdk/e2e/RbacE2ETest.java b/src/test/java/io/permit/sdk/e2e/RbacE2ETest.java index 7f24389..c6e402f 100644 --- a/src/test/java/io/permit/sdk/e2e/RbacE2ETest.java +++ b/src/test/java/io/permit/sdk/e2e/RbacE2ETest.java @@ -1,10 +1,12 @@ package io.permit.sdk.e2e; +import com.google.common.primitives.Booleans; import io.permit.sdk.PermitE2ETestBase; import io.permit.sdk.api.PermitApiError; import io.permit.sdk.api.PermitContextError; import io.permit.sdk.Permit; import io.permit.sdk.api.models.CreateOrUpdateResult; +import io.permit.sdk.enforcement.CheckQuery; import io.permit.sdk.enforcement.Resource; import io.permit.sdk.enforcement.User; import io.permit.sdk.openapi.models.*; @@ -16,6 +18,7 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; +import java.util.List; import static org.junit.jupiter.api.Assertions.*; @@ -181,6 +184,25 @@ void testPermissionCheckRBAC() { new Resource.Builder("document").withTenant(tenant.key).build() )); + logger.info("testing bulk permission check"); + boolean[] checks = permit.bulkCheck(Arrays.asList( + // positive permission check + new CheckQuery( + userInput, + "read", + new Resource.Builder("document").withTenant(tenant.key).build() + ), + // negative permission check + new CheckQuery( + User.fromString("auth0|elon"), + "create", + new Resource.Builder("document").withTenant(tenant.key).build() + ) + )); + assertEquals(checks.length, 2); + assertTrue(checks[0]); + assertFalse(checks[1]); + // change the user role permit.api.users.assignRole(user.key, admin.key, tenant.key); permit.api.users.unassignRole(user.key, viewer.key, tenant.key);