Giter Site home page Giter Site logo

casbin / casbin-cpp Goto Github PK

View Code? Open in Web Editor NEW
219.0 11.0 61.0 3.18 MB

An authorization library that supports access control models like ACL, RBAC, ABAC in C/C++

Home Page: https://casbin.org

License: Apache License 2.0

C++ 97.53% C 0.33% CMake 0.95% Python 1.19%
casbin c cpp access-control authorization rbac abac permission access-control-list role-based-access-control attribute-based-access-control acl

casbin-cpp's Introduction

Casbin-CPP

CI GitHub release (latest by date) semantic-release Discord

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

casdoor

News: Are you still worried about how to write the correct Casbin policy? Casbin online editor is coming to help! Try it at: http://casbin.org/editor/

Build Availability on Platforms:

Operating Systems Availability status
Windows (VS C++) ✔️ Available
Linux ✔️ Available
macOS ✔️ Available

casbin Logo


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

Note: PyCasbin-on-CPP is available to use. Refer to the documentation for installation and usage.

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 Casbin, 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 Casbin 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 Casbin 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 explict 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 Casbin 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 Casbin is not designed as a password container. However, Casbin stores the user-role mapping for the RBAC scenario.

Documentation

https://casbin.org/docs/overview

Online editor

You can also use the online editor (https://casbin.org/editor/) to write your Casbin 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

Integrating Casbin to your project through CMake

Without installing casbin locally

Here is a working project to demonstarte how to set up your CMake configurations to integrate casbin without any prior installations.

You may integrate casbin into your CMake project through find_package. It is assumed that you're using CMake >= v3.19.

You must have casbin installed on your system OR have it fetched from GitHub through FetchContent.

Here's what your Findcasbin.cmake file should be:

include(FetchContent)

FetchContent_Declare(
        casbin
        GIT_REPOSITORY https://github.com/casbin/casbin-cpp.git
        GIT_TAG v1.38.1
)

set(CASBIN_BUILD_TEST OFF)            # If you don't need to build tests for casbin
set(CASBIN_BUILD_BENCHMARK OFF)       # If you don't need to build benchmarks for casbin
set(CASBIN_BUILD_BINDINGS OFF)        # If you don't need language bindings provided by casbin
set(CASBIN_BUILD_PYTHON_BINDINGS OFF) # If you don't need python bindings provided by casbin

# Making casbin and its targets accessible to our project
FetchContent_MakeAvailable(casbin)

FetchContent_GetProperties(casbin)

# If casbin wasn't populated, then manually populate it
if(NOT casbin_POPULATED)
    FetchContent_Populate(casbin)
    add_subdirectory(${casbin_SOURCE_DIR} ${casbin_BINARY_DIR})
endif()

Now that casbin's targets are available to your project, your may link your own targets against casbin's likewise:

add_executable(myexec main.cpp)

target_link_libraries(myexec PRIVATE casbin)

set(myexec_INCLUDE_DIR ${casbin_SOURCE_DIR}/include)
target_include_directories(myexec PRIVATE ${myexec_INCLUDE_DIR})

Do remember to include casbin_SOURCE_DIR/include directory wherever casbin's functions are utilised.

With local installation

You may integrate casbin into your CMake project through find_package. It is assumed that you're using CMake >= v3.19

  1. Clone/checkout to casbin/casbin-cpp:master

    git clone https://github.com/casbin/casbin-cpp.git
  2. Open terminal/cmd in the root directory of the project:

    mkdir build
    cd build
    cmake ..

    Note: Look up for the logs of this step. And add the path indicated by the log into your PATH/project include directory. The log message you're looking for should be something like this:

    [casbin]: Installing casbin ...
    [casbin]: Installing casbin ... -  The targets can now be imported with find_package(casbin)
    [casbin]: Build the "install" target and add "/usr/local/include" to you PATH for casbin to work
  3. After the project is configured successfully, build it:

    cmake --build . --config Release
  4. Install casbin:

    cmake --build . --config Release --target install

    Now, casbin has been installed and ready to go.

  5. In your project's CMake file, add

    find_package(casbin REQUIRED)

    This will import all the targets exported by casbin to your project

  6. Link against casbin (Refer to Step 2's Note to get the value of MY_INCLUDE_DIR for your system):

    set(MY_INCLUDE_DIR "/usr/local/include")
    target_include_directories(MyTargetName PRIVATE ${MY_INCLUDE_DIR})
    target_link_libraries(MyTargetName PRIVATE casbin::casbin)

Installation and Set-Up

Build instructions for all platforms

(Assuming you have CMake v3.19 or later installed)

  1. Clone/checkout to casbin/casbin-cpp:master

    git clone https://github.com/casbin/casbin-cpp.git
  2. Open terminal/cmd in the root directory of the project:

    Note: On Windows, this command will also create Visual Studio project files in the /build directory.

    mkdir build
    cd build
    cmake ..
  3. After the project is configured successfully, build it:

    cmake --build .
  4. To install casbin library to your machine run:

    cmake --build . --target install
    • For Windows, this will install casbin.lib to <custom-path>/casbin-cpp/build/casbin and the headers to C:/Program Files/casbin/include.
    • For Unix based OS i.e. Linux and macOS, this will install casbin.a to <custom-path>/casbin-cpp/build/casbin and the headers to usr/local/include.

    You can add the respective include and lib paths to the PATH environment variable to use casbin.

  5. (OPTIONAL) To run the tests, issue the following command from /build:

    ctest

Get started

  1. Add the include directory of the project to the PATH Environment variable.

    #include <casbin/casbin.h>
  2. Make a new a casbin::Enforcer with a model file and a policy file:

    casbin::Enforcer e("./path/to/model.conf", "./path/to/policy.csv");
  3. Add an enforcement hook into your code right before the access happens:

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

    std::vector<std::string> roles( e.GetImplicitRolesForUser(sub) );

Here's the summary:

#include <casbin/casbin.h>
#include <string>

void IsAuthorized() {
    casbin::Enforcer e("./path/to/model.conf", "./path/to/policy.csv");

    std::string sub = "alice"; // the user that wants to access a resource.
    std::string obj = "data1"; // the resource that is going to be accessed.
    std::string act = "read"; // the operation that the user performs on the resource.

    if(e.Enforce({ sub, obj, act })) {
        // permit alice to read data1
    } else {
        // deny the request, show an error
    }
}

Policy management

Casbin provides two sets of APIs to manage permissions:

  • Management API: the primitive API that provides full support for Casbin policy management.
  • 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.

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

model editor

policy editor

Policy persistence

https://casbin.org/docs/adapters

Policy consistence between multiple nodes

https://casbin.org/docs/watchers

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

How to Contribute

Please read the contributing guide.

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.

casbin-cpp's People

Contributors

ailiujiarui avatar alexeychashchegorov avatar arashpartow avatar ba7lya avatar bigcat26 avatar com8 avatar cs1137195420 avatar divy9881 avatar emperoryp7 avatar hsluoyz avatar jalinwang avatar karanaljx avatar lezli01 avatar newbieorange avatar nodece avatar noob20000405 avatar pdldelange avatar pokisemaine avatar polbreachity avatar riptide3 avatar selflocking avatar sheny1xuan avatar uran0sh avatar yyy1000 avatar zipochan 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

casbin-cpp's Issues

AddFunction is not working as expect

branch: v1.11.2
I'm trying to add my custom matcher function like this:

ReturnType myMatcher(Scope scope) 
{
    string key1 = GetString(scope, 0);
    string key2 = GetString(scope, 1);
    PushBooleanValue(scope, true);
    return RETURN_RESULT;
}

int main()
{
    auto model = make_shared<Model>();
    ...
    model->AddDef("m", "m", "g(r.sub, p.sub) && myMatcher(r.obj, p.obj) && regexMatch(r.act, p.act)");

    Enforcer e = Enforcer(model, adapter);
    e.AddFunction("myMatcher", myMatcher, 2);
    if (e.Enforce({ ... })) {
    }
}

When I debug the program, stepped over e.Enforce, it does not invoke myMatcher.

The problem is that a new scope was create in EnforceWithMatcher to evaluate params, but my custom matcher is not in that scope.

Python bindings to facilitate PyCasbin-on-CPP

The project has the potential to utilize its C++ API for PyCasbin-on-CPP through Python bindings which will allow us to call C++ code from Python. CPython exposes various endpoints for us to make bindings, but this approach will be cumbersome and vulnerable to a lot of errors and memory leaks which won't be easy to debug. pybind11 can be used for making Python bindings and modules with C++11 as it is based on Boost::Python library.

[Test] Error in locating Test Entities in Xcode

Description

The target casbin_benchmark is throwing casbin::MissingRequiredSections exception.

Screenshot

Screenshot 2021-08-05 at 10 44 02 PM

Approaches

I think this is due to hardcoding the relative path into tests/benchmark/config_path.h

Screenshot 2021-08-05 at 10 46 32 PM

Performance issues

  • m_enforce lacks the clearing of the function lists of m_func_map
  • split.cpp has a 100k std::string vector reservation which makes enforcement take a lot longer than necessary

Got wrong enforce result if there are keyMatch or regexMatch

Model

[request_definition]
r = sub, obj, act

[policy_definition]
p = sub, obj, act

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

[matchers]
m = r.sub == p.sub && keyMatch2(r.obj, p.obj) && regexMatch(r.act, p.act)

Policy

p, alice, /alice_data/:resource, GET
p, alice, /alice_data2/:id/using/:resId, GET

I use the following sample code

#include <casbin/enforcer.h>
#include <iostream>

int main()
{
	casbin::Enforcer e("model.conf", "policy.csv");

	if (e.Enforce({"alice", "/alice_data/hello", "GET"})) {
		std::cout << "Enforce OK" << std::endl;
	} else {
		std::cout << "Enforce NOT Good" << std::endl;
	}

	if (e.Enforce({"alice", "/alice_data/hello", "POST"})) {
		std::cout << "Enforce OK" << std::endl;
	} else {
		std::cout << "Enforce NOT Good" << std::endl;
	}
}

Got

Enforce OK
Enforce OK

But it should be

OK
NOT OK

Improve portability

We love the effort but currently we can not use the project due to portability issues. I would propose to make the following changes.

  • Introduce "casbin" namespace.
  • Remove "using namespace" in all headers.
  • Remove "using std" everywhere.

The latter two changes conflict with point 3 of the contribution guide which is actually considered bad practice and decreases portability. See: https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice.

Making these changes would make the project more inline with point 12 of the contributation guide and would improve portablity. See also: https://google.github.io/styleguide/cppguide.html#Namespaces.

Happy to help out on this in case this issue is accepted.

Exceptions should inherit `std::exception`

All C++ exceptions should inherit std::exception so that a generic

{
   casbin_stuff();
}
catch (std::exception & e)
{
}

captures all of them.

Please fix this, it makes your library pretty much unusable. Any static analyzer would tell you that's wrong.

diff --git a/casbin/exception/casbin_adapter_exception.h b/casbin/exception/casbin_adapter_exception.h
index 41d9179..4739c93 100644
--- a/casbin/exception/casbin_adapter_exception.h
+++ b/casbin/exception/casbin_adapter_exception.h
@@ -6,10 +6,8 @@
 namespace casbin {
 
 // Exception class for Casbin Adapter Exception.
-class CasbinAdapterException{
-    std::string error_message;
-    public:
-        CasbinAdapterException(std::string error_message);
+struct CasbinAdapterException : std::logic_error {
+    using std::logic_error::logic_error;
 };
 
 } // namespace casbin
diff --git a/casbin/exception/casbin_enforcer_exception.h b/casbin/exception/casbin_enforcer_exception.h
index a68a599..25aa479 100644
--- a/casbin/exception/casbin_enforcer_exception.h
+++ b/casbin/exception/casbin_enforcer_exception.h
@@ -6,10 +6,8 @@
 namespace casbin {
 
 // Exception class for Casbin Enforcer Exception.
-class CasbinEnforcerException{
-    std::string error_message;
-    public:
-        CasbinEnforcerException(std::string error_message);
+struct CasbinEnforcerException : std::runtime_error {
+    using std::runtime_error::runtime_error;
 };
 
 } // namespace casbin
diff --git a/casbin/exception/casbin_rbac_exception.h b/casbin/exception/casbin_rbac_exception.h
index 1ac8adf..2ae3a6b 100644
--- a/casbin/exception/casbin_rbac_exception.h
+++ b/casbin/exception/casbin_rbac_exception.h
@@ -6,10 +6,8 @@
 namespace casbin {
 
 // Exception class for Casbin Adapter Exception.
-class CasbinRBACException{
-    std::string error_message;
-    public:
-        CasbinRBACException(std::string error_message);
+struct CasbinRBACException : std::invalid_argument {
+    using std::invalid_argument::invalid_argument;
 };
 
 } // namespace casbin
diff --git a/casbin/exception/illegal_argument_exception.h b/casbin/exception/illegal_argument_exception.h
index 5366019..5be86ab 100644
--- a/casbin/exception/illegal_argument_exception.h
+++ b/casbin/exception/illegal_argument_exception.h
@@ -2,14 +2,14 @@
 #define CASBIN_CPP_EXCEPTION_ILLEGAL_ARGUMENT_EXCEPTION
 
 #include <string>
+#include <stdexcept>
 
 namespace casbin {
 
 // Exception class for illegal arguments.
-class IllegalArgumentException{
-    std::string error_message;
-    public:
-        IllegalArgumentException(std::string error_message);
+struct IllegalArgumentException : std::invalid_argument
+{
+    using std::invalid_argument::invalid_argument;
 };
 
 } // namespace casbin
diff --git a/casbin/exception/io_exception.h b/casbin/exception/io_exception.h
index 2804ff8..843a930 100644
--- a/casbin/exception/io_exception.h
+++ b/casbin/exception/io_exception.h
@@ -6,10 +6,8 @@
 namespace casbin {
 
 // Exception class for I/O operations.
-class IOException{
-    std::string error_message;
-    public:
-        IOException(std::string error_message);
+struct IOException : std::runtime_error {
+    using std::runtime_error::runtime_error;
 };
 
 } // namespace casbin
diff --git a/casbin/exception/missing_required_sections.h b/casbin/exception/missing_required_sections.h
index 504eb70..28f4029 100644
--- a/casbin/exception/missing_required_sections.h
+++ b/casbin/exception/missing_required_sections.h
@@ -6,10 +6,8 @@
 namespace casbin {
 
 // Exception class for missing required sections.
-class MissingRequiredSections{
-    std::string error_message;
-    public:
-        MissingRequiredSections(std::string error_message);
+struct MissingRequiredSections : std::domain_error{
+    using std::domain_error::domain_error;
 };
 
 } // namespace casbin
diff --git a/casbin/exception/unsupported_operation_exception.h b/casbin/exception/unsupported_operation_exception.h
index b32a564..dd55a16 100644
--- a/casbin/exception/unsupported_operation_exception.h
+++ b/casbin/exception/unsupported_operation_exception.h
@@ -6,10 +6,8 @@
 namespace casbin {
 
 // Exception class for unsupported operations.
-class UnsupportedOperationException{
-    std::string error_message;
-    public:
-        UnsupportedOperationException(std::string error_message);
+struct UnsupportedOperationException : std::logic_error {
+    using std::logic_error::logic_error;
 };
 
 } // namespace casbin

Configure CMake build system 🏗️

The current state of the CMake config is quite basic and won't scale with the project. #84, #79, #50, #96, and #42 would require a robust build system with minimal setup across all platforms to add features seamlessly and debug on all platforms with a single codebase.

Integrate with Glewlwyd

See: babelouest/glewlwyd#184 (comment)

We should provide help and support including development efforts to help Glewlwyd integrate with Casbin. We need to communicate with them, know our customer's need and help them with the code.

I suggest putting this in a high priority (than the issues proposed by our own people) because we have been "working behind closed doors" for long (we raise issues by ourselves, then solve them) and this can be the first time for us to show Casbin-Cpp is also useful for others.

cross platform compile casbin-cpp

Currently, casbin-cpp only builds on windows, we need to support linux and other os. Using CMake as the build system may be a solution

bug: assign value to uninitialized vector

in bool Enforcer :: enforce(string matcher, Scope scope)

   ...

    vector <float> matcher_results;  // <-- uninitialized

    if(policy_len != 0) {
        if(this->model->m["r"].assertion_map["r"]->tokens.size() != this->func_map.GetRLen())
            return false;

        //TODO
        for( int i = 0 ; i < policy_len ; i++){
            // log.LogPrint("Policy Rule: ", pvals)
            vector<string> p_vals = this->model->m["p"].assertion_map["p"]->policy[i];
            if(this->model->m["p"].assertion_map["p"]->tokens.size() != p_vals.size())
                return false;

            PushObject(this->func_map.scope, "p");
            for(int j = 0 ; j < p_tokens.size() ; j++){
                int index = int(p_tokens[j].find("_"));
                string token = p_tokens[j].substr(index+1);
                PushStringPropToObject(this->func_map.scope, "p", p_vals[j], token);
            }

            this->func_map.Evaluate(exp_string);
            
            //TODO
            // log.LogPrint("Result: ", result)
            if(CheckType(this->func_map.scope) == Type :: Bool){
                bool result = GetBoolean(this->func_map.scope);
                if(!result) {
                    policy_effects[i] = Effect :: Indeterminate;
                    continue;
                }
            }
            else if(CheckType(this->func_map.scope) == Type :: Float){
                bool result = GetFloat(this->func_map.scope);
                if(result == 0) {
                    policy_effects[i] = Effect :: Indeterminate;
                    continue;
                } else
                    matcher_results[i] = result;   // <-- crash here
            }
            else
                return false;

crash while initialize Enforcer without adapter

My program

auto model = make_shared<Model>();
model->AddDef("r", "r", "sub, obj, act");
model->AddDef("p", "p", "sub, obj, act");
model->AddDef("g", "g", "_, _");
model->AddDef("e", "e", "some(where (p.eft == allow))");
model->AddDef("m", "m", "g(r.sub, p.sub) && r.obj == p.obj && r.act == p.act");
Enforcer e = Enforcer(model);  // <-- crash

Cause by following issue

Enforcer ::Enforcer(shared_ptr<Model> m): Enforcer(m, NULL) {
}

Enforcer :: Enforcer(shared_ptr<Model> m, shared_ptr<Adapter> adapter) {
    this->adapter = adapter;
    this->watcher = NULL;

    this->model = m;
    this->model->PrintModel();
    this->func_map.LoadFunctionMap();

    this->Initialize();

    if (this->adapter->file_path != "") {.    // <-- this->adapter is NULL
        this->LoadPolicy();
    }
}

can casbin-cpp support ABAC and eval()?

in the casbin docs, I learned that casbin supports abac and the model file is as follows:

[request_definition]
r = sub, obj, act

[policy_definition]
p = sub_rule, obj, act

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

[matchers]
m = eval(p.sub_rule) && r.obj == p.obj && r.act == p.act

can you tell me if casbin-cpp supports abac now?If not support then when will it be ready? looking forward to your answer, thanks

[QUESTION] Incorrect enforce result when using LoadPolicyLine

Hi, I was trying casbin-cpp but the behavior is different than the enforcement test on the website editor, if casbin::LoadPolicyLine() is used.

The enforcer is constructed with:

casbin::Enforcer enforcer{std::shared_ptr<casbin::Model>(
        casbin::Model::NewModelFromString(GetFileConfigFromCloud("model.conf")))};

The model is RBAC with resource roles (exactly copied from the website), and the policy is:

p, data_group_admin, data_group, read

g, me, data_group_admin
g2, route, data_group

However, enforce("me", "route", "read") always return false, while the website shows it should be true.

If I add the following line to the policy file, then it does return true, proving the policy is somewhat (partially?) loaded:

p, me, route, read

The policy is loaded using casbin::LoadPolicyLine():

const std::string policy = GetFileConfigFromCloud("policy.csv");
for (const auto& line : SplitStringView(policy, "\n")) {
    std::string line_str = std::string(line);
    casbin::LoadPolicyLine(casbin::Trim(line_str), enforcer.GetModel().get());
}

If the policy is loaded by simply passing the path to the Enforcer constructor, everything works as expected.

Any thoughts about what is wrong with my code?

Setup some PR actions.

Some PR actions like Semantic-PR, coveralls(for code coverage) and probably travis-CI after we add CMake support for cpp.

Cannot build Solution on Visual Studio 2019

Hello everyone.
I am trying to build project with Visual Studio 2019. I follow the tutorial in your project with step:

  • Clone project
  • Double click on casbin.sln
  • Click Build -> Build Solution

But compiler return some error with code C1083: cannot open include file. See picture
image

I don't change any config in solution. I don't know where am I wrong. Can you help me solve my problem?
Many thanks.

Can't build on Linux (Ubuntu 20.04)

See my logs:

In file included from casbin/util/built_in_functions.cpp:30:
casbin/util/../ip_parser/parser/parseCIDR.h:14:10: fatal error: ../exception/ParserException.h: No such file or directory
   14 | #include "../exception/ParserException.h"
      |          ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
compilation terminated.

image

Also see Travis CI: https://travis-ci.org/github/casbin/casbin-cpp

Improve existing code quality

C++ has some static detection tools, I use the open source cppcheck to check the current code quality.It is not satisfactory, it will cause some performance loss,at least we have to be able to achieve effective c++ in some aspects.I'm already working and researching this,I will list a few rules,but I will follow the contribution guidelines #7, if you have no objections, please allow me to do this.@hsluoyz @xcaptain

1.Class object has a constructor with 1 argument that should use Keyword:explicit.
2.Exception should be caught by reference.
https://stackoverflow.com/questions/2522299/c-catch-blocks-catch-exception-by-value-or-reference
3.Prefer prefix ++/-- operators for non-primitive types.
https://stackoverflow.com/questions/631506/does-pre-and-post-increment-decrement-operators-in-c-have-same-performance-in
4.Variable is assigned in constructor body. Consider performing initialization in initialization list.
https://stackoverflow.com/questions/9903248/initializing-fields-in-constructor-initializer-list-vs-constructor-body
5.Function parameter value should be passed by reference.
https://stackoverflow.com/questions/10231349/are-the-days-of-passing-const-stdstring-as-a-parameter-over
6.Applying size_type as a subscript when using string and vector or use the Keyword auto
https://stackoverflow.com/questions/1181079/stringsize-type-instead-of-int
7.The byte defined in the ip_parse folder has been implemented in the std library as std::byte, which is recommended to be written as Byte
8.Avoiding c-style type casting
https://stackoverflow.com/questions/3278441/c-type-casting
https://stackoverflow.com/questions/332030/when-should-static-cast-dynamic-cast-const-cast-and-reinterpret-cast-be-used/332086#332086
and so on...

There are some things not mentioned, I will continue to add, submit pr after the test

remove filePath from tests

string filePath(string filepath) {
char* root = _getcwd(NULL, 0);
string rootStr = string(root);
vector <string> directories = Split(rootStr, "\\", -1);
vector<string>::iterator it = find(directories.begin(), directories.end(), "x64");
vector <string> left{ *(it-1) };
it = find_end(directories.begin(), directories.end(), left.begin(), left.end());
int index = int(directories.size() + (it - directories.end()));
vector <string> finalDirectories(directories.begin(), directories.begin() + index + 1);
vector<string> userD = Split(filepath, "/", -1);
for (int i = 1; i < userD.size(); i++)
finalDirectories.push_back(userD[i]);
string filepath1 = finalDirectories[0];
for (int i = 1; i < finalDirectories.size(); i++)
filepath1 = filepath1 + "/" + finalDirectories[i];
return filepath1;
}

This function is duplicated several times in tests, looks like it just turns a path into an absolute path, would consider remove it, since the relative execution path is determined.

Setup benchmarks

Really happy to see a new casbin product is born with good features, thanks @divy9881 for your hard work.

BTW, It's also interesting to see benchmarks numbers in casbin-cpp, normally cpp should win bench again rust and golang.

Could you add benchmarks?

Contribution guide

  1. Our build system is makefile (on Linux) & Visual Studio project files (on Windows). We don't use cross-platform building tools like CMake because I think it only makes things more complicated. Just maintaining two native build systems (makefile and Visual Studio) is easier and more friendly to users. Casbin is a library instead of app, so I must choose something used more widely. Please make your code compile well on both platforms before any PR. I personally will test the code on Visual Studio and CLion on Windows.
  2. We use Google test as the test framework.
    3. Use use namespace std;, there should be no std::string in the code. [Abandoned]
  3. The allowed source file name's extensions are .cpp and .h. Others like .cc, .hpp are forbidden.
  4. Write minimized working code first, like file adapter, model, enforcer. Don't try to setup a code framework, or something like CI, linter only. I cannot witness those things work well without concrete code.
  5. Use printf instead of cout. No cout will be allowed in the code.
  6. Follow the module (filename) naming of Golang Casbin: https://github.com/casbin/casbin . Do not invent a name by yourself.
  7. Your code in PR should compile well itself on Windows and Linux, better with tests. Do not leave a feature in half, which has 100+ compile errors and then send PR.
  8. Base your code on our latest master branch, follow our folder structure, filename naming, etc.
  9. Do not use CMake or any cross-platform building tools (I have to say it again).
  10. Don't commit so many code in one PR. One PR can only contain one commit, with 100 LoC change.
  11. Other things please follow Google C++ Style Guide: https://google.github.io/styleguide/cppguide.html

gcc complains "pragma once" in *.cpp file

gcc version

c++ (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0
Copyright (C) 2019 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

compiler output:

[  1%] Building CXX object CMakeFiles/casbin.dir/casbin/enforcer.cpp.o
/usr/bin/c++    -g   -std=gnu++11 -o CMakeFiles/casbin.dir/casbin/enforcer.cpp.o -c /home/bigcat26/work/lab/third_party/casbin/casbin/enforcer.cpp
/home/bigcat26/work/lab/third_party/casbin/casbin/enforcer.cpp:17:9: warning: #pragma once in main file
   17 | #pragma once
      |         ^~~~
[  3%] Building CXX object CMakeFiles/casbin.dir/casbin/enforcer_cached.cpp.o
/usr/bin/c++    -g   -std=gnu++11 -o CMakeFiles/casbin.dir/casbin/enforcer_cached.cpp.o -c /home/bigcat26/work/lab/third_party/casbin/casbin/enforcer_cached.cpp
/home/bigcat26/work/lab/third_party/casbin/casbin/enforcer_cached.cpp:17:9: warning: #pragma once in main file
   17 | #pragma once
      |         ^~~~
[  5%] Building CXX object CMakeFiles/casbin.dir/casbin/internal_api.cpp.o
/usr/bin/c++    -g   -std=gnu++11 -o CMakeFiles/casbin.dir/casbin/internal_api.cpp.o -c /home/bigcat26/work/lab/third_party/casbin/casbin/internal_api.cpp
/home/bigcat26/work/lab/third_party/casbin/casbin/internal_api.cpp:17:9: warning: #pragma once in main file
   17 | #pragma once
      |         ^~~~
[  7%] Building CXX object CMakeFiles/casbin.dir/casbin/management_api.cpp.o
/usr/bin/c++    -g   -std=gnu++11 -o CMakeFiles/casbin.dir/casbin/management_api.cpp.o -c /home/bigcat26/work/lab/third_party/casbin/casbin/management_api.cpp
/home/bigcat26/work/lab/third_party/casbin/casbin/management_api.cpp:17:9: warning: #pragma once in main file
   17 | #pragma once
      |         ^~~~
[  8%] Building CXX object CMakeFiles/casbin.dir/casbin/model/function.cpp.o
/usr/bin/c++    -g   -std=gnu++11 -o CMakeFiles/casbin.dir/casbin/model/function.cpp.o -c /home/bigcat26/work/lab/third_party/casbin/casbin/model/function.cpp
/home/bigcat26/work/lab/third_party/casbin/casbin/model/function.cpp:17:9: warning: #pragma once in main file
   17 | #pragma once
      |         ^~~~
[ 10%] Building CXX object CMakeFiles/casbin.dir/casbin/rbac_api.cpp.o
/usr/bin/c++    -g   -std=gnu++11 -o CMakeFiles/casbin.dir/casbin/rbac_api.cpp.o -c /home/bigcat26/work/lab/third_party/casbin/casbin/rbac_api.cpp
/home/bigcat26/work/lab/third_party/casbin/casbin/rbac_api.cpp:17:9: warning: #pragma once in main file
   17 | #pragma once
      |         ^~~~
[ 12%] Building CXX object CMakeFiles/casbin.dir/casbin/rbac_api_with_domains.cpp.o
/usr/bin/c++    -g   -std=gnu++11 -o CMakeFiles/casbin.dir/casbin/rbac_api_with_domains.cpp.o -c /home/bigcat26/work/lab/third_party/casbin/casbin/rbac_api_with_domains.cpp
/home/bigcat26/work/lab/third_party/casbin/casbin/rbac_api_with_domains.cpp:17:9: warning: #pragma once in main file
   17 | #pragma once
      |         ^~~~
[ 14%] Building CXX object CMakeFiles/casbin.dir/casbin/util/built_in_functions.cpp.o
/usr/bin/c++    -g   -std=gnu++11 -o CMakeFiles/casbin.dir/casbin/util/built_in_functions.cpp.o -c /home/bigcat26/work/lab/third_party/casbin/casbin/util/built_in_functions.cpp
/home/bigcat26/work/lab/third_party/casbin/casbin/util/built_in_functions.cpp:17:9: warning: #pragma once in main file
   17 | #pragma once
      |         ^~~~

Integrate with mosquitto

Currently, I'm using mosquitto with it's own ACL module dynamic security plugin, but it was complex designed (such as groups & roles, priority id), and resource(topic) group was not supported.

If we can integrate mosquitto dynsec plugin with casbin, that would be great.

Upgrade to C++17

The project can utilize the benefits of the modern C++17 standard. It is better, faster, and has more features than C++11. The features relevant for us include:

The above benefits would only compound with time and make this project up to date.

Setup a code style linter

I can usually find a lot of code style issues in our code like this PR: #48. I don't want to review and fix them one by one. We need a systematic and automatic way to solve it.

How does C/C++ solve the code linting issue? I want a solution better working for multiple OSes, multiple IDEs. I only know something like EditorConfig: https://editorconfig.org/

What tool does C/C++ project often use for code linter?

Project porting casbin from go to cpp starts

As there are many more files and so need some guidance that, from which file we should start porting.
The golang code structure used in casbin is understood at full potential.
Now, we are ready to start this project with full potential.

@hsluoyz Please review this

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.