Skip to content

Commit

Permalink
bulk check
Browse files Browse the repository at this point in the history
  • Loading branch information
asafc committed Oct 11, 2023
1 parent fe3ce2c commit 8df3f5b
Show file tree
Hide file tree
Showing 5 changed files with 207 additions and 6 deletions.
11 changes: 7 additions & 4 deletions src/main/java/io/permit/sdk/Permit.java
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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<CheckQuery> 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);
Expand Down
19 changes: 19 additions & 0 deletions src/main/java/io/permit/sdk/enforcement/CheckQuery.java
Original file line number Diff line number Diff line change
@@ -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());
}
}
103 changes: 101 additions & 2 deletions src/main/java/io/permit/sdk/enforcement/Enforcer.java
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -26,7 +32,7 @@ class EnforcerInput {
public final User user;
public final String action;
public final Resource resource;
public final HashMap<String, Object> context;
public final Context context;

/**
* Constructs a new instance of the {@code EnforcerInput} class with the specified data.
Expand All @@ -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<String, Object> context) {
EnforcerInput(User user, String action, Resource resource, Context context) {
this.user = user;
this.action = action;
this.resource = resource;
Expand Down Expand Up @@ -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<OpaResult> 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<OpaResult> allow) {
this.allow = allow;
}
}

/**
* The {@code Enforcer} class is responsible for performing permission checks against the PDP.
* It implements the {@link IEnforcerApi} interface.
Expand Down Expand Up @@ -257,8 +279,85 @@ public boolean checkUrl(User user, String httpMethod, String url, String tenant,
}
}

@Override
public boolean[] bulkCheck(List<CheckQuery> checks) throws IOException {
List<EnforcerInput> 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<EnforcerInput> 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())
);
}
}
58 changes: 58 additions & 0 deletions src/main/java/io/permit/sdk/enforcement/IEnforcerApi.java
Original file line number Diff line number Diff line change
Expand Up @@ -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<CheckQuery> checks) throws IOException;
}
22 changes: 22 additions & 0 deletions src/test/java/io/permit/sdk/e2e/RbacE2ETest.java
Original file line number Diff line number Diff line change
@@ -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.*;
Expand All @@ -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.*;

Expand Down Expand Up @@ -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);
Expand Down

0 comments on commit 8df3f5b

Please sign in to comment.