Giter Site home page Giter Site logo

casbin / jcasbin Goto Github PK

View Code? Open in Web Editor NEW
2.3K 73.0 444.0 728 KB

An authorization library that supports access control models like ACL, RBAC, ABAC in Java

Home Page: https://casbin.org

License: Apache License 2.0

Java 100.00%
casbin java access-control authorization rbac abac acl auth authz permission

jcasbin's Introduction

jCasbin

codebeat badge GitHub Actions codecov Javadocs Maven Central Release Discord

Sponsored by

Build auth with fraud prevention, faster.
Try Stytch for API-first authentication, user & org management, multi-tenant SSO, MFA, device fingerprinting, and more.

💖 Looking for an open-source identity and access management solution like Okta, Auth0, Keycloak ? Learn more about: Casdoor

casdoor

News: still worry about how to write the correct jCasbin policy? Casbin online editor is coming to help! Try it at: https://casbin.org/editor/

casbin Logo

jCasbin is a powerful and efficient open-source access control library for Java projects. It provides support for enforcing authorization based on various access control models.

All the languages supported by Casbin:

golang java nodejs php
Casbin jCasbin node-Casbin PHP-Casbin
production-ready production-ready production-ready production-ready
python dotnet c++ rust
PyCasbin Casbin.NET Casbin-CPP Casbin-RS
production-ready production-ready beta-test production-ready

Table of contents

Supported models

  1. ACL (Access Control List)
  2. ACL with superuser
  3. ACL without users: especially useful for systems that don't have authentication or user log-ins.
  4. ACL without resources: some scenarios may target for a type of resources instead of an individual resource by using permissions like write-article, read-log. It doesn't control the access to a specific article or log.
  5. RBAC (Role-Based Access Control)
  6. RBAC with resource roles: both users and resources can have roles (or groups) at the same time.
  7. RBAC with domains/tenants: users can have different role sets for different domains/tenants.
  8. ABAC (Attribute-Based Access Control): syntax sugar like resource.Owner can be used to get the attribute for a resource.
  9. RESTful: supports paths like /res/*, /res/:id and HTTP methods like GET, POST, PUT, DELETE.
  10. Deny-override: both allow and deny authorizations are supported, deny overrides the allow.
  11. Priority: the policy rules can be prioritized like firewall rules.

How it works?

In jCasbin, an access control model is abstracted into a CONF file based on the PERM metamodel (Policy, Effect, Request, Matchers). So switching or upgrading the authorization mechanism for a project is just as simple as modifying a configuration. You can customize your own access control model by combining the available models. For example, you can get RBAC roles and ABAC attributes together inside one model and share one set of policy rules.

The most basic and simplest model in jCasbin is ACL. ACL's model CONF is:

# Request definition
[request_definition]
r = sub, obj, act

# Policy definition
[policy_definition]
p = sub, obj, act

# Policy effect
[policy_effect]
e = some(where (p.eft == allow))

# Matchers
[matchers]
m = r.sub == p.sub && r.obj == p.obj && r.act == p.act

An example policy for ACL model is like:

p, alice, data1, read
p, bob, data2, write

It means:

  • alice can read data1
  • bob can write data2

Features

What jCasbin does:

  1. enforce the policy in the classic {subject, object, action} form or a customized form as you defined, both allow and deny authorizations are supported.
  2. handle the storage of the access control model and its policy.
  3. manage the role-user mappings and role-role mappings (aka role hierarchy in RBAC).
  4. support built-in superuser like root or administrator. A superuser can do anything without explicit permissions.
  5. multiple built-in operators to support the rule matching. For example, keyMatch can map a resource key /foo/bar to the pattern /foo*.

What jCasbin does NOT do:

  1. authentication (aka verify username and password when a user logs in)
  2. manage the list of users or roles. I believe it's more convenient for the project itself to manage these entities. Users usually have their passwords, and jCasbin is not designed as a password container. However, jCasbin stores the user-role mapping for the RBAC scenario.

Installation

For Maven:

<dependency>
  <groupId>org.casbin</groupId>
  <artifactId>jcasbin</artifactId>
  <version>1.x.y (replace with latest version)</version>
</dependency>

Documentation

https://casbin.org/docs/overview

Online editor

You can also use the online editor (https://casbin.org/editor/) to write your jCasbin model and policy in your web browser. It provides functionality such as syntax highlighting and code completion, just like an IDE for a programming language.

Tutorials

https://casbin.org/docs/tutorials

Get started

  1. New a jCasbin enforcer with a model file and a policy file:

    Enforcer enforcer = new Enforcer("path/to/model.conf", "path/to/policy.csv");

Note: you can also initialize an enforcer with policy in DB instead of file, see Policy persistence section for details.

  1. Add an enforcement hook into your code right before the access happens:

    String sub = "alice"; // the user that wants to access a resource.
    String obj = "data1"; // the resource that is going to be accessed.
    String act = "read"; // the operation that the user performs on the resource.
    
    if (enforcer.enforce(sub, obj, act) == true) {
        // permit alice to read data1
    } else {
        // deny the request, show an error
    }
  2. Besides the static policy file, jCasbin also provides API for permission management at run-time. For example, You can get all the roles assigned to a user as below:

    Roles roles = enforcer.getRoles("alice");

See Policy management APIs for more usage.

  1. Please refer to the src/test package for more usage.

Policy management

jCasbin provides two sets of APIs to manage permissions:

  • Management API: the primitive API that provides full support for jCasbin policy management. See here for examples.
  • RBAC API: a more friendly API for RBAC. This API is a subset of Management API. The RBAC users could use this API to simplify the code. See here for examples.

We also provide a web-based UI for model management and policy management:

model editor

policy editor

Policy persistence

https://casbin.org/docs/adapters

Role manager

https://casbin.org/docs/role-managers

Examples

Model Model file Policy file
ACL basic_model.conf basic_policy.csv
ACL with superuser basic_model_with_root.conf basic_policy.csv
ACL without users basic_model_without_users.conf basic_policy_without_users.csv
ACL without resources basic_model_without_resources.conf basic_policy_without_resources.csv
RBAC rbac_model.conf rbac_policy.csv
RBAC with resource roles rbac_model_with_resource_roles.conf rbac_policy_with_resource_roles.csv
RBAC with domains/tenants rbac_model_with_domains.conf rbac_policy_with_domains.csv
ABAC abac_model.conf N/A
RESTful keymatch_model.conf keymatch_policy.csv
Deny-override rbac_model_with_deny.conf rbac_policy_with_deny.csv
Priority priority_model.conf priority_policy.csv

Middlewares

Authz middlewares for web frameworks: https://casbin.org/docs/middlewares

Our adopters

https://casbin.org/docs/adopters

Spring Boot support

We provide Spring Boot support, you can use casbin-spring-boot-starter to quickly develop in SpringBoot

In casbin-spring-boot-starter, we made the following adjustments:

  1. Rewrite JDBCAdapter to support a variety of commonly used JDBC databases
  2. Implement RedisWatcher
  3. IDEA Editor Configuration Tips
  4. Provide default configuration, automatic assembly
  5. SpringSecurity integration (future)
  6. Shiro integration (future)

https://github.com/jcasbin/casbin-spring-boot-starter

Contributors

This project exists thanks to all the people who contribute.

Backers

Thank you to all our backers! 🙏 [Become a backer]

Sponsors

Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [Become a sponsor]

License

This project is licensed under the Apache 2.0 license.

Contact

If you have any issues or feature requests, please contact us. PR is welcomed.

jcasbin's People

Contributors

bgranvea avatar canxer314 avatar cguillot avatar chancywu avatar damienmiheev avatar dependabot[bot] avatar divy9881 avatar divyagar avatar elfisworking avatar fangzhengjin avatar hasonhuang avatar hsluoyz avatar imp2002 avatar kdebski85 avatar lmay001 avatar longxu0509 avatar m-razavi avatar nodece avatar pokisemaine avatar pzet123 avatar r4wand avatar rob-3r7o avatar roman-787 avatar rongfengliang avatar selflocking avatar seriouszyx avatar shink avatar shy1st avatar tangyang9464 avatar tldyl avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jcasbin's Issues

transitivity not respected

if I create a new group of resource from the base example, then Alice is not able to access to resources contains on this new group but only the group itself

p, alice, data1,   read
p, bob, data2, write
p, data2_admin, data2, read
p, data2_admin, data2, write
g, alice, data2_admin
g, data3, datagroup
p, data2_admin, datagroup, read

if I request like this

{
	"user":"alice",
	"resource":"data3",
	"action":"read"
}

then the answer is : NO , expected is : YES

proof :

  • alice belongs to data2_admin
  • data3 belongs to datagroup
  • permission is given READ for group of user data2_admin on group of resource datagroup
    by transitivity alice should be able to READ data3

Not validating with jCasbin

Hi,

I'm not able to enforce a policy that is working on Casbin Editor with jCasbin.

I have this conf:

[request_definition]
r = sub, obj, act, artifact

[policy_definition]
p = sub, obj, act, artifact

[role_definition]
g = _, _

[policy_effect]
e = some(where (p.eft == allow))

[matchers]
m = g(r.sub, p.sub) && keyMatch(r.act, p.act) && regexMatch(r.artifact, p.artifact)

This policy file:

p, group_app1_manager, schema, promote, .*APP1
p, group_app1_manager, schema, get, .*APP1
p, group_app1_manager, schema, create, .*APP1
p, group_app1_manager, schema, get, .*APP1
p, group_app1_manager, topic, create, .*APP1

p, group_app1_viewer, topic, list, .*APP1
p, group_app1_viewer, topic, get, .*APP1
p, group_app1_viewer, schema, get, .*APP1
p, group_app1_viewer, schema, list, .*APP1

p, group_dsp_admin, *, *, .*

g, admin, group_dsp_admin
g, viewer, group_app1_viewer
g, manager, group_app1_manager

My code:

    @Test
    public void givenViewerUser_ThenList_MustAllow() {
        assertTrue(enforcer.enforce("viewer", "schema", "list", "europe-west1-APP1-SALES-BY-LOCATION-value"));
    }

My application log:

16:28:36.360 [main] INFO  org.casbin.jcasbin - Model:
16:28:36.361 [main] INFO  org.casbin.jcasbin - p.p: sub, obj, act, artifact
16:28:36.361 [main] INFO  org.casbin.jcasbin - r.r: sub, obj, act, artifact
16:28:36.361 [main] INFO  org.casbin.jcasbin - e.e: some(where (p_eft == allow))
16:28:36.361 [main] INFO  org.casbin.jcasbin - g.g: _, _
16:28:36.361 [main] INFO  org.casbin.jcasbin - m.m: g(r_sub, p_sub) && keyMatch(r_act, p_act) && regexMatch(r_artifact, p_artifact)
16:28:36.370 [main] INFO  org.casbin.jcasbin - Policy:
16:28:36.370 [main] INFO  org.casbin.jcasbin - p: sub, obj, act, artifact: [[group_app1_manager, schema, promote, .*APP1], [group_app1_manager, schema, get, .*APP1], [group_app1_manager, schema, create, .*APP1], [group_app1_manager, schema, get, .*APP1], [group_app1_manager, topic, create, .*APP1], [group_app1_viewer, topic, list, .*APP1], [group_app1_viewer, topic, get, .*APP1], [group_app1_viewer, schema, get, .*APP1], [group_app1_viewer, schema, list, .*APP1], [group_dsp_admin, *, *, .*]]
16:28:36.370 [main] INFO  org.casbin.jcasbin - g: _, _: [[admin, group_dsp_admin], [viewer, group_app1_viewer], [manager, group_app1_manager]]
16:28:36.371 [main] INFO  org.casbin.jcasbin - Role links for: g
16:28:36.371 [main] INFO  org.casbin.jcasbin - viewer < group_app1_viewer
16:28:36.371 [main] INFO  org.casbin.jcasbin - group_app1_viewer < 
16:28:36.371 [main] INFO  org.casbin.jcasbin - manager < group_app1_manager
16:28:36.371 [main] INFO  org.casbin.jcasbin - group_dsp_admin < 
16:28:36.371 [main] INFO  org.casbin.jcasbin - group_app1_manager < 
16:28:36.371 [main] INFO  org.casbin.jcasbin - admin < group_dsp_admin
16:28:36.454 [main] INFO  org.casbin.jcasbin - Request: viewer, schema, list, europe-west1-APP1-SALES-BY-LOCATION-value ---> false

Any ideas?

Thanks a lot!

ABAC + RBAC mixture model: How to use custom function with enforcer

As we know only request is permissible to have object and object to be associated with functions in matcher definition.

Currently I want to create the Intimefunction in which I want to provide limited time admin access or privilege access to certain users.

I have created the function and added the same using enforcer.addFunction(name, function(instance)).

Do I not require to input any policies according to the limited access, Actually it may become mixture of RBAC and ABAC.
I want to know how to enforce the above criteria, how to pass the enforcing on the parameters or on what condition I need to check

Integrate casbin with jsf

Hi, I need to use casbin with jsf for my project. Is there any taglib available for jsf which can be used for role based page display ?

How to define new matcher function?

I've written a function but now how should add it to function map?

public class InCollectionFunc extends AbstractFunction {
    public InCollectionFunc() {
    }

    public AviatorObject call(Map<String, Object> env, AviatorObject arg1, AviatorObject arg2, AviatorObject arg3) {
        String value = FunctionUtils.getStringValue(arg1, env);
        String collection = FunctionUtils.getStringValue(arg3, env);
        return AviatorBoolean.valueOf(isInCollection(value, collection));
    }

    private boolean isInCollection(String value,String collection) {
        System.out.println("value:" + value + " isIn collection:" + collection);
        return true;
    }

    public String getName() {
        return getNameStatic();
    }

    public static String getNameStatic() {
        return "isIn";
    }
}
enforcer = new Enforcer("erole.conf", "policy.csv");
enforcer.addFunction(InCollectionFunc.getNameStatic(),new InCollectionFunc());

Question: Is there a way to persist policy and model?

Use case is that I have a program that takes a model and a policy path and to test it I'd like to be able to do something like

Model m = newModel();
m.addDef("r", "r", "sub, obj, act");
m.addDef("p", "p", "sub, obj, act");
m.addDef("g", "g", "_, _");
m.addDef("e", "e", "some(where (p.eft == allow))");
m.addDef("m", "m", "g(r.sub, p.sub) && r.obj == p.obj && r.act == p.act");

Enforcer e = new Enforcer(m);

e.addPermissionForUser("alice", "data1", "read");
Path modelURI = e.persistModel();
Path policyURI = e.persistPolicy();

assertTrue(new myProgram(modelURI, policyURI).isAuth("alice", "read"))

Integration with Apache Shiro and Spring Security

In Java world, Apache Shiro and Spring Security are very popular security frameworks. We need to find ways to wrap jCasbin into a middleware of the above both, so Shiro and Spring users can use jCasbin without much migration efforts.

jcasbin maven related issue

image
Hello I am a jcasbin user. I thank you for the great project. I am using maven.

  • What I noticed is the jar that comes from maven is called jcasbin-1.2.0. the current version is 1.4.0 this must be a mistake right?

  • also the exceptions are not included in the jar

  • FileAdapter with Inputstream is not included as well in the maven version, which is very useful

How to Define ABAC roles

Hi
I want to use ABAC authorization for one of my application but I don't how to define roles and policies.
Let me describe the scenario:
1-Subject: There roles(Operator, Manager, Reviewer) and each User has a Branch.
2- Resource: There are several Object (Order, Document,..), and each Object has a Branch.
3- Actions: There are some actions such as Create, Edit, View, Confirm, Reject.

Some policies:
1- All User can View to objects if object.branch in user.branch
2- All user can do actions on objects during wroking time (8:30 - 17:00)
3- Manager can View to objects whenever they want.
4- User with name X has Branch A,B.
5- Manager can do Confirm and Reject.
6- Operator can do View and Create
7- Reviewer can only view objects if object. status= confirmed.

Would you please help me how to define these scenario?

roles

[Need help] How to secure a Rest api?

I want to secure a REST-Api with jcasbin. But i dont get the right place to start.

Is this the right practice?

URL: /api/v1/user/10

public Result showUser(int id){
       User user = UserService.getUser(id);
       if(isAllowed(session.get(userID), 10, GET)){
              return success;
       }else{
              return error;
       }
}

private boolean isAllowed(String userId, String data, String action){
       enforcer.addPolicy(userId, data, action);
       return enforcer.enforce(userId, data, action);
}

config-file:

[request_definition]
r = acc, obj, act

[policy_definition]
p = sub, obj, act

[policy_effect]
e = some(where (p.eft == allow))

[matchers]
m = r.acc== p.acc && r.obj == p.obj && r.act == p.act

I'm asking this because of:

I can not set policys in advance, because i dont know all users
I can not set policiys in advance, because i dont know the id of the resource
I can not set policiys in advance, because i dont know the Action of the request
Maybe im stupid but i dont get it ................ in german it is called "auf dem Schlauch stehen" (stand on the hose)

Could you show me a short REST-Example in Java where i could start? Is my example useable? I dont think so, because of the enforcer.addPolicy(userId, data, action); call ....

Benchmark for SyncedEnforcer

I am trying to get benchmark for SyncedEnforcer and found that increasing threadPool size won't increase the qps for enforce because write lock is used when function syncedEnforcer.enforce() is called. However, in golang version, they use read lock instead. Does that mean the golang benchmark for SyncedEnforcer would be much higher than jcasbin? I'm curious why a write lock is needed in enforce phase since no policy is changed.

springboot fatjar can't read casbin config resources

when I maven package my springboot project as a fatjar, then i run commed java -jar, here are some exception stack messages below.

Caused by: org.casbin.jcasbin.exception.CasbinConfigException: file:\C:\Users\lenovo\Desktop\pgcm-1.0-SNAPSHOT-exec.jar!\BOOT-INF\classes!\casbin\rbac_model.conf (文件名、目录名或卷标语法不正确。)
        at org.casbin.jcasbin.config.Config.parse(Config.java:92) ~[jcasbin-1.4.0.jar!/:na]
        at org.casbin.jcasbin.config.Config.newConfig(Config.java:49) ~[jcasbin-1.4.0.jar!/:na]
        at org.casbin.jcasbin.model.Model.loadModel(Model.java:108) ~[jcasbin-1.4.0.jar!/:na]
        at org.casbin.spring.boot.autoconfigure.CasbinAutoConfiguration.enforcer(CasbinAutoConfiguration.java:100) ~[casbin-spring-boot-starter-0.0.8.jar!/:na]

and here is org.casbin.jcasbin.config.Config.parse method below

private void parse(String fname) {
        lock.lock();
        try (FileInputStream fis = new FileInputStream(fname)) {
            BufferedReader buf = new BufferedReader(new InputStreamReader(fis));
            parseBuffer(buf);
        } catch (IOException e) {
            throw new CasbinConfigException(e.getMessage(), e.getCause());
        } finally {
            lock.unlock();
        }
    }

then I found a question inStackOverflow, https://stackoverflow.com/questions/25869428/classpath-resource-not-found-when-running-as-jar

I don't know this is a bug or not, and how to do my problem, hope u can reply me soon.

Delete Permission throw an exception

when I invocke enforcer.deletePermission(perm) while I have no permission assigned to anyone(no this perm record), it throws the following exception:
CasbinAdapterException: Remove filtered policy error, remove 0 rows, expect least 1 rows

I'm using the default model(no conf file).

Help: java.io.FileNotFoundException

    mEnforcer = new Enforcer("excomple/permission_model.conf", "excomple/permission_policy.csv");

Error:
java.io.FileNotFoundException: \excomple\permission_model.conf (系统找不到指定的路径。)

Multi-line mode Matcher not work

If appending '\' at the end of Line, an ExpressionSyntaxErrorException occurs

[request_definition]
r = sub, dom, obj, act

[policy_definition]
p = sub, dom, obj, act, eft

[role_definition]
g = _, _,; user group
g2 = _, _, _ ; group role
g3 = _, _, _ ; resource group

[policy_effect]
e = some(where (p.eft == allow)) && !some(where (p.eft == deny))

[matchers]
m = (g(r.sub, p.sub) || g2(r.sub, p.sub, r.dom)) && (keyMatch(r.obj, p.obj) || g3(r.obj, p.obj, r.dom)) \
    && (p.dom == 'public' || r.dom == p.dom) && keyMatch(r.act, p.act)
Caused by: com.googlecode.aviator.exception.ExpressionSyntaxErrorException: Syntax error:Unexpect token '\' at 100, current token: [type='Char',lexeme='\',index=100]. Parsing expression: `(g(r_sub, p_sub) || g2(r_sub, p_sub, r_dom)) && (keyMatch(r_obj, p_obj) || g3(r_obj, p_obj, r_dom)) \^^`
	at com.googlecode.aviator.parser.ExpressionParser.reportSyntaxError(ExpressionParser.java:765)
	at com.googlecode.aviator.parser.ExpressionParser.parse(ExpressionParser.java:791)
	at com.googlecode.aviator.AviatorEvaluatorInstance.innerCompile(AviatorEvaluatorInstance.java:673)
	at com.googlecode.aviator.AviatorEvaluatorInstance.access$000(AviatorEvaluatorInstance.java:109)
	at com.googlecode.aviator.AviatorEvaluatorInstance$2.call(AviatorEvaluatorInstance.java:641)
	at com.googlecode.aviator.AviatorEvaluatorInstance$2.call(AviatorEvaluatorInstance.java:638)
	at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
	at com.googlecode.aviator.AviatorEvaluatorInstance.compile(AviatorEvaluatorInstance.java:648)

Potential partial/complete dataloss in savePolicy.

Failure in the savePolicy function can lead to a complete loss of all data because savePolicy doesn't use transactions AND:

  1. First drops the table
  2. Recreates the table.
  3. Executes a batch of inserts to save the policy.

If 1 succeed and a failure occurs anytime after it can lead to a partial or complete data loss.

It'd be much safer if it:

  1. Started a transaction
  2. Deleted everything in the table (not drop table, mysql doesn't support DML transactions)
  3. Inserted the new policy.
  4. Committed the transaction.

I actually don't see any usage of transactions in this Adapter, which is worrisome, but maybe I'm missing something?

tenant feature is not working using transitivity

Giving this model (user groups, resource groups and tenants enabled), and this policies :

Model:
2019-04-02 09:52:12.053  INFO 28508 --- [           main] org.casbin.jcasbin                       : p.p: sub, obj, act, dom
2019-04-02 09:52:12.053  INFO 28508 --- [           main] org.casbin.jcasbin                       : r.r: sub, obj, act, dom
2019-04-02 09:52:12.053  INFO 28508 --- [           main] org.casbin.jcasbin                       : e.e: some(where (p_eft == allow))
2019-04-02 09:52:12.053  INFO 28508 --- [           main] org.casbin.jcasbin                       : g.g: _, _, _
2019-04-02 09:52:12.053  INFO 28508 --- [           main] org.casbin.jcasbin                       : g.g2: _, _, _
2019-04-02 09:52:12.053  INFO 28508 --- [           main] org.casbin.jcasbin                       : m.m: g(r_sub, p_sub) && r_dom == p_dom && g2(r_obj, p_obj) && r_act == p_act
2019-04-02 09:52:12.062  INFO 28508 --- [           main] org.casbin.jcasbin                       : Policy:
2019-04-02 09:52:12.063  INFO 28508 --- [           main] org.casbin.jcasbin                       : p: sub, obj, act, dom: [[alice, data1, read, domain1], [bob, data2, write, domain1], [data2_admin, data2, read, domain1], [data2_admin, data2, write, domain1], [data2_admin, datagroup, read, domain1]]
2019-04-02 09:52:12.063  INFO 28508 --- [           main] org.casbin.jcasbin                       : g: _, _, _: [[alice, data2_admin, domain1]]
2019-04-02 09:52:12.063  INFO 28508 --- [           main] org.casbin.jcasbin                       : g2: _, _, _: [[data3, datagroup, domain1]]
2019-04-02 09:52:12.063  INFO 28508 --- [           main] org.casbin.jcasbin                       : Role links for: g
2019-04-02 09:52:12.063  INFO 28508 --- [           main] org.casbin.jcasbin                       : domain1::data2_admin < 
2019-04-02 09:52:12.063  INFO 28508 --- [           main] org.casbin.jcasbin                       : domain1::alice < domain1::data2_admin
2019-04-02 09:52:12.063  INFO 28508 --- [           main] org.casbin.jcasbin                       : Role links for: g2
2019-04-02 09:52:12.063  INFO 28508 --- [           main] org.casbin.jcasbin                       : domain1::data2_admin < 
2019-04-02 09:52:12.064  INFO 28508 --- [           main] org.casbin.jcasbin                       : domain1::data3 < domain1::datagroup
2019-04-02 09:52:12.064  INFO 28508 --- [           main] org.casbin.jcasbin                       : domain1::alice < domain1::data2_admin
2019-04-02 09:52:12.064  INFO 28508 --- [           main] org.casbin.jcasbin                       : domain1::datagroup < 

when asking if alice can read data3 on domain 1, it says no. alice belongs to group data2_admin and data3 belongs to datagroup. a policy says that data2_admin can read on datagroup on domain 1 ... so ? why it does not work ?

2019-04-02 09:56:03.406  INFO 28508 --- [nio-8080-exec-6] org.casbin.jcasbin                       : Request: alice, data3, read, domain1 ---> false

ps : this example was working when not using tenant feature
pps : btw, I don not understand why logs are showing users and user groups on g2 group here Role links for: g2 ... that should concern only resources and group resources
pps : these are parameters coming from debug : {r_sub=alice, p_act=read, p_dom=domain1, r_act=read, r_dom=domain1, p_sub=data2_admin, r_obj=data3, p_obj=datagroup} where result from expression gives false

r: alice, data3, read, domain1
p: data2_admin, datagroup, read, domain1

NullPointer appears in hasRoleForUser

image

This should be a design issue with getRolesForUser.
When user does not assign role, it should return empty list instead of null.
Similarly, the same should be true for getUsersForRole, getRolesForUserInDomain, etc.

nullPointer at Enforcer

cas
Capturecas
null

It doesn't reach the condition , when I instanciate the Enforcer I immediatly entre the exception , please help

Fix the javadoc errors

When I try to release this repo into Maven with the following command,

mvn clean deploy -P sonatype-oss-release -Darguments="gpg.passphrase=xxxxxx"

I encountered the javadoc errors. It seems that our javadocs are in wrong format.

[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  01:35 min
[INFO] Finished at: 2020-09-29T22:55:43+08:00
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-javadoc-plugin:2.7:jar (attach-javadocs) on project jcasbin: MavenReportException: Error while creati
ng archive:
[ERROR] Exit code: 1 - F:\github_repos\jcasbin\src\main\java\org\casbin\jcasbin\main\InternalEnforcer.java:104: warning: no @param for op
[ERROR]     public void buildIncrementalRoleLinks(Model.PolicyOperations op, String ptype, List<List<String>> rules) {
[ERROR]                 ^
[ERROR] F:\github_repos\jcasbin\src\main\java\org\casbin\jcasbin\main\InternalEnforcer.java:104: warning: no @param for ptype
[ERROR]     public void buildIncrementalRoleLinks(Model.PolicyOperations op, String ptype, List<List<String>> rules) {
[ERROR]                 ^
[ERROR] F:\github_repos\jcasbin\src\main\java\org\casbin\jcasbin\main\InternalEnforcer.java:104: warning: no @param for rules
[ERROR]     public void buildIncrementalRoleLinks(Model.PolicyOperations op, String ptype, List<List<String>> rules) {
[ERROR]                 ^
[ERROR] F:\github_repos\jcasbin\src\main\java\org\casbin\jcasbin\model\Policy.java:251: error: bad use of '>'
[ERROR]      * @return succeeds(effects.size() > 0) or not.
[ERROR]                                        ^
[ERROR] F:\github_repos\jcasbin\src\main\java\org\casbin\jcasbin\rbac\DefaultRoleManager.java:59: error: @param name not found
[ERROR]      * @param domainMatchingPredicate a matcher for supporting domain pattern in g
[ERROR]               ^
[ERROR] F:\github_repos\jcasbin\src\main\java\org\casbin\jcasbin\rbac\DefaultRoleManager.java:61: warning: no @param for domainMatchingFunc
[ERROR]     public DefaultRoleManager(int maxHierarchyLevel, final BiPredicate<String, String> matchingFunc,
[ERROR]            ^
[ERROR] F:\github_repos\jcasbin\src\main\java\org\casbin\jcasbin\util\BuiltInFunctions.java:131: warning: no @param for key1
[ERROR]     public static boolean keyMatch4(String key1, String key2) {
[ERROR]                           ^
[ERROR] F:\github_repos\jcasbin\src\main\java\org\casbin\jcasbin\util\BuiltInFunctions.java:131: warning: no @param for key2
[ERROR]     public static boolean keyMatch4(String key1, String key2) {
[ERROR]                           ^
[ERROR] F:\github_repos\jcasbin\src\main\java\org\casbin\jcasbin\util\BuiltInFunctions.java:131: warning: no @return
[ERROR]     public static boolean keyMatch4(String key1, String key2) {
[ERROR]                           ^
[ERROR]
[ERROR] Command line was: "C:\Program Files\Java\jdk1.8.0_261\jre\..\bin\javadoc.exe" @options @packages
[ERROR]
[ERROR] Refer to the generated Javadoc files in 'F:\github_repos\jcasbin\target\apidocs' dir.
[ERROR]
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException

@tldyl can you fix it so I can release new versions?

Save model in Databse

Is it possible to save whole model in databse. (Currently the Adaptor implementations (File & JDBC) only save g,p section of model into database.)

abac with roles

Hi,

I want to use the abac part of jcasbin to secure my restful endpoints.

I want to be able to define groups and write a matcher that will combine group permissions and user permissions

p, alice, data1, read
p, bob, data2, write
p, data2_admin, data2, read
p, data2_admin, data2, write
g, alice, data2_admin
[request_definition]
r = sub, obj, act

[policy_definition]
p = sub, obj, act

[role_definition]
g = _, _

[policy_effect]
e = some(where (p.eft == allow))

[matchers]
m = (g(r.sub, p.sub) || r.sub == r.obj.owner) && r.obj == p.obj && r.act == p.act

is this correct syntax?

thanks!

API enhancement requirement: batch object API for permission validation

HI there,
I have a requirement in our business to validate the permission for inputed multiple objects and filter the objects which current user don't have permission to access, it seems that current verion API can't support it, please assess if can be added in your furture version, if this could not be in your scope, batch api for permission validation is also ok,that would be highly appreciate if scheduled release date could be provided, thanks!

delete user does not work

if I delete a user it does not delete it but it removes him from all groups
if i can enforce , permissions remain so i can still get a positive access answer using this user

suggestion: allow to query enforcer for number of expected parameters for enforce call

Given the different styles of supported models and the fact that the data source might be unknown/out of our control it would be useful to be able to determine the number of parameters required for a call to `enforcer#enforce(...)#.

Or at least fail with something better than Method threw 'java.lang.ArrayIndexOutOfBoundsException' exception.

e.g.

enforcer.enforce("alice","data1","read")

would thrown an exception for

p, admin, domain1, data1, read
p, admin, domain1, data1, write
p, admin, domain2, data2, read
p, admin, domain2, data2, write

g, alice, admin, domain1
g, bob, admin, domain2

but would succeed for

p, alice, data1, read
p, bob, data2, write
p, data_group_admin, data_group, write

g, alice, data_group_admin
g2, data1, data_group
g2, data2, data_group

I thought I could guess it from enforcer.getAllActions() but in the 1st case this returns
actions:[data1, data1, data2, data2]
while in the 2nd it (correctly) returns
actions:[read, write, write]

I think this particular scenario would be solvable with enforcer.getAllDomains() but is not very scalable as a solution for future changes.

Performance problem of CoreEnforcer.enforce

In my use case of jcasbin, I have many calls of CoreEnforcer.enforce and this becomes a performance bottleneck. The root cause seems to be in these lines:

        AviatorEvaluatorInstance eval = AviatorEvaluator.newInstance();
[...]
        String expString = model.model.get("m").get("m").value;
        Expression expression = eval.compile(expString);

The compiled expression is very likely to be the same each time and it is parsed and recompiled each time. Shouldn't we instanciate AviatorEvaluatorInstance only once and use eval.compile(expString, true) to get a cached expression?

NullPointerException occurred when init with empty policy

Member functions of Policy class do not check if the key ptype exists in the map, so when I tried to call enforcer.addPolicy() or enforcer.getPolicy() after init enforcer with empty policy, NullPointerException was throw. Is it a design issue? Ptype's existence should be checked and if it does not exist, empty list should be returned, not NullPointerException.

The benchmark for jcasbin

Hi there,
As we may have millions of policies in our business, not sure the currect framework could support such so large policies? if it will cause the OOM issue? or other perfromance issues? is there a benchmark for jcasbin? thanks.

calling enforce with group of grants feature does not work

Calling function com.se.datahub.main.CoreEnforcer.enforce(CoreEnforcer.java:345) with arguments : [alice, data3, read] ends with error below :

2019-04-19 14:24:58.543  INFO 4856 --- [io-8080-exec-10] org.casbin.jcasbin                       : Policy Rule: [alice, data1, read]
2019-04-19 14:24:58.543  INFO 4856 --- [io-8080-exec-10] org.casbin.jcasbin                       : Result: false
2019-04-19 14:24:58.543  INFO 4856 --- [io-8080-exec-10] org.casbin.jcasbin                       : Policy Rule: [bob, data2, write]
2019-04-19 14:24:58.543  INFO 4856 --- [io-8080-exec-10] org.casbin.jcasbin                       : Result: false
2019-04-19 14:24:58.543  INFO 4856 --- [io-8080-exec-10] org.casbin.jcasbin                       : Policy Rule: [data2_admin, data2, read]
2019-04-19 14:24:58.543  INFO 4856 --- [io-8080-exec-10] org.casbin.jcasbin                       : Result: false
2019-04-19 14:24:58.543  INFO 4856 --- [io-8080-exec-10] org.casbin.jcasbin                       : Policy Rule: [data2_admin, data2, write]
2019-04-19 14:24:58.543  INFO 4856 --- [io-8080-exec-10] org.casbin.jcasbin                       : Result: false
2019-04-19 14:24:58.543  INFO 4856 --- [io-8080-exec-10] org.casbin.jcasbin                       : Policy Rule: [data2_admin, datagroup, read]
2019-04-19 14:24:58.546 ERROR 4856 --- [io-8080-exec-10] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is com.googlecode.aviator.exception.ExpressionRuntimeException: Execute expression error] with root cause

java.lang.IllegalArgumentException: Wrong number of args (1) passed to: g3
	at com.googlecode.aviator.runtime.function.AbstractFunction.throwArity(AbstractFunction.java:19) ~[aviator-4.1.2.jar:na]
	at com.googlecode.aviator.runtime.function.AbstractFunction.call(AbstractFunction.java:47) ~[aviator-4.1.2.jar:na]
	at Script_1555676698541_2/1743385755.execute0(Unknown Source) ~[na:na]
	at com.googlecode.aviator.ClassExpression.execute(ClassExpression.java:72) ~[aviator-4.1.2.jar:na]
	at com.se.datahub.main.CoreEnforcer.enforce(CoreEnforcer.java:345) ~[classes/:na]
	at com.se.datahub.rest.EnforcementController.enforce(EnforcementController.java:21) ~[classes/:na]

ABAC roles

Hi.
I want to use the abac part of jcasbin. The problem is that I couldn't find where to define the attributes variables , example (r_obj.owner, r.sub.branch).

For this example that already exists:

[request_definition]
r = sub, obj, act

[policy_definition]
p = sub, obj, act

[role_definition]
g = _, _

[policy_effect]
e = some(where (p.eft == allow))

[matchers]
m = (g(r.sub, p.sub) || r.sub == r.obj.owner) && r.obj == p.obj && r.act == p.act
I got this: Exception in thread "main" com.googlecode.aviator.exception.ExpressionRuntimeException: Could not find variable r_obj.owner
	at com.googlecode.aviator.runtime.type.AviatorJavaType.getProperty(AviatorJavaType.java:301)
	at com.googlecode.aviator.runtime.type.AviatorJavaType.getValue(AviatorJavaType.java:251)
	at com.googlecode.aviator.runtime.type.AviatorJavaType.compare(AviatorJavaType.java:381)
	at Script_1551791355988_0/1869997857.execute0(Unknown Source)
	at com.googlecode.aviator.ClassExpression.execute(ClassExpression.java:72)
	at org.casbin.jcasbin.main.CoreEnforcer.enforce(CoreEnforcer.java:345)
	at Server.main(Server.java:131)
.....

Would you please help me!
Thanks

Whether MySQL 8 is supported?

There will be parameters in the URL of MySQL 8. Do you want to confirm whether MySQL 8 is supported? What do you do if you support the parameters in the URL?

image

image

image

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.