diff --git a/docs/CommandLineTools.mdx b/docs/CommandLineTools.mdx index bfada0d2..842e70fc 100644 --- a/docs/CommandLineTools.mdx +++ b/docs/CommandLineTools.mdx @@ -6,19 +6,19 @@ keywords: [command-line tools, casbin, cli] authors: [liulifox233] --- -**Casbin CLIs** are command-line tools that provide a command-line interface for Casbin, enabling you to use all of Casbin APIs in the shell. This documentation covers the usage of Casbin CLI for various languages including Rust, Java, Go, Python, .NET, and NodeJs. +**Casbin CLIs** offer command-line interfaces that expose Casbin's full API directly in your shell environment. This guide explains how to use Casbin's CLI implementations across multiple languages, including Rust, Java, Go, Python, .NET, and Node.js. ## Installation ### Go (casbin-go-cli) -1. Clone project from repository +1. Clone the repository: ```bash git clone https://github.com/casbin/casbin-go-cli.git ``` -2. Build project +2. Build the CLI: ```bash cd casbin-go-cli @@ -27,21 +27,21 @@ authors: [liulifox233] ### Rust (casbin-rust-cli) -#### From crates.io +#### Install from crates.io ```bash cargo install casbin-rust-cli ``` -#### From source +#### Build from source -1. Clone project from repository +1. Clone the repository: ```bash git clone https://github.com/casbin-rs/casbin-rust-cli.git ``` -2. Build project +2. Build with release optimizations: ```bash cd casbin-rust-cli @@ -50,13 +50,13 @@ cargo install casbin-rust-cli ### Java (casbin-java-cli) -1. Clone project from repository +1. Clone the repository: ```bash git clone https://github.com/jcasbin/casbin-java-cli.git ``` -2. Build project, the jar package will be generated in the target directory +2. Build using Maven (the JAR file will be created in the `target` directory): ```bash cd casbin-java-cli @@ -65,20 +65,20 @@ cargo install casbin-rust-cli ### Python (casbin-python-cli) -1. Clone project from repository +1. Clone the repository: ```bash git clone https://github.com/casbin/casbin-python-cli.git ``` -2. Install dependencies +2. Install required dependencies: ```bash cd casbin-python-cli pip install -r requirements.txt ``` -3. Run CLI +3. Run the CLI: ```bash python -m casbin_cli.client [command] [options] [args] @@ -86,13 +86,13 @@ cargo install casbin-rust-cli ### .NET (casbin-dotnet-cli) -1. Clone project from repository +1. Clone the repository: ```bash git clone https://github.com/casbin-net/casbin-dotnet-cli.git ``` -2. Build project +2. Build the project: ```bash cd casbin-dotnet-cli @@ -103,19 +103,19 @@ cargo install casbin-rust-cli ## Options -| options | description | must | remark | -|-----------------------|----------------------------------------------------------------------|------|-----------------------------------------------------------| -| `-m, --model` | The path of the model file or model text | y | Please wrap it with `""` and separate each line with `\|` | -| `-p, --policy` | The path of the policy file or policy text | y | Please wrap it with `""` and separate each line with `\|` | -| `-e, --enforce` | Check permissions | n | Please wrap it with `""` | -| `-ex, --enforceEx` | Check permissions and get which policy it is | n | Please wrap it with `""` | -| `-AF, --addFuntion` | Add custom funtion ( casbin-java-cli only ) | n | Please wrap it with `""` and separate each line with `\|` | -| `-ap, --addPolicy` | Add a policy rule to the policy file ( casbin-java-cli only ) | n | Please wrap it with `""` | -| `-rp, --removePolicy` | Remove a policy rule from the policy file ( casbin-java-cli only ) | n | Please wrap it with `""` | +| Option | Description | Required | Notes | +|-----------------------|------------------------------------------------------------------------|----------|--------------------------------------------------------------| +| `-m, --model` | Model file path or model definition text | Yes | Wrap in quotes and use `\|` as line separator | +| `-p, --policy` | Policy file path or policy definition text | Yes | Wrap in quotes and use `\|` as line separator | +| `-e, --enforce` | Evaluate access permissions | No | Wrap arguments in quotes | +| `-ex, --enforceEx` | Evaluate permissions and display the matched policy | No | Wrap arguments in quotes | +| `-AF, --addFuntion` | Register a custom function (casbin-java-cli only) | No | Wrap in quotes and use `\|` as line separator | +| `-ap, --addPolicy` | Append a policy rule to the policy file (casbin-java-cli only) | No | Wrap arguments in quotes | +| `-rp, --removePolicy` | Delete a policy rule from the policy file (casbin-java-cli only) | No | Wrap arguments in quotes | -## Get started +## Getting Started -- Check whether Alice has read permission on data1 +- Verify if Alice can read data1: ```shell ./casbin enforce -m "examples/rbac_model.conf" -p "examples/rbac_policy.csv" "alice" "data1" "read" @@ -129,7 +129,7 @@ cargo install casbin-rust-cli > `{"allow":true,"explain":null}` -- Check whether Alice has write permission for data2. If so, display the effective policy. +- Verify if Alice can write to data2 and show which policy grants the permission: ```shell ./casbin enforceEx -m "examples/rbac_model.conf" -p "examples/rbac_policy.csv" "alice" "data2" "write" @@ -137,7 +137,7 @@ cargo install casbin-rust-cli > `{"allow":true,"explain":["data2_admin","data2","write"]}` -- Add a policy to the policy file ( casbin-java-cli only ) +- Add a new policy rule to the policy file (casbin-java-cli only): ```shell ./casbin addPolicy -m "examples/rbac_model.conf" -p "examples/rbac_policy.csv" "alice" "data2" "write" @@ -145,7 +145,7 @@ cargo install casbin-rust-cli > `{"allow":true,"explain":null}` -- Delete a policy from the policy file ( casbin-java-cli only ) +- Remove a policy rule from the policy file (casbin-java-cli only): ```shell ./casbin removePolicy -m "examples/rbac_model.conf" -p "examples/rbac_policy.csv" "alice" "data2" "write" diff --git a/docs/Contributing.mdx b/docs/Contributing.mdx index d71d2a3b..b6fddbc1 100644 --- a/docs/Contributing.mdx +++ b/docs/Contributing.mdx @@ -6,11 +6,11 @@ keywords: [Contributing] authors: [Selflocking, EmperorYP7] --- -Casbin is a powerful authorization library that supports access control models with implementations in many programming languages. If you are proficient in any programming language, you can contribute to the development of Casbin. New contributors are always welcome. +Casbin is an authorization library that implements access control models across multiple programming languages. Contributors with expertise in any supported language are welcome to participate in its development. -Currently, there are two main types of projects: +The project consists of two primary categories: -* **Algorithms-oriented projects** - These projects involve implementing algorithms in different programming languages. Casbin supports a wide range of languages, including Golang, Java, C++, Elixir, Dart, and Rust, along with their related products. +* **Algorithm-focused projects** - These involve implementing Casbin's core algorithms in various languages, including Go, Java, C++, Elixir, Dart, and Rust, along with their ecosystem integrations. | [![golang](/img/langs/golang.png)](https://github.com/casbin/casbin) | [![java](/img/langs/java.png)](https://github.com/casbin/jcasbin) | [![nodejs](/img/langs/nodejs.png)](https://github.com/casbin/node-casbin) | [![php](/img/langs/php.png)](https://github.com/php-casbin/php-casbin) | |----------------------------------------------------------------------|-------------------------------------------------------------------|---------------------------------------------------------------------------|------------------------------------------------------------------------| @@ -22,35 +22,35 @@ Currently, there are two main types of projects: | [PyCasbin](https://github.com/casbin/pycasbin) | [Casbin.NET](https://github.com/casbin/Casbin.NET) | [Casbin-CPP](https://github.com/casbin/casbin-cpp) | [Casbin-RS](https://github.com/casbin/casbin-rs) | | Production-ready | Production-ready | Production-ready | Production-ready | -* **Application-oriented projects** - These projects are related to applications built on top of Casbin. +* **Application-based projects** - These projects build applications on top of the Casbin library. -| Project | Demo | Details | Skill Stacks | -|----------------------------------------------------------|--------------------------------------------|---------------------------------------------------------------------|--------------------| -| [Casbin Editor](https://github.com/casbin/casbin-editor) | [Casbin Editor](https://editor.casbin.org) | Casbin-editor is a web-based editor for Casbin models and policies. | TypeScript + React | +| Project | Demo | Details | Tech Stack | +|----------------------------------------------------------|--------------------------------------------|-----------------------------------------------------------------------------------|--------------------| +| [Casbin Editor](https://github.com/casbin/casbin-editor) | [Casbin Editor](https://editor.casbin.org) | A browser-based editor for creating and testing Casbin models and policies. | TypeScript + React | -## Getting Involved +## Ways to Contribute -There are many ways to contribute to Casbin. Here are some ideas to get started: +There are multiple ways to help Casbin grow: -* **Use Casbin and report issues!** When using Casbin, report any issues you encounter to help promote the development of Casbin. Whether it's a bug or a proposal, filing an issue on [GitHub](https://github.com/casbin/casbin) is recommended. However, it would be better to have a discussion first on [Discord](https://discord.gg/S5UjpzGZjN) or [GitHub Discussions](https://github.com/casbin/casbin/discussions) before filing an issue. +* **Use Casbin and provide feedback** - Your real-world experience helps us improve. Report bugs or suggest features on [GitHub](https://github.com/casbin/casbin). Before opening an issue, consider discussing it first on [Discord](https://discord.gg/S5UjpzGZjN) or [GitHub Discussions](https://github.com/casbin/casbin/discussions). - > Note: When reporting an issue, please use English to describe the details of your problem. + > Note: Please describe issues in English. -* **Help with documentation!** Contributing to the documentation is a good starting point for your contribution. +* **Improve documentation** - Documentation improvements are an excellent starting point for new contributors. -* **Help solve issues!** We have prepared a table containing easy tasks suitable for beginners, with different levels of challenges labeled with different tags. You can check the table [here](https://github.com/orgs/casbin/projects/2). +* **Resolve existing issues** - Check our [issue board](https://github.com/orgs/casbin/projects/2) for beginner-friendly tasks, labeled by difficulty level. -## Pull Requests +## Submitting Pull Requests -Casbin uses GitHub as its development platform, so pull requests are the main way to contribute. +Casbin develops on GitHub, making pull requests the standard contribution method. -Before opening a pull request, there are a few things you need to know: +Before submitting a pull request: -* Explain why you are sending the pull request and what it will do for the repository. +* Clearly explain the purpose and impact of your changes on the repository. -* Make sure the pull request does only one thing. If there are multiple changes, please split them into separate pull requests. +* Keep each pull request focused on a single change. Submit separate pull requests for unrelated modifications. -* If you are adding new files, please include the Casbin license at the top of the new file(s). +* When adding new files, include the Casbin license header at the top: ```text // Copyright 2021 The casbin Authors. All Rights Reserved. @@ -68,8 +68,8 @@ Before opening a pull request, there are a few things you need to know: // limitations under the License. ``` -* When opening a pull request and committing your contribution, it is recommended to use semantic commits with the following format: ```(): ```. The `````` is optional. For more detailed usage, please refer to [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/). +* Use semantic commit messages following the format: ```(): ```. The `````` is optional. For detailed guidelines, see [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/). -## License +## Licensing -By contributing to Casbin, you agree that your contributions will be licensed under the Apache License. +All contributions to Casbin are licensed under the Apache License. diff --git a/docs/DataPermissions.mdx b/docs/DataPermissions.mdx index 9e6ad434..b25c65b8 100644 --- a/docs/DataPermissions.mdx +++ b/docs/DataPermissions.mdx @@ -6,15 +6,15 @@ keywords: [Data Permissions, implicit] authors: [ErikQQY] --- -We have two solutions for data permissions (filtering): using implicit assignment APIs or using the `BatchEnforce()` API. +Casbin provides two approaches for implementing data-level permission filtering: querying implicit assignments or using batch enforcement. -### 1. Query Implicit Roles or Permissions +### 1. Querying Implicit Roles and Permissions -When a user inherits a role or permission via an RBAC hierarchy instead of being directly assigned them in a policy rule, we refer to this type of assignment as "implicit". To query such implicit relations, you need to use the following two APIs: `GetImplicitRolesForUser()` and `GetImplicitPermissionsForUser()`, instead of `GetRolesForUser()` and `GetPermissionsForUser()`. For more details, please refer to [this GitHub issue](https://github.com/casbin/casbin/issues/137). +When users inherit roles or permissions through an RBAC hierarchy rather than through direct policy assignments, these are called "implicit" assignments. To retrieve these relationships, use `GetImplicitRolesForUser()` and `GetImplicitPermissionsForUser()` instead of the standard `GetRolesForUser()` and `GetPermissionsForUser()` methods. Additional details are available in [this GitHub issue](https://github.com/casbin/casbin/issues/137). -### 2. Use `BatchEnforce()` +### 2. Using `BatchEnforce()` -`BatchEnforce()` enforces each request and returns the results in a boolean array. +`BatchEnforce()` evaluates multiple access requests simultaneously and returns their results as a boolean array. For example: diff --git a/docs/Dispatchers.mdx b/docs/Dispatchers.mdx index f52f76d3..fc066d52 100644 --- a/docs/Dispatchers.mdx +++ b/docs/Dispatchers.mdx @@ -6,19 +6,19 @@ keywords: [dispatcher] authors: [dovics] --- -Dispatchers provide a way to synchronize incremental changes of policy. They should be based on consistency algorithms such as Raft to ensure the consistency of all enforcer instances. Through dispatchers, users can easily establish distributed clusters. +Dispatchers enable synchronization of incremental policy changes across distributed Casbin enforcer instances. They rely on consistency algorithms like Raft to maintain uniform policy state across all enforcers, simplifying the creation of distributed authorization clusters. -The dispatcher's method is divided into two parts. The first part is the method combined with Casbin. These methods should be called inside Casbin. Users can use the more complete API provided by Casbin itself. +A dispatcher's functionality is split into two parts. The first consists of methods integrated with Casbin's core. These methods are called internally by Casbin, allowing developers to use Casbin's standard API without modification. -The other part is the method defined by the dispatcher itself, including the dispatcher initialization method, and different functions provided by different algorithms, such as dynamic membership and config changes. +The second part includes the dispatcher's own initialization and algorithm-specific features, such as dynamic membership management and configuration updates. :::note -We hope dispatchers only ensure the consistency of the Casbin enforcer at runtime. So if the policy is inconsistent during initialization, the dispatchers will not work properly. Users need to ensure that the state of all instances is consistent before using dispatchers. +Dispatchers synchronize runtime policy changes only. They do not resolve pre-existing inconsistencies during initialization. You must ensure all enforcer instances start with identical policy states before enabling dispatchers. ::: -A complete list of Casbin dispatchers is provided below. Any 3rd-party contributions on a new dispatcher are welcomed. Please inform us, and we will add it to this list. +Below is a list of available Casbin dispatchers. Contributions of new dispatchers are welcome—let us know, and we'll include them here. ```mdx-code-block @@ -37,7 +37,7 @@ import {DispatcherGoData} from "@site/src/tableData/DispatcherData/DispatcherGoD ### DistributedEnforcer -DistributedEnforcer wraps SyncedEnforcer for the dispatcher. +`DistributedEnforcer` wraps `SyncedEnforcer` to work with dispatchers. ```mdx-code-block diff --git a/docs/Enforcers.mdx b/docs/Enforcers.mdx index b2d52026..a5ab4ada 100644 --- a/docs/Enforcers.mdx +++ b/docs/Enforcers.mdx @@ -6,11 +6,11 @@ keywords: [enforcer, supported enforcers] authors: [Abingcbc] --- -The `Enforcer` is the main structure in Casbin. It acts as an interface for users to perform operations on policy rules and models. +The `Enforcer` serves as Casbin's primary interface, providing methods for interacting with access control policies and models. -## Supported Enforcers +## Available Enforcers -A complete list of Casbin enforcers is provided below. Any 3rd-party contribution on a new enforcer is welcomed. Please inform us, and we will add it to this list :) +Below is a complete list of Casbin enforcers. Third-party enforcer contributions are welcome—please let us know and we'll add them to this list. ```mdx-code-block @@ -19,12 +19,12 @@ A complete list of Casbin enforcers is provided below. Any 3rd-party contributio | Enforcer | Author | Description | |---------------------------------------------------------------------------------------------|--------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| [Enforcer](https://github.com/casbin/casbin/blob/master/enforcer.go) | Casbin | The `Enforcer` is the basic structure for users to interact with Casbin policies and models. You can find more details about the `Enforcer` API [here](/docs/management-api). | -| [CachedEnforcer](https://github.com/casbin/casbin/blob/master/enforcer_cached.go) | Casbin | The `CachedEnforcer` is based on the `Enforcer` and supports caching the evaluation result of a request in memory using a map. It provides the ability to clear caches within a specified expiration time. Moreover, it guarantees thread safety with a Read-Write lock. You can use `EnableCache` to enable caching of evaluation results (default is enabled). The other API methods of `CachedEnforcer` are the same as `Enforcer`. | -| [DistributedEnforcer](https://github.com/casbin/casbin/blob/master/enforcer_distributed.go) | Casbin | The `DistributedEnforcer` supports multiple instances in distributed clusters. It wraps the `SyncedEnforcer` for the dispatcher. You can find more details about the dispatcher [here](/docs/dispatchers#distributedenforcer). | -| [SyncedEnforcer](https://github.com/casbin/casbin/blob/master/enforcer_synced.go) | Casbin | The `SyncedEnforcer` is based on the `Enforcer` and provides synchronized access. It is thread-safe. | -| [SyncedCachedEnforcer](https://github.com/casbin/casbin/blob/master/enforcer_cached_synced.go)| Casbin | The `SyncedCachedEnforcer` wraps the `Enforcer` and provides decision sync cache. | -| [ContextEnforcer](https://github.com/casbin/casbin/blob/master/enforcer_context.go) | Casbin | The `ContextEnforcer` implements the `IEnforcerContext` interface and provides context-aware API methods. Currently, only operations that utilize `ContextAdapter` have corresponding context versions, such as `LoadPolicyCtx()`, `SavePolicyCtx()`, `AddPolicyCtx()`, `RemovePolicyCtx()`, etc. This enforcer allows using context for more precise control over adapter operations. The interface is designed to support future expansion of context-aware functionality across more Casbin operations. | +| [Enforcer](https://github.com/casbin/casbin/blob/master/enforcer.go) | Casbin | The base `Enforcer` provides the primary interface for policy and model operations. See the [Management API documentation](/docs/management-api) for detailed API information. | +| [CachedEnforcer](https://github.com/casbin/casbin/blob/master/enforcer_cached.go) | Casbin | Extends the `Enforcer` with in-memory caching of enforcement results. Supports configurable cache expiration and includes thread-safe access via read-write locks. Use `EnableCache` to toggle caching (enabled by default). The remaining API methods match those of the base `Enforcer`. | +| [DistributedEnforcer](https://github.com/casbin/casbin/blob/master/enforcer_distributed.go) | Casbin | Designed for distributed deployments, this enforcer wraps `SyncedEnforcer` to work with dispatchers. Additional information is available in the [dispatcher documentation](/docs/dispatchers#distributedenforcer). | +| [SyncedEnforcer](https://github.com/casbin/casbin/blob/master/enforcer_synced.go) | Casbin | Extends `Enforcer` with synchronized access for thread-safe operations. | +| [SyncedCachedEnforcer](https://github.com/casbin/casbin/blob/master/enforcer_cached_synced.go)| Casbin | Combines the caching features of `CachedEnforcer` with the synchronization of `SyncedEnforcer`. | +| [ContextEnforcer](https://github.com/casbin/casbin/blob/master/enforcer_context.go) | Casbin | Implements the `IEnforcerContext` interface to provide context-aware operations. Currently supports context for adapter operations like `LoadPolicyCtx()`, `SavePolicyCtx()`, `AddPolicyCtx()`, and `RemovePolicyCtx()`. This interface is designed for future expansion of context support across additional Casbin operations. | ```mdx-code-block @@ -33,11 +33,11 @@ A complete list of Casbin enforcers is provided below. Any 3rd-party contributio | Enforcer | Author | Description | |---------------------------------------------------------------------------------------------|--------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| [Enforcer](https://github.com/casbin/pycasbin/blob/master/casbin/enforcer.py) | Casbin | The `Enforcer` is the basic structure for users to interact with Casbin policies and models. You can find more details about the `Enforcer` API [here](/docs/management-api). | -| [DistributedEnforcer](https://github.com/casbin/pycasbin/blob/master/casbin/distributed_enforcer.py) | Casbin | The `DistributedEnforcer` supports multiple instances in distributed clusters. It wraps the `SyncedEnforcer` for the dispatcher. You can find more details about the dispatcher [here](/docs/dispatchers#distributedenforcer). | -| [SyncedEnforcer](https://github.com/casbin/pycasbin/blob/master/casbin/synced_enforcer.py) | Casbin | The `SyncedEnforcer` is based on the `Enforcer` and provides synchronized access. It is thread-safe. | -| [AsyncEnforcer](https://github.com/casbin/pycasbin/blob/master/casbin/async_enforcer.py)| Casbin | The `AsyncEnforcer` provides async API. | -| [FastEnforcer](https://github.com/casbin/pycasbin/blob/master/casbin/fast_enforcer.py)| Casbin | The `FastEnforcer` uses a new model which is 50x faster than the normal model. You can find more [here](https://github.com/wakemaster39/fastbin) | +| [Enforcer](https://github.com/casbin/pycasbin/blob/master/casbin/enforcer.py) | Casbin | The base `Enforcer` provides the primary interface for policy and model operations. See the [Management API documentation](/docs/management-api) for detailed API information. | +| [DistributedEnforcer](https://github.com/casbin/pycasbin/blob/master/casbin/distributed_enforcer.py) | Casbin | Designed for distributed deployments, this enforcer wraps `SyncedEnforcer` to work with dispatchers. Additional information is available in the [dispatcher documentation](/docs/dispatchers#distributedenforcer). | +| [SyncedEnforcer](https://github.com/casbin/pycasbin/blob/master/casbin/synced_enforcer.py) | Casbin | Extends `Enforcer` with synchronized access for thread-safe operations. | +| [AsyncEnforcer](https://github.com/casbin/pycasbin/blob/master/casbin/async_enforcer.py)| Casbin | Provides asynchronous API methods for non-blocking enforcement operations. | +| [FastEnforcer](https://github.com/casbin/pycasbin/blob/master/casbin/fast_enforcer.py)| Casbin | Uses an optimized model architecture offering up to 50× performance improvements over the standard enforcer. More details are available at [fastbin's repository](https://github.com/wakemaster39/fastbin). | ```mdx-code-block diff --git a/docs/EnvoyAuthz.mdx b/docs/EnvoyAuthz.mdx index 952c26e8..6bedc5fd 100644 --- a/docs/EnvoyAuthz.mdx +++ b/docs/EnvoyAuthz.mdx @@ -6,24 +6,24 @@ keywords: [Envoy, Envoy-authz, Istio] authors: [ashish493] --- -[Envoy-authz](https://github.com/casbin/envoy-authz) is a middleware for Envoy that performs external RBAC & ABAC authorization through casbin. This middleware uses [Envoy's external authorization API](https://www.envoyproxy.io/docs/envoy/latest/intro/arch_overview/security/ext_authz_filter.html) via a gRPC server. This proxy can be deployed on any type of Envoy-based service mesh, such as Istio. +[Envoy-authz](https://github.com/casbin/envoy-authz) is an Envoy middleware that provides external RBAC and ABAC authorization through Casbin. It integrates with [Envoy's external authorization API](https://www.envoyproxy.io/docs/envoy/latest/intro/arch_overview/security/ext_authz_filter.html) via a gRPC server and can be deployed on any Envoy-based service mesh, including Istio. -## Requirements +## Prerequisites -- Envoy 1.17+ -- Istio or any other type of service mesh -- grpc dependencies +- Envoy 1.17 or later +- Istio or another Envoy-based service mesh +- gRPC dependencies -Dependencies are managed using `go.mod`. +Dependencies are managed through `go.mod`. -## Working of the Middleware +## How It Works -- A client makes an HTTP request. -- The Envoy proxy sends the request to the gRPC server. -- The gRPC server authorizes the request based on casbin policies. -- If authorized, the request is forwarded; otherwise, it is denied. +- A client initiates an HTTP request +- Envoy intercepts the request and forwards it to the gRPC authorization server +- The server evaluates the request against Casbin policies +- Authorized requests proceed; unauthorized requests are blocked -The gRPC server is based on protocol buffer from [external_auth.proto](https://github.com/envoyproxy/envoy/blob/master/api/envoy/service/auth/v2alpha/external_auth.proto) in Envoy. +The gRPC server implements the protocol buffer definition from Envoy's [external_auth.proto](https://github.com/envoyproxy/envoy/blob/master/api/envoy/service/auth/v2alpha/external_auth.proto): ```protobuf // A generic interface for performing authorization checks on incoming @@ -35,29 +35,29 @@ service Authorization { } ``` -From the above proto file, we need to use the `Check()` service in the authorization server. +The authorization server must implement the `Check()` method defined above. ## Usage -- Define the Casbin policies in the config files following this [guide](/docs/how-it-works). +- Configure your Casbin policies in the configuration files following the [Casbin documentation](/docs/how-it-works). -You can verify/test your policies using the online [casbin-editor](/editor). +You can test your policies using the online [Casbin editor](/editor). -- Start the authentication server by running: +- Launch the authorization server: ```bash go build . ./authz ``` -- Load the Envoy configuration: +- Apply the Envoy configuration: ```bash envoy -c authz.yaml -l info ``` -Once Envoy starts, it will intercept requests for the authorization process. +Once Envoy starts, it will route incoming requests through the authorization middleware. ## Integrating with Istio -To make this middleware work, you need to send custom headers containing usernames in the JWT token or headers. You can refer to the official [Istio documentation](https://istio.io/v1.4/docs/tasks/policy-enforcement/control-headers/) for more information on modifying `Request Headers`. +To enable this middleware, configure your system to pass user identity information through custom headers in JWT tokens or request headers. For instructions on modifying request headers, consult the official [Istio documentation](https://istio.io/v1.4/docs/tasks/policy-enforcement/control-headers/). diff --git a/docs/FrontendUsage.mdx b/docs/FrontendUsage.mdx index 1084dba1..0b8096d4 100644 --- a/docs/FrontendUsage.mdx +++ b/docs/FrontendUsage.mdx @@ -6,8 +6,7 @@ keywords: [Casbin.js, react-authz, rbac-react, vue-authz, angular-authz] authors: [hsluoyz] --- - -[Casbin.js](https://github.com/casbin/casbin.js) is a Casbin addon that facilitates your access-control management in the frontend application. +[Casbin.js](https://github.com/casbin/casbin.js) is a Casbin extension that simplifies access control management in frontend applications. ## Installation @@ -22,18 +21,18 @@ or yarn add casbin.js ``` -## Frontend Middlewares +## Frontend Frameworks -| Middleware | Type | Author | Description | -|-------------------------------------------------------------|---------|----------------------------------------|-------------------------------------------------------------------| -| [react-authz](https://github.com/casbin-js/react-authz) | React | Casbin | React wrapper for Casbin.js | -| [rbac-react](https://github.com/daobeng/rbac-react) | React | [@daobeng](https://github.com/daobeng) | Role Based Access Control in React using HOCs, CASL and Casbin.js | -| [vue-authz](https://github.com/casbin-js/vue-authz) | Vue | Casbin | Vue wrapper for Casbin.js | -| [angular-authz](https://github.com/casbin-js/angular-authz) | Angular | Casbin | Angular wrapper for Casbin.js | +| Framework | Type | Author | Description | +|-------------------------------------------------------------|---------|----------------------------------------|-------------------------------------------------------------------------------| +| [react-authz](https://github.com/casbin-js/react-authz) | React | Casbin | React wrapper for Casbin.js | +| [rbac-react](https://github.com/daobeng/rbac-react) | React | [@daobeng](https://github.com/daobeng) | Role-Based Access Control in React using Higher-Order Components, CASL, and Casbin.js | +| [vue-authz](https://github.com/casbin-js/vue-authz) | Vue | Casbin | Vue wrapper for Casbin.js | +| [angular-authz](https://github.com/casbin-js/angular-authz) | Angular | Casbin | Angular wrapper for Casbin.js | ## Quick Start -You can use the `manual` mode in your frontend application and set the permissions whenever you wish. +Configure Casbin.js in `manual` mode to set permissions explicitly in your frontend application: ```javascript const casbinjs = require("casbin.js"); @@ -48,7 +47,7 @@ const permission = { const authorizer = new casbinjs.Authorizer("manual"); ``` -Now we have an authorizer, `authorizer`. We can get permission rules from it by using the `authorizer.can()` and `authorizer.cannot()` APIs. The return values of these 2 APIs are JavaScript Promises ([details here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises)), so we should use the `then()` method of the return value like this: +With an authorizer instance, you can check permissions using `authorizer.can()` and `authorizer.cannot()`. Both methods return JavaScript Promises ([see MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises)), so use the `then()` method to handle results: ```javascript result = authorizer.can("write", "data1"); @@ -62,7 +61,7 @@ result.then((success, failed) => { // output: you can write data1 ``` -The `cannot()` API is used in the same way: +The `cannot()` method works identically: ```javascript result = authorizer.cannot("read", "data2"); @@ -76,13 +75,13 @@ result.then((success, failed) => { // output: you can read data2 ``` -In the code above, the `success` variable in the parameters means the request gets the result without throwing an error and doesn't mean that the permission rule is `true`. The `failed` variable is also unrelated to the permission rules. It only makes sense when something goes wrong in the process of the request. +The `success` parameter indicates that the query completed without errors—not that permission was granted. Similarly, `failed` relates to query errors, not permission denial. -You can refer to our [React example](https://github.com/casbin-js/examples) to see a practical usage of Casbin.js. +See our [React example](https://github.com/casbin-js/examples) for practical Casbin.js usage. ### Permission Object -Casbin.js will accept a JSON object to manipulate the corresponding permission of a visitor. For example: +Casbin.js uses a JSON object to represent visitor permissions. For example: ```json { @@ -91,13 +90,13 @@ Casbin.js will accept a JSON object to manipulate the corresponding permission o } ``` -The permission object above shows that the visitor can `read` the `data1` and `data2` objects, while they can only `write` the `data1` objects. +This object indicates that the visitor can read both `data1` and `data2` objects but can only write to `data1`. ## Advanced Usage -Casbin.js provides a perfect solution for integrating your frontend access-control management with your backend Casbin service. +Casbin.js provides seamless integration between frontend access control and your backend Casbin service. -Use the `auto` mode and specify your endpoint when initializing the Casbin.js `Authorizer`, it will automatically sync the permission and manipulate the frontend status. +Use `auto` mode and specify your backend endpoint when initializing the Casbin.js `Authorizer`. It will automatically synchronize permissions and manage frontend authorization state: ```javascript const casbinjs = require('casbin.js'); @@ -121,11 +120,11 @@ result.then((success, failed) => { }); ``` -Correspondingly, you need to expose an interface (e.g. a RestAPI) to generate the permission object and pass it to the frontend. In your API controller, call `CasbinJsGetUserPermission` to construct the permission object. Here is an example in Beego: +On the backend, expose an endpoint (such as a REST API) that generates the permission object for the frontend. In your API controller, call `CasbinJsGetUserPermission` to construct the permission object. This Beego example demonstrates the pattern: :::note -Your endpoint server should return something like +Your endpoint should return a response like: ```json { @@ -153,46 +152,46 @@ func (c *APIController) GetFrontendPermission() { :::note -Currently, the `CasbinJsGetPermissionForUser` API is only supported in Go Casbin and Node-Casbin. If you want this API to be supported in other languages, please [raise an issue](https://github.com/casbin/casbin.js/issues) or leave a comment below. +Currently, `CasbinJsGetPermissionForUser` is available only in Go Casbin and Node-Casbin. To request support in other languages, please [open an issue](https://github.com/casbin/casbin.js/issues) or leave a comment below. ::: -## API List +## API Reference ### `setPermission(permission: string)` -Set the permission object. Always used in `manual` mode. +Sets the permission object. Used primarily in `manual` mode. ### `setUser(user: string)` -Set the visitor identity and update the permission. Always used in `auto` mode. +Sets the visitor identity and refreshes permissions. Used primarily in `auto` mode. ### `can(action: string, object: string)` -Check if the user can perform `action` on `object`. +Checks if the user can perform `action` on `object`. ### `cannot(action: string, object: string)` -Check if the user **cannot** perform `action` on `object`. +Checks if the user **cannot** perform `action` on `object`. ### `canAll(action: string, objects: Array)` -Check if the user can perform `action` on **all** objects in `objects`. +Checks if the user can perform `action` on **all** objects in `objects`. ### `canAny(action: string, objects: Array)` -Check if the user can perform `action` on **any one** of the `objects`. +Checks if the user can perform `action` on **any** object in `objects`. ## Why Casbin.js -People may wonder about the difference between Node-Casbin and Casbin.js. In a word, Node-Casbin is the core of Casbin implemented in the NodeJS environment, and it's normally used as an access-controlling management toolkit at the server ends. Casbin.js is a frontend library that helps you use Casbin to authorize your webpage users at the client side. +People often wonder about the distinction between Node-Casbin and Casbin.js. Node-Casbin is Casbin's core implementation for Node.js environments, typically deployed at the server level for access control management. Casbin.js is a frontend library that helps you apply Casbin authorization logic at the client side for webpage users. -Normally, it is not proper to directly build up a Casbin service and do the authorization/enforcement tasks at a web frontend application due to the following problems: +Directly building a Casbin service for frontend authorization presents several issues: -1. When someone turns on the client, the enforcer will be initialized, and it will pull all the policies from the backend persistent layers. A high concurrency could bring tough pressure on the databases and cost a lot of network throughput. -2. Loading all policies to the client side could bring security risks. -3. It is difficult to separate the client and server as well as facilitate agile development. +1. When a client connects, the enforcer initializes and pulls all policies from backend storage. High concurrency can strain databases and consume significant network bandwidth. +2. Exposing all policies to clients creates security vulnerabilities. +3. Tight coupling between client and server complicates development and maintenance. -We need a tool that eases the process of using Casbin at the frontend. Actually, the core of Casbin.js is the manipulation of the current user's permission at the client side. As you mentioned, Casbin.js does a fetch from a specified endpoint. This procedure will sync the permission of the user with the backend Casbin service. After having the permission data, developers can use Casbin.js interfaces to manage the behavior of the user at the frontend side. +Casbin.js addresses these challenges by managing user permissions at the client level. The core functionality involves synchronizing the current user's permissions with the backend Casbin service through a fetch operation. Once permission data is retrieved, developers can use Casbin.js interfaces to control user behavior at the frontend. -Casbin.js avoids the two problems mentioned above: Casbin service will no longer be pulled up repeatedly, and the size of passing messages between the client and the server is reduced. We also avoid storing all the policies at the frontend. The user can only access their own permission, but has no knowledge about the access-control model and other users' permissions. Besides, Casbin.js can also efficiently decouple the client and the server in authorization management. +This approach eliminates repeated enforcer initialization, reduces message size between client and server, and avoids exposing all policies at the frontend. Users access only their own permissions without knowledge of the access control model or other users' permissions. Additionally, Casbin.js effectively decouples client and server authorization logic. diff --git a/docs/GraphQLMiddlewares.mdx b/docs/GraphQLMiddlewares.mdx index 57ad4a7a..e753039b 100644 --- a/docs/GraphQLMiddlewares.mdx +++ b/docs/GraphQLMiddlewares.mdx @@ -6,7 +6,7 @@ keywords: [GraphQL, authorization] authors: [hsluoyz] --- -Casbin follows the officially suggested way to provide authorization for GraphQL endpoints by having a single source of truth for authorization: [https://graphql.org/learn/authorization/](https://graphql.org/learn/authorization/). In other words, Casbin should be placed between the GraphQL layer and your business logic. +Casbin follows the recommended GraphQL authorization pattern by implementing authorization as a single source of truth: [https://graphql.org/learn/authorization/](https://graphql.org/learn/authorization/). This means Casbin logic should sit between the GraphQL layer and your business logic. ```javascript // Casbin authorization logic lives inside postRepository @@ -25,9 +25,9 @@ var postType = new GraphQLObjectType({ }); ``` -## Supported GraphQL Middlewares +## Available GraphQL Middlewares -A complete list of Casbin GraphQL middlewares is provided below. Any third-party contributions on a new GraphQL middleware are welcomed. Please inform us, and we will add it to this list:) +Below is a complete list of Casbin GraphQL middlewares. Third-party middleware contributions are welcome—please let us know and we'll include them here. ```mdx-code-block @@ -36,8 +36,8 @@ A complete list of Casbin GraphQL middlewares is provided below. Any third-party | Middleware | GraphQL Implementation | Author | Description | |------------------------------------------------------------------------------------|--------------------------------------------------|------------------------------------------------|--------------------------------------------------------| -| [graphql-authz](https://github.com/casbin/graphql-authz) | [graphql](https://github.com/graphql-go/graphql) | Casbin | An authorization middleware for graphql-go | -| [graphql-casbin](https://github.com/esmaeilpour/graphql-casbin) | [graphql](https://github.com/graphql-go/graphql) | [@esmaeilpour](https://github.com/esmaeilpour) | An implementation of using Graphql and Casbin together | +| [graphql-authz](https://github.com/casbin/graphql-authz) | [graphql](https://github.com/graphql-go/graphql) | Casbin | Authorization middleware for graphql-go | +| [graphql-casbin](https://github.com/esmaeilpour/graphql-casbin) | [graphql](https://github.com/graphql-go/graphql) | [@esmaeilpour](https://github.com/esmaeilpour) | GraphQL and Casbin integration example | | [gqlgen_casbin_RBAC_example](https://github.com/WenyXu/gqlgen_casbin_RBAC_example) | [gqlgen](https://github.com/99designs/gqlgen) | [@WenyXu](https://github.com/WenyXu) | (empty) | ```mdx-code-block @@ -45,18 +45,18 @@ A complete list of Casbin GraphQL middlewares is provided below. Any third-party ``` -| Middleware | GraphQL Implementation | Author | Description | -|---------------------------------------------------------------|-----------------------------------------------------|--------|-------------------------------------------------------------------------------------------| -| [graphql-authz](https://github.com/node-casbin/graphql-authz) | [GraphQL.js](https://github.com/graphql/graphql-js) | Casbin | A Casbin authorization middleware for [GraphQL.js](https://github.com/graphql/graphql-js) | +| Middleware | GraphQL Implementation | Author | Description | +|---------------------------------------------------------------|-----------------------------------------------------|--------|--------------------------------------------------------------------------------------------| +| [graphql-authz](https://github.com/node-casbin/graphql-authz) | [GraphQL.js](https://github.com/graphql/graphql-js) | Casbin | Casbin authorization middleware for [GraphQL.js](https://github.com/graphql/graphql-js) | ```mdx-code-block ``` -| Middleware | GraphQL Implementation | Author | Description | -|--------------------------------------------------------------|------------------------------------------------------------------|----------------------------------------------|--------------------------------------------------------------------------------------------------------| -| [graphql-authz](https://github.com/Checho3388/graphql-authz) | [GraphQL-core 3](https://github.com/graphql-python/graphql-core) | [@Checho3388](https://github.com/Checho3388) | A Casbin authorization middleware for [GraphQL-core 3](https://github.com/graphql-python/graphql-core) | +| Middleware | GraphQL Implementation | Author | Description | +|--------------------------------------------------------------|------------------------------------------------------------------|----------------------------------------------|------------------------------------------------------------------------------------------------------| +| [graphql-authz](https://github.com/Checho3388/graphql-authz) | [GraphQL-core 3](https://github.com/graphql-python/graphql-core) | [@Checho3388](https://github.com/Checho3388) | Casbin authorization middleware for [GraphQL-core 3](https://github.com/graphql-python/graphql-core) | ```mdx-code-block diff --git a/docs/IDEPlugins.mdx b/docs/IDEPlugins.mdx index cfa09060..e64bea32 100644 --- a/docs/IDEPlugins.mdx +++ b/docs/IDEPlugins.mdx @@ -6,13 +6,13 @@ keywords: [IDE plugins, JetBrains, VSCode] authors: [nodece] --- -We offer plugins for the following IDEs: +Casbin provides plugins for the following integrated development environments: ## JetBrains IDEs - Download: [https://plugins.jetbrains.com/plugin/14809-casbin](https://plugins.jetbrains.com/plugin/14809-casbin) - Source code: [https://github.com/will7200/casbin-idea-plugin](https://github.com/will7200/casbin-idea-plugin) -## VSCode +## Visual Studio Code - Source code: [https://github.com/casbin/casbin-vscode-plugin](https://github.com/casbin/casbin-vscode-plugin) diff --git a/docs/K8sAuthz.mdx b/docs/K8sAuthz.mdx index 3fdc2eda..8b3e574a 100644 --- a/docs/K8sAuthz.mdx +++ b/docs/K8sAuthz.mdx @@ -6,45 +6,45 @@ keywords: [Kubernetes authorization, Kubernetes RBAC, Kubernetes ABAC, K8s-authz authors: [hsluoyz] --- -[K8s-authz](https://github.com/casbin/k8s-authz) is a Kubernetes (k8s) authorization middleware based on Casbin that utilizes RBAC (Role-Based Access Control) and ABAC (Attribute-Based Access Control) for policy enforcement. This middleware integrates with the K8s validation admission webhook to validate the policies defined by Casbin for each request made to K8s resources. Custom admission controllers are registered with Kubernetes using the `ValidatingAdmissionWebhook` to perform validations on request objects forwarded by the API server and provide a response indicating whether the request should be allowed or rejected. +[K8s-authz](https://github.com/casbin/k8s-authz) is a Kubernetes authorization middleware built on Casbin that implements RBAC (Role-Based Access Control) and ABAC (Attribute-Based Access Control) policy enforcement. This middleware integrates with the Kubernetes validation admission webhook to evaluate Casbin-defined policies against each request to Kubernetes resources. Custom admission controllers register with Kubernetes using `ValidatingAdmissionWebhook` to validate request objects forwarded by the API server and return allow or deny responses. -To determine when to send incoming requests to the admission controller, a validation webhook has been implemented. This webhook proxies requests for any type of K8s resource or sub-resource and performs policy verification. Users are only allowed to perform operations on these resources if they are authorized by the Casbin enforcer. The [enforcer](/docs/get-started#new-a-casbin-enforcer) checks the roles of the user as defined in the policies. The K8s cluster is the deployment target for this middleware. +The validation webhook proxies requests for all Kubernetes resource types and subresources, performing policy verification for each. Users can perform operations on resources only when authorized by the Casbin enforcer. The [enforcer](/docs/get-started#new-a-casbin-enforcer) evaluates user roles as defined in the policies. Deploy this middleware directly to your Kubernetes cluster. -## Requirements +## Prerequisites -Before proceeding, ensure that you have the following: +Before you begin, ensure you have: -- A running Kubernetes cluster. You can set up a local cluster using Docker or set up a complete Kubernetes ecosystem on your server. For detailed instructions, refer to this [guide](https://kubernetes.io/docs/tutorials/kubernetes-basics/create-cluster/cluster-intro/) for setting up a local Kubernetes cluster on Windows or this [guide](https://www.digitalocean.com/community/tutorials/how-to-create-a-kubernetes-cluster-using-kubeadm-on-ubuntu-18-04) for setting up a cluster on Linux. -- Kubectl CLI. Instructions for installing Kubectl on Windows can be found [here](https://kubernetes.io/docs/tasks/tools/install-kubectl-windows/), and for Linux [here](https://kubernetes.io/docs/tasks/tools/install-kubectl-linux/). +- A running Kubernetes cluster. Set up a local cluster using Docker or establish a complete Kubernetes environment on your server. For local setup on Windows, see [this guide](https://kubernetes.io/docs/tutorials/kubernetes-basics/create-cluster/cluster-intro/). For Linux server setup, see [this tutorial](https://www.digitalocean.com/community/tutorials/how-to-create-a-kubernetes-cluster-using-kubeadm-on-ubuntu-18-04). +- Kubectl CLI. Installation instructions: [Windows](https://kubernetes.io/docs/tasks/tools/install-kubectl-windows/) | [Linux](https://kubernetes.io/docs/tasks/tools/install-kubectl-linux/) - OpenSSL ## Usage -Follow these steps to use K8s-authz: +Follow these steps to configure K8s-authz: -1. Generate certificates and keys for each user using OpenSSL. Run the script below: +1. Generate certificates and keys for each user using OpenSSL. Run: ```bash ./gen_cert.sh ``` -2. Build the Docker image from the [Dockerfile](https://github.com/casbin/k8s-authz/blob/master/Dockerfile) manually by running the following command. Remember to change the build version in the command and in the deployment [file](https://github.com/casbin/k8s-authz/blob/718f58c46e3dbf79063b5b1c18348c2fee5de9e9/manifests/deployment.yaml#L18) accordingly. +2. Build the Docker image from the [Dockerfile](https://github.com/casbin/k8s-authz/blob/master/Dockerfile) manually. Update the version number in both the command and the deployment [file](https://github.com/casbin/k8s-authz/blob/718f58c46e3dbf79063b5b1c18348c2fee5de9e9/manifests/deployment.yaml#L18): ```bash docker build -t casbin/k8s_authz:0.1 . ``` -3. Define the Casbin policies in the [model.conf](https://github.com/casbin/k8s-authz/blob/master/config/model.conf) and [policy.csv](https://github.com/casbin/k8s-authz/blob/master/config/policy.csv) files. For more information on how these policies work, refer to the [documentation](/docs/how-it-works). +3. Define Casbin policies in [model.conf](https://github.com/casbin/k8s-authz/blob/master/config/model.conf) and [policy.csv](https://github.com/casbin/k8s-authz/blob/master/config/policy.csv) files. For policy configuration details, see the [documentation](/docs/how-it-works). -4. Before deploying, you can modify the ports in the [main.go](https://github.com/casbin/k8s-authz/blob/master/main.go) file, as well as in the validation webhook configuration [file](https://github.com/casbin/k8s-authz/blob/master/manifests/deployment.yaml), based on your specific requirements. +4. (Optional) Modify ports in [main.go](https://github.com/casbin/k8s-authz/blob/master/main.go) and the validation webhook configuration [file](https://github.com/casbin/k8s-authz/blob/master/manifests/deployment.yaml) according to your requirements. -5. Deploy the validation controller and the webhook on the Kubernetes cluster by running the following command: +5. Deploy the validation controller and webhook to the Kubernetes cluster: ```bash kubectl apply -f deployment.yaml ``` -6. For a production server, it is recommended to create a Kubernetes `secret` to secure the certificates: +6. For production environments, create a Kubernetes `secret` to secure certificates: ```bash kubectl create secret generic casbin -n default \ @@ -52,6 +52,6 @@ Follow these steps to use K8s-authz: --from-file=cert.pem=certs/casbin-crt.pem ``` -7. After completing the above steps, you need to update the certificate directory in [main.go](https://github.com/casbin/k8s-authz/blob/3560551427c0431a9d4594ad1206f084ede37c49/main.go#L26) and the [manifests](https://github.com/casbin/k8s-authz/blob/3560551427c0431a9d4594ad1206f084ede37c49/manifests/deployment.yaml#L22) with the directory of the created `secret`. +7. Update the certificate directory paths in [main.go](https://github.com/casbin/k8s-authz/blob/3560551427c0431a9d4594ad1206f084ede37c49/main.go#L26) and the [manifests](https://github.com/casbin/k8s-authz/blob/3560551427c0431a9d4594ad1206f084ede37c49/manifests/deployment.yaml#L22) to reference the created `secret`. -Now, the server should be up and running, ready to validate requests made to K8s resources and enforce policies accordingly. +The server should now be operational, validating requests to Kubernetes resources and enforcing policies. diff --git a/docs/K8sGateKeeper.mdx b/docs/K8sGateKeeper.mdx index 1d6155c2..7b4a6699 100644 --- a/docs/K8sGateKeeper.mdx +++ b/docs/K8sGateKeeper.mdx @@ -6,15 +6,15 @@ keywords: [k8s-gatekeeper, Kubernetes, K8s] authors: [ComradeProgrammer] --- -## 1. Overview & Documents for Casbin K8s-Gatekeeper +## 1. Overview & Documentation for Casbin K8s-Gatekeeper -Casbin K8s-GateKeeper is a Kubernetes admission webhook that integrates Casbin as the Access Control tool. By using Casbin K8s-GateKeeper, you can establish flexible rules to authorize or intercept any operation on K8s resources, WITHOUT writing any piece of code, but only several lines of declarative configurations of Casbin models and policies, which are part of the Casbin ACL (Access Control List) language. +Casbin K8s-GateKeeper is a Kubernetes admission webhook that integrates Casbin for access control. Using Casbin K8s-GateKeeper, you can define flexible authorization rules for any Kubernetes resource operation through declarative Casbin model and policy configurations—no code required. -Casbin K8s-GateKeeper is developed and maintained by the Casbin community. The repository of this project is available here: [https://github.com/casbin/k8s-gatekeeper](https://github.com/casbin/k8s-gatekeeper) +Casbin K8s-GateKeeper is developed and maintained by the Casbin community. Repository: [https://github.com/casbin/k8s-gatekeeper](https://github.com/casbin/k8s-gatekeeper) -### 0.1 A Simple Example +### 0.1 A Basic Example -For example, you don't need to write any code, but use the following lines of configuration to achieve this function: "Forbid images with some specified tags to be used in any deployments": +Here's an example that blocks deployments using images with specific tags, using only configuration: Model: @@ -33,33 +33,33 @@ m = r.obj.Request.Namespace == "default" && r.obj.Request.Resource.Resource =="d contain(split(accessWithWildcard(${OBJECT}.Spec.Template.Spec.Containers , "*", "Image"),":",1) , p.obj) ``` -And Policy: +Policy: ```csv p, "1.14.1",deny ``` -These are in ordinary Casbin ACL language. Suppose you have already read chapters about them, it will be very easy to understand. +This uses standard Casbin ACL language, which should be straightforward if you've read the introductory chapters. -Casbin K8s-Gatekeeper has the following advantages: +Casbin K8s-Gatekeeper offers several advantages: -- Easy to use. Writing several lines of ACL is far better than writing lots of code. -- It allows hot updates of configurations. You don't need to shut down the whole plugin to modify configurations. -- It is flexible. Arbitrary rules can be made on any K8s resource, which can be explored with `kubectl gatekeeper`. -- It simplifies the implementation of K8s admission webhook, which is very complicated. You don't need to know what K8s admission webhook is or how to write code for it. All you need to do is to know the resource on which you want to put constraints and then write Casbin ACL. Everyone knows that K8s is complex, but by using Casbin K8s-Gatekeeper, your time can be saved. -- It is maintained by the Casbin community. Feel free to contact us if anything about this plugin confuses you or if you encounter any problems when trying this. +- Simple to use—write ACL configurations instead of extensive code +- Supports live configuration updates without plugin restarts +- Flexible—apply arbitrary rules to any Kubernetes resource using `kubectl gatekeeper` +- Simplifies Kubernetes admission webhook implementation—no need to understand webhook internals or write webhook code. Just define constraints and write Casbin ACL. +- Community-maintained—contact us with questions or issues -### 1.1 How Casbin K8s-Gatekeeper Works? +### 1.1 How Casbin K8s-Gatekeeper Works -K8s-Gatekeeper is an admission webhook for K8s that uses [Casbin](/docs/overview) to apply arbitrary user-defined access control rules to help prevent any operation on K8s that the administrator doesn't want. +K8s-Gatekeeper is an admission webhook for Kubernetes that uses [Casbin](/docs/overview) to enforce custom access control rules, preventing unwanted operations on Kubernetes resources. -Casbin is a powerful and efficient open-source access control library. It provides support for enforcing authorization based on various access control models. For more details about Casbin, see [Overview](/docs/overview). +Casbin is an efficient open-source access control library supporting various authorization models. For details, see the [Overview](/docs/overview). -Admission webhooks in K8s are HTTP callbacks that receive 'admission requests' and do something with them. In particular, K8s-Gatekeeper is a special type of admission webhook: 'ValidatingAdmissionWebhook', which can decide whether to accept or reject this admission request or not. As for admission requests, they are HTTP requests describing an operation on specified resources of K8s (for example, creating/deleting a deployment). For more about admission webhooks, see [K8s official documentation](https://kubernetes.io/docs/reference/access-authn-authz/extensible-admission-controllers/#what-are-admission-webhooks). +Admission webhooks in Kubernetes are HTTP callbacks that receive and process admission requests. K8s-Gatekeeper is a ValidatingAdmissionWebhook that accepts or rejects admission requests. Admission requests are HTTP requests describing operations on Kubernetes resources (e.g., creating or deleting a deployment). For more information, see the [Kubernetes documentation](https://kubernetes.io/docs/reference/access-authn-authz/extensible-admission-controllers/#what-are-admission-webhooks). -### 1.2 An Example Illustrating How It Works +### 1.2 Example Workflow -For example, when somebody wants to create a deployment containing a pod running nginx (using kubectl or K8s clients), K8s will generate an admission request, which (if translated into YAML format) can be something like this: +When someone creates a deployment with an nginx pod (via kubectl or Kubernetes clients), Kubernetes generates an admission request like this (in YAML format): ```yaml apiVersion: apps/v1 @@ -83,11 +83,11 @@ spec: - containerPort: 80 ``` -This request will go through the process of all the middleware shown in the picture, including our K8s-Gatekeeper. K8s-Gatekeeper can detect all the Casbin enforcers stored in K8s's etcd, which is created and maintained by the user (via `kubectl` or the Go client we provide). Each enforcer contains a Casbin model and a Casbin policy. The admission request will be processed by every enforcer, one by one, and only by passing all enforcers can a request be accepted by this K8s-Gatekeeper. +This request passes through middleware layers, including K8s-Gatekeeper. K8s-Gatekeeper detects all Casbin enforcers stored in Kubernetes etcd (created and maintained by users via `kubectl` or the provided Go client). Each enforcer contains a Casbin model and policy. The admission request is evaluated by each enforcer sequentially, and must pass all enforcers to be accepted. -(If you do not understand what a Casbin enforcer, model, or policy is, see this document: [Get Started](/docs/get-started)). +(If you're unfamiliar with Casbin enforcers, models, or policies, see [Get Started](/docs/get-started)). -For example, for some reason, the administrator wants to forbid the appearance of the image 'nginx:1.14.1' while allowing 'nginx:1.3.1'. An enforcer containing the following rule and policy can be created (We will explain how to create an enforcer, what these models and policies are, and how to write them in the following chapters). +For instance, if an administrator wants to block the 'nginx:1.14.1' image while allowing 'nginx:1.3.1', they can create an enforcer with this model and policy (creation and configuration details follow in subsequent sections): Model: @@ -114,35 +114,35 @@ p, "nginx:1.13.1",allow p, "nginx:1.14.1",deny ``` -By creating an enforcer containing the model and policy above, the previous admission request will be rejected by this enforcer, which means K8s won't create this deployment. +Creating an enforcer with this model and policy will reject the admission request, preventing Kubernetes from creating the deployment. -## 2 Install K8s-gatekeeper +## 2. Installing K8s-gatekeeper -There are three methods available for installing K8s-gatekeeper: External webhook, Internal webhook, and Helm. +Three installation methods are available: External webhook, Internal webhook, and Helm. :::note -Note: These methods are only meant for users to try out K8s-gatekeeper and are not secure. If you wish to use it in a productive environment, please ensure that you read [Chapter 5. Advanced settings](#5-advanced-settings) and make any necessary modifications before installation. +These installation methods are for evaluation purposes only. For production deployments, review [Chapter 5. Advanced settings](#5-advanced-settings) and apply necessary security modifications before installation. ::: -### 2.1 Internal webhook +### 2.1 Internal Webhook -#### 2.1.1 Step 1: Build the image +#### 2.1.1 Step 1: Build the Image -For the internal webhook method, the webhook itself will be implemented as a service within Kubernetes. To create the necessary service and deployment, you need to build an image of K8s-gatekeeper. You can build your own image by running the following command: +For internal webhook deployment, K8s-gatekeeper runs as a Kubernetes service. Build the image: ```shell docker build --target webhook -t k8s-gatekeeper . ``` -This command will create a local image called 'k8s-gatekeeper:latest'. +This creates a local image named 'k8s-gatekeeper:latest'. :::note -Note: If you are using minikube, please execute `eval $(minikube -p minikube docker-env)` before running 'docker build'. +For minikube users, run `eval $(minikube -p minikube docker-env)` before 'docker build'. ::: -#### 2.1.2 Step 2: Set up services and deployments for K8s-gatekeeper +#### 2.1.2 Step 2: Deploy Services and Resources -Run the following commands: +Run these commands: ```shell kubectl apply -f config/rbac.yaml @@ -150,24 +150,24 @@ kubectl apply -f config/webhook_deployment.yaml kubectl apply -f config/webhook_internal.yaml ``` -This will start running K8s-gatekeeper, and you can confirm this by running `kubectl get pods`. +Verify deployment with `kubectl get pods`. -#### 2.1.3 Step 3: Install CRD Resources for K8s-gatekeeper +#### 2.1.3 Step 3: Install CRD Resources -Run the following commands: +Install custom resource definitions: ```shell kubectl apply -f config/auth.casbin.org_casbinmodels.yaml kubectl apply -f config/auth.casbin.org_casbinpolicies.yaml ``` -### 2.2 External webhook +### 2.2 External Webhook -For the external webhook method, K8s-gatekeeper will be running outside of Kubernetes, and Kubernetes will access K8s-gatekeeper as it would access a regular website. Kubernetes has a mandatory requirement that the admission webhook must be HTTPS. For the purpose of trying out K8s-gatekeeper, we have provided a set of certificates and a private key (although this is not secure). If you prefer to use your own certificate, please refer to [Chapter 5. Advanced settings](#5-advanced-settings) for instructions on adjusting the certificate and private key. +For external webhook deployment, K8s-gatekeeper runs outside Kubernetes. Kubernetes requires HTTPS for admission webhooks. We provide test certificates and a private key (not production-secure). For custom certificates, see [Chapter 5. Advanced settings](#5-advanced-settings). -The certificate we provide is issued for 'webhook.domain.local'. So, modify the host (e.g., /etc/hosts) and point 'webhook.domain.local' to the IP address on which K8s-gatekeeper is running. +The provided certificate is issued for 'webhook.domain.local'. Update your hosts file (e.g., /etc/hosts) to point 'webhook.domain.local' to the IP address where K8s-gatekeeper runs. -Then execute the following command: +Execute: ```shell go mod tidy @@ -178,111 +178,111 @@ kubectl apply -f config/auth.casbin.org_casbinpolicies.yaml kubectl apply -f config/webhook_external.yaml ``` -### 2.3 Install K8s-gatekeeper via Helm +### 2.3 Installing via Helm + +#### 2.3.1 Step 1: Build the Image -#### 2.3.1 Step 1: Build the image +See [Chapter 2.1.1](#211-step-1-build-the-image). -Please refer to [Chapter 2.1.1](#211-step-1-build-the-image). +#### 2.3.2 Helm Installation -#### 2.3.2 Helm installation +Run: `helm install k8sgatekeeper ./k8sgatekeeper` -Run the command `helm install k8sgatekeeper ./k8sgatekeeper`. +## 3. Using K8s-gatekeeper -## 3. Try K8s-gatekeeper +### 3.1 Creating Casbin Models and Policies -### 3.1 Create Casbin Model and Policy +Create models and policies using either kubectl or the provided Go client. -You have two methods to create a model and policy: via kubectl or via the go-client we provide. +#### 3.1.1 Create/Update via kubectl -#### 3.1.1 Create/Update Casbin Model and Policy via kubectl +In K8s-gatekeeper, Casbin models are stored as 'CasbinModel' CRD resources. The definition is in `config/auth.casbin.org_casbinmodels.yaml`. -In K8s-gatekeeper, the Casbin model is stored in a CRD resource called 'CasbinModel'. Its definition is located in `config/auth.casbin.org_casbinmodels.yaml`. +See examples in `example/allowed_repo/model.yaml`. Important fields: -There are examples in `example/allowed_repo/model.yaml`. Pay attention to the following fields: +- metadata.name: Model name. Must match the associated CasbinPolicy object name for K8s-gatekeeper to pair them correctly. +- spec.enable: Set to "false" to disable this model and its associated policy. +- spec.modelText: String containing the Casbin model definition. -- metadata.name: the name of the model. This name MUST be the same as the name of the CasbinPolicy object related to this model, so that K8s-gatekeeper can pair them and create an enforcer. -- spec.enable: if this field is set to "false", this model (as well as the CasbinPolicy object related to this model) will be ignored. -- spec.modelText: a string that contains the model text of a Casbin model. +Casbin policies are stored as 'CasbinPolicy' CRD resources, defined in `config/auth.casbin.org_casbinpolicies.yaml`. -The Casbin Policy is stored in another CRD resource called 'CasbinPolicy', whose definition can be found in `config/auth.casbin.org_casbinpolicies.yaml`. +See examples in `example/allowed_repo/policy.yaml`. Important fields: -There are examples in `example/allowed_repo/policy.yaml`. Pay attention to the following fields: +- metadata.name: Policy name. Must match the associated CasbinModel object name. +- spec.policyItem: String containing the Casbin policy definition. -- metadata.name: the name of the policy. This name MUST be the same as the name of the CasbinModel object related to this policy, so that K8s-gatekeeper can pair them and create an enforcer. -- spec.policyItem: a string that contains the policy text of a Casbin model. - -After creating your own CasbinModel and CasbinPolicy files, use the following command to apply them: +Apply your CasbinModel and CasbinPolicy files: ```shell kubectl apply -f ``` -Once a pair of CasbinModel and CasbinPolicy is created, K8s-gatekeeper will be able to detect it within 5 seconds. +K8s-gatekeeper detects new CasbinModel/CasbinPolicy pairs within 5 seconds. -#### 3.1.2 Create/Update Casbin Model and Policy via the go-client we provide +#### 3.1.2 Create/Update via Go Client -We understand that there may be situations where it is not convenient to use the shell to execute commands directly on a node of the K8s cluster, such as when you are building an automatic cloud platform for your corporation. Therefore, we have developed a go-client to create and maintain CasbinModel and CasbinPolicy. +For scenarios where direct shell access to cluster nodes is impractical (e.g., when building automated cloud platforms), we provide a Go client for managing CasbinModel and CasbinPolicy resources. -The go-client library is located in `pkg/client`. +The Go client library is in `pkg/client`. -In `client.go`, we provide a function to create a client. +In `client.go`, use this function to create a client: ```go func NewK8sGateKeeperClient(externalClient bool) (*K8sGateKeeperClient, error) ``` -The `externalClient` parameter determines whether K8s-gatekeeper is running inside the K8s cluster or not. +The `externalClient` parameter indicates whether K8s-gatekeeper runs inside or outside the Kubernetes cluster. -In `model.go`, we provide various functions to create, delete, and modify CasbinModel. You can find out how to use these interfaces in `model_test.go`. +In `model.go`, functions are provided for creating, deleting, and modifying CasbinModel. See `model_test.go` for usage examples. -In `policy.go`, we provide various functions to create, delete, and modify CasbiPolicy. You can find out how to use these interfaces in `policy_test.go`. +In `policy.go`, functions are provided for creating, deleting, and modifying CasbinPolicy. See `policy_test.go` for usage examples. -### 3.1.2 Try Whether K8s-gatekeeper Works +### 3.1.2 Testing K8s-gatekeeper -Suppose you have already created the exact model and policy in `example/allowed_repo`. Now, try the following command: +After creating the model and policy from `example/allowed_repo`, test with: ```shell kubectl apply -f example/allowed_repo/testcase/reject_1.yaml ``` -You should find that K8s will reject this request and mention that the webhook was the reason why this request is rejected. However, when you try to apply `example/allowed_repo/testcase/approve_2.yaml`, it will be accepted. +Kubernetes should reject this request, citing the webhook as the rejection reason. However, applying `example/allowed_repo/testcase/approve_2.yaml` should succeed. -## 4. How to Write Model and Policy with K8s-gatekeeper +## 4. Writing Models and Policies for K8s-gatekeeper -First of all, make sure you are familiar with the basic grammar of Casbin Models and Policies. If you are not, please read the [Get Started](/docs/get-started) section first. In this chapter, we assume that you already understand what Casbin Models and Policies are. +Ensure you understand Casbin model and policy syntax before proceeding. If not, read the [Get Started](/docs/get-started) section first. This chapter assumes familiarity with Casbin models and policies. -### 4.1 Request Definition of Model +### 4.1 Request Definition -When K8s-gatekeeper is authorizing a request, the input is always an object: the Go object of the Admission Request. This means that the enforcer will always be used like this: +When K8s-gatekeeper evaluates a request, the input is always an AdmissionReview Go object. The enforcer is used as follows: ```go ok, err := enforcer.Enforce(admission) ``` -where `admission` is an `AdmissionReview` object defined by K8s's official go api `"k8s.io/api/admission/v1"`. You can find the definition of this struct in this repository: [https://github.com/kubernetes/api/blob/master/admission/v1/types.go](https://github.com/kubernetes/api/blob/master/admission/v1/types.go). For more information, you can also refer to [https://kubernetes.io/docs/reference/access-authn-authz/extensible-admission-controllers/#webhook-request-and-response](https://kubernetes.io/docs/reference/access-authn-authz/extensible-admission-controllers/#webhook-request-and-response). +where `admission` is an `AdmissionReview` object from Kubernetes' official Go API `"k8s.io/api/admission/v1"`. The struct definition is available at: [https://github.com/kubernetes/api/blob/master/admission/v1/types.go](https://github.com/kubernetes/api/blob/master/admission/v1/types.go). Additional documentation: [https://kubernetes.io/docs/reference/access-authn-authz/extensible-admission-controllers/#webhook-request-and-response](https://kubernetes.io/docs/reference/access-authn-authz/extensible-admission-controllers/#webhook-request-and-response). -Therefore, for any model used by K8s-gatekeeper, the definition of the `request_definition` should always be like this: +For K8s-gatekeeper models, the `request_definition` should always follow this format: ```ini [request_definition] r = obj ``` -The name 'obj' is not mandatory, as long as the name is consistent with the name used in the `[matchers]` part. +The name 'obj' can be changed as long as it's used consistently in the `[matchers]` section. -### 4.2 Matchers of Model +### 4.2 Model Matchers -You are supposed to use the ABAC feature of Casbin to write your rules. However, the expression evaluator integrated in Casbin does not support indexing in maps or arrays(slices), nor the expansion of arrays. Therefore, K8s-gatekeeper provides various 'Casbin functions' as extensions to implement these features. If you still find that your demand cannot be fulfilled by these extensions, feel free to start an issue, or create a pull request. +Use Casbin's ABAC feature to write rules. However, Casbin's expression evaluator doesn't natively support map/array indexing or array expansion. K8s-gatekeeper provides extension functions to address this. If you need additional functionality, please open an issue or submit a pull request. -If you are not familiar with Casbin functions, you can refer to [Function](/docs/function) for more information. +For background on Casbin functions, see [Function](/docs/function). -Here are the extension functions: +Extension functions: -### 4.2.1 Extension functions +### 4.2.1 Extension Functions #### 4.2.1.1 access -Access is used to solve the problem that Casbin does not support indexing in maps or arrays. The example `example/allowed_repo/model.yaml` demonstrates the usage of this function: +The `access` function enables map and array indexing. See `example/allowed_repo/model.yaml`: ```ini [matchers] @@ -290,9 +290,9 @@ m = r.obj.Request.Namespace == "default" && r.obj.Request.Resource.Resource =="d access(r.obj.Request.Object.Object.Spec.Template.Spec.Containers , 0, "Image") == p.obj ``` -In this matcher, `access(r.obj.Request.Object.Object.Spec.Template.Spec.Containers , 0, "Image")` is equivalent to `r.obj.Request.Object.Object.Spec.Template.Spec.Containers[0].Image`, where `r.obj.Request.Object.Object.Spec.Template.Spec.Containers` is a slice. +Here, `access(r.obj.Request.Object.Object.Spec.Template.Spec.Containers , 0, "Image")` is equivalent to `r.obj.Request.Object.Object.Spec.Template.Spec.Containers[0].Image`, where `r.obj.Request.Object.Object.Spec.Template.Spec.Containers` is a slice. -Access can also call simple functions that have no parameters and return a single value. The example `example/container_resource_limit/model.yaml` demonstrates this: +`access` can also call parameterless functions that return a single value. See `example/container_resource_limit/model.yaml`: ```ini [matchers] @@ -301,26 +301,26 @@ Access can also call simple functions that have no parameters and return a singl parseFloat(access(r.obj.Request.Object.Object.Spec.Template.Spec.Containers , 0, "Resources","Limits","memory","Value")) >= parseFloat(p.memory) ``` -In this matcher, `access(r.obj.Request.Object.Object.Spec.Template.Spec.Containers , 0, "Resources","Limits","cpu","Value")` is equivalent to `r.obj.Request.Object.Object.Spec.Template.Spec.Containers[0].Resources.Limits["cpu"].Value()`, where `r.obj.Request.Object.Object.Spec.Template.Spec.Containers[0].Resources.Limits` is a map, and `Value()` is a simple function that has no parameters and returns a single value. +Here, `access(r.obj.Request.Object.Object.Spec.Template.Spec.Containers , 0, "Resources","Limits","cpu","Value")` equals `r.obj.Request.Object.Object.Spec.Template.Spec.Containers[0].Resources.Limits["cpu"].Value()`, where `r.obj.Request.Object.Object.Spec.Template.Spec.Containers[0].Resources.Limits` is a map and `Value()` is a parameterless function returning a single value. #### 4.2.1.2 accessWithWildcard -Sometimes, you may have a demand like this: all elements in an array must have a prefix "aaa". However, Casbin does not support `for` loops. With `accessWithWildcard` and the "map/slice expansion" feature, you can easily implement such a demand. +To check conditions across all array elements (e.g., "all elements must start with 'aaa'") without `for` loops, use `accessWithWildcard` with map/slice expansion. -For example, suppose `a.b.c` is an array `[aaa,bbb,ccc,ddd,eee]`, then the result of `accessWithWildcard(a,"b","c","*")` will be a slice `[aaa,bbb,ccc,ddd,eee]`. By using the wildcard `*`, the slice is expanded. +If `a.b.c` is the array `[aaa,bbb,ccc,ddd,eee]`, then `accessWithWildcard(a,"b","c","*")` returns the slice `[aaa,bbb,ccc,ddd,eee]`. The wildcard `*` expands the slice. -Similarly, the wildcard can be used more than once. For example, the result of `accessWithWildcard(a,"b","c","*","*")` will be `[a.b.c[0][0], a.b.c[0][1], ..., a.b.c[1][0], a.b.c[1][1], ...]`. +Multiple wildcards are supported. For example, `accessWithWildcard(a,"b","c","*","*")` returns `[a.b.c[0][0], a.b.c[0][1], ..., a.b.c[1][0], a.b.c[1][1], ...]`. -### 4.2.1.3 Functions Supporting Variable-length Arguments +### 4.2.1.3 Variable-Length Argument Functions -In the expression evaluator of Casbin, when a parameter is an array, it will be automatically expanded as a variable-length argument. Utilizing this feature to support array/slice/map expansion, we have also integrated several functions that accept an array/slice as a parameter: +Casbin's expression evaluator automatically expands arrays as variable-length arguments. Leveraging this for array/slice/map expansion, several functions accept arrays/slices: -- contain(): accepts multiple parameters and returns whether any parameter (except the last parameter) equals the last parameter. -- split(a,b,c...,sep,index): returns a slice that contains `[splits(a,sep)[index], splits(b,sep)[index], splits(a,sep)[index], ...]`. -- len(): returns the length of the variable-length argument. -- matchRegex(a,b,c...,regex): returns whether all of the given parameters (`a`, `b`, `c`, ...) match the given regex. +- contain(): Accepts multiple parameters and returns whether any parameter (except the last) equals the last parameter. +- split(a,b,c...,sep,index): Returns `[splits(a,sep)[index], splits(b,sep)[index], splits(c,sep)[index], ...]`. +- len(): Returns the variable-length argument count. +- matchRegex(a,b,c...,regex): Returns whether all parameters (`a`, `b`, `c`, ...) match the regex. -Here is an example in `example/disallowed_tag/model.yaml`: +Example from `example/disallowed_tag/model.yaml`: ```ini [matchers] @@ -328,87 +328,86 @@ Here is an example in `example/disallowed_tag/model.yaml`: contain(split(accessWithWildcard(r.obj.Request.Object.Object.Spec.Template.Spec.Containers , "*", "Image"),":",1) , p.obj) ``` -Assuming that `accessWithWildcard(r.obj.Request.Object.Object.Spec.Template.Spec.Containers , "*", "Image")` returns `["a:b", "c:d", "e:f", "g:h"]`, because splits supports variable-length arguments and performs the splits operation on each element, the element at index 1 will be selected and returned. Therefore, `split(accessWithWildcard(r.obj.Request.Object.Object.Spec.Template.Spec.Containers , "*", "Image"),":",1)` returns `["b","d","f","h"]`. And `contain(split(accessWithWildcard(r.obj.Request.Object.Object.Spec.Template.Spec.Containers , "*", "Image"),":",1) , p.obj)` returns whether `p.obj` is contained in `["b","d","f","h"]`. +If `accessWithWildcard(r.obj.Request.Object.Object.Spec.Template.Spec.Containers , "*", "Image")` returns `["a:b", "c:d", "e:f", "g:h"]`, the split operation processes each element with variable-length argument support, selecting index 1 from each. Thus, `split(accessWithWildcard(r.obj.Request.Object.Object.Spec.Template.Spec.Containers , "*", "Image"),":",1)` returns `["b","d","f","h"]`. Finally, `contain(split(accessWithWildcard(r.obj.Request.Object.Object.Spec.Template.Spec.Containers , "*", "Image"),":",1) , p.obj)` checks if `p.obj` exists in `["b","d","f","h"]`. #### 4.2.1.2 Type Conversion Functions -- ParseFloat(): Parses an integer to a float (this is necessary because any number used in comparison must be converted into a float). -- ToString(): Converts an object to a string. This object must have a basic type of string (for example, an object of type `XXX` when there is a statement `type XXX string`). +- ParseFloat(): Converts integers to floats (required because comparisons need float type). +- ToString(): Converts objects to strings. The object must have an underlying string type (e.g., `type XXX string`). - IsNil(): Returns whether the parameter is nil. ## 5. Advanced Settings -### 5.1 About Certificates +### 5.1 Certificate Configuration -In Kubernetes (k8s), it is mandatory that a webhook should use HTTPS. There are two approaches to achieve this: +Kubernetes requires webhooks to use HTTPS. Two options are available: -- Use self-signed certificates (examples in this repository use this method) -- Use a normal certificate +- Self-signed certificates (used in this repository's examples) +- Publicly trusted certificates -#### 5.1.1 Self-signed certificates +#### 5.1.1 Self-Signed Certificates -Using a self-signed certificate means that the Certificate Authority (CA) issuing the certificate is not one of the well-known CAs. Therefore, you must let k8s know about this CA. +Self-signed certificates use a Certificate Authority (CA) that isn't publicly recognized. You must configure Kubernetes to trust this CA. -Currently, the example in this repository uses a self-made CA, whose private key and certificate are stored in `config/certificate/ca.crt` and `config/certificate/ca.key` respectively. The certificate for the webhook is `config/certificate/server.crt`, which is issued by the self-made CA. The domains of this certificate are "webhook.domain.local" (for external webhook) and "casbin-webhook-svc.default.svc" (for internal webhook). +The repository examples use a custom CA with private key and certificate stored in `config/certificate/ca.key` and `config/certificate/ca.crt`. The webhook certificate `config/certificate/server.crt` is issued by this CA for domains "webhook.domain.local" (external webhook) and "casbin-webhook-svc.default.svc" (internal webhook). -Information about the CA is passed to k8s via webhook configuration files. Both `config/webhook_external.yaml` and `config/webhook_internal.yaml` have a field called "CABundle", which contains a base64 encoded string of the CA's certificate. +CA information is passed to Kubernetes via webhook configuration files. Both `config/webhook_external.yaml` and `config/webhook_internal.yaml` contain a "CABundle" field with the base64-encoded CA certificate. -In case you need to change the certificate/domain (for example, if you want to put this webhook into another namespace of k8s while using an internal webhook, or if you want to change the domain while using an external webhook), the following procedures should be followed: +To change the certificate/domain (e.g., moving the webhook to another namespace or changing domains): 1. Generate a new CA: - - Generate the private key for the fake CA: + - Generate the CA private key: ```shell openssl genrsa -des3 -out ca.key 2048 ``` - - Remove the password protection of the private key: + - Remove password protection: - ``` shell + ```shell openssl rsa -in ca.key -out ca.key ``` -2. Generate a private key for the webhook server: +2. Generate a webhook server private key: ```shell openssl genrsa -des3 -out server.key 2048 openssl rsa -in server.key -out server.key ``` -3. Use the self-generated CA to sign the certificate for the webhook: +3. Sign the webhook certificate with the CA: - - Copy your system's openssl config file for temporary use. You can find out the location of the config file by running `openssl version -a`, usually called `openssl.cnf`. + - Copy your system's OpenSSL config file (find it with `openssl version -a`, typically `openssl.cnf`). - - In the config file: - - Find the `[req]` paragraph and add the following line: `req_extensions = v3_req` - - Find the `[v3_req]` paragraph and add the following line: `subjectAltName = @alt_names` - - Append the following lines to the file: + - Modify the config file: + - In the `[req]` section, add: `req_extensions = v3_req` + - In the `[v3_req]` section, add: `subjectAltName = @alt_names` + - Append: ```ini [alt_names] - DNS.2= + DNS.2= ``` - Note: Replace 'casbin-webhook-svc.default.svc' with the real service name of your own service if you decide to modify the service name. + Note: Replace 'casbin-webhook-svc.default.svc' with your actual service name if modified. - - Use the modified config file to generate a certificate request file: + - Generate a certificate request: ```shell openssl req -new -nodes -keyout server.key -out server.csr -config openssl.cnf ``` - - Use the self-made CA to respond to the request and sign the certificate: + - Sign the certificate with the CA: ```shell openssl x509 -req -days 3650 -in server.csr -out server.crt -CA ca.crt -CAkey ca.key -CAcreateserial -extensions v3_req -extensions SAN -extfile openssl.cnf ``` -4. Replace the 'CABundle' field: - Both `config/webhook_external.yaml` and `config/webhook_internal.yaml` have a field called "CABundle", which contains a base64 encoded string of the certificate of the CA. Update this field with the new certificate. +4. Update the 'CABundle' field in both `config/webhook_external.yaml` and `config/webhook_internal.yaml` with the base64-encoded new CA certificate. -5. If you are using helm, similar changes need to be applied to the helm charts. +5. For Helm deployments, apply equivalent changes to the Helm charts. -#### 5.1.2 Legal certificates +#### 5.1.2 Publicly Trusted Certificates -If you use legal certificates, you do not need to go through all these procedures. Remove the "CABundle" field in `config/webhook_external.yaml` and `config/webhook_internal.yaml`, and change the domain in these files to the domain you own. +With publicly trusted certificates, skip the above procedures. Remove the "CABundle" field from `config/webhook_external.yaml` and `config/webhook_internal.yaml`, and set the domain to your registered domain. diff --git a/docs/KongAuthz.mdx b/docs/KongAuthz.mdx index 7cb61df4..10fb1d6a 100644 --- a/docs/KongAuthz.mdx +++ b/docs/KongAuthz.mdx @@ -6,25 +6,25 @@ keywords: [Kong, Kong API Gateway, kong-authz, Lua] authors: [hsluoyz] --- -[kong-authz](https://github.com/casbin-lua/kong-authz) is an authorization plugin for Kong based on [lua-casbin](https://github.com/casbin/lua-casbin/). This plugin enables request authorization in Kong API Gateway using Casbin's powerful and flexible access control models. +[kong-authz](https://github.com/casbin-lua/kong-authz) is an authorization plugin for Kong built on [lua-casbin](https://github.com/casbin/lua-casbin/). This plugin enables request authorization in Kong API Gateway using Casbin's flexible access control models. ## Prerequisites -The following need to be installed in advance: +Install the following before proceeding: - [Kong](https://konghq.com/) -- [4daysorm-adapter](https://github.com/casbin-lua/4daysorm-adapter) (optional, if you want to use database as policy storage) -- [luasql-adapter](https://github.com/casbin-lua/luasql-adapter) (optional, if you want to use database as policy storage) +- [4daysorm-adapter](https://github.com/casbin-lua/4daysorm-adapter) (optional, for database-backed policy storage) +- [luasql-adapter](https://github.com/casbin-lua/luasql-adapter) (optional, for database-backed policy storage) :::info -The Casbin policy is read from a file by default. If you want to use Casbin policy from a database, choose either 4daysorm-adapter or luasql-adapter. +By default, policies are loaded from files. To use database-backed policies, install either 4daysorm-adapter or luasql-adapter. ::: ## Installation -Ensure you have Casbin's system dependencies installed: +Install Casbin's system dependencies: -- For systems with `apt` package manager: +- For systems with `apt`: ```bash sudo apt install gcc libpcre3 libpcre3-dev @@ -48,14 +48,14 @@ Install the kong-authz plugin: sudo luarocks install https://raw.githubusercontent.com/casbin-lua/kong-authz/master/kong-authz-0.0.1-1.rockspec ``` -Add the plugin to your `kong.conf` file by appending `kong-authz` (with a comma) to the `plugins` variable: +Add the plugin to your `kong.conf` by appending `kong-authz` (comma-separated) to the `plugins` variable: ```conf # kong.conf plugins = bundled, kong-authz ``` -Finally, start or restart Kong: +Start or restart Kong: ```bash kong start [-c /path/to/kong.conf] @@ -63,11 +63,11 @@ kong start [-c /path/to/kong.conf] ## Configuration -You can add this plugin on top of any service/API or globally by sending a request through the Kong Admin API. +Configure this plugin at the service, API, or global level through the Kong Admin API. ### File-Based Policy Storage -Add the plugin globally with file-based policy storage: +Configure globally with file-based policies: ```bash curl -i -X POST \ @@ -80,7 +80,7 @@ curl -i -X POST \ ### Database Policy Storage with LuaSQL -Add the plugin to a specific service with LuaSQL adapter: +Configure for a specific service using the LuaSQL adapter: ```bash curl -i -X POST \ @@ -99,7 +99,7 @@ curl -i -X POST \ ### Database Policy Storage with 4DaysORM -Add the plugin to a specific service with 4DaysORM adapter: +Configure for a specific service using the 4DaysORM adapter: ```bash curl -i -X POST \ @@ -116,21 +116,21 @@ curl -i -X POST \ --data 'config.db_info.port=3306' ``` -## How Authorization Works +## Authorization Process -The authorization determines a request based on `{subject, object, action}`, which means what `subject` can perform what `action` on what `object`. In this plugin: +Authorization evaluates requests using `{subject, object, action}`, determining what `subject` can perform what `action` on what `object`. In this plugin: -1. **subject**: the logged-in username as passed in the header -2. **object**: the URL path for the web resource like "dataset1/item1" -3. **action**: HTTP method like GET, POST, PUT, DELETE, or high-level actions you defined like "read-file", "write-blog" +1. **subject**: The logged-in username passed in the request header +2. **object**: The URL path for the resource (e.g., "dataset1/item1") +3. **action**: HTTP method (GET, POST, PUT, DELETE) or custom actions like "read-file" or "write-blog" -For details on writing authorization policies, refer to the [Casbin documentation](/docs/how-it-works). +For policy authoring details, consult the [Casbin documentation](/docs/how-it-works). -## Example Usage +## Example Configuration -Here's a complete example of setting up kong-authz for a service: +Complete example of configuring kong-authz for a service: -1. Set up an example service: +1. Create an example service: ```bash curl -i -X POST \ @@ -139,7 +139,7 @@ curl -i -X POST \ --data 'url=http://mockbin.org' ``` -1. Set up a route for the service: +1. Create a route for the service: ```bash curl -i -X POST \ @@ -147,7 +147,7 @@ curl -i -X POST \ --data 'hosts[]=example.com' ``` -1. Configure the kong-authz plugin: +1. Apply the kong-authz plugin: ```bash curl -i -X POST \ @@ -158,7 +158,7 @@ curl -i -X POST \ --data 'config.username=user' ``` -1. Test the authorization by sending a request: +1. Test authorization with a request: ```bash curl -i -X GET \ @@ -167,7 +167,7 @@ curl -i -X GET \ --header 'user: anonymous' ``` -When run for the first time, it will create a Casbin Enforcer using the model and policy paths. If this returns any non-500 error, the configuration is successful. Otherwise, check the error.log file in your Kong setup. +On first execution, this creates a Casbin Enforcer using the specified model and policy paths. Any non-500 error indicates successful configuration. For 500 errors, check the error.log file in your Kong installation. ## Resources diff --git a/docs/LBAC.mdx b/docs/LBAC.mdx index 21d5d004..cef91194 100644 --- a/docs/LBAC.mdx +++ b/docs/LBAC.mdx @@ -6,13 +6,13 @@ keywords: [lbac, lattice-based access control, security model, confidentiality, authors: [nodece] --- -## What is the LBAC model? +## What is LBAC? -LBAC stands for Lattice-Based Access Control. It is a formal access control model that can be implemented in various ways. The example shown below demonstrates one possible implementation in Casbin that combines confidentiality and integrity controls. +LBAC (Lattice-Based Access Control) is a formal access control model that can be implemented in multiple ways. The implementation shown here demonstrates one approach in Casbin that combines confidentiality and integrity controls. ## Model Definition -Here is an example LBAC model implementation in Casbin: +This example shows an LBAC model implementation in Casbin: ```conf [request_definition] @@ -31,20 +31,18 @@ e = some(where (p.eft == allow)) m = (r.act == "read" && r.subject_confidentiality >= r.object_confidentiality && r.subject_integrity >= r.object_integrity) || (r.act == "write" && r.subject_confidentiality <= r.object_confidentiality && r.subject_integrity <= r.object_integrity) ``` -## How it works +## How It Works -In this example implementation, the matcher function implements access control rules based on two security properties: +This implementation uses the matcher function to enforce access control based on two security dimensions: -- **Confidentiality Control**: Prevents unauthorized disclosure of information -- **Integrity Control**: Prevents unauthorized modification of information +- **Confidentiality Control**: Protects against unauthorized information disclosure +- **Integrity Control**: Protects against unauthorized information modification -The access control decisions are made by comparing the security levels of subjects and objects in both dimensions. +Access decisions are made by comparing security levels of subjects and objects across both dimensions. -## Examples +## Example Requests -### Request Examples - -The following are example requests to demonstrate how this LBAC implementation works: +The following examples demonstrate how this LBAC implementation evaluates requests: ```text # Normal read operations (ALLOWED) @@ -74,7 +72,7 @@ guest, 2, 2, file_private, 1, 3, write # guest (conf:2, int:2) writes file ## Security Levels -In this example implementation, both confidentiality and integrity levels are represented as integers where higher numbers indicate higher security levels: +In this implementation, both confidentiality and integrity are represented as integers where higher values indicate higher security levels: ### Confidentiality Levels @@ -90,16 +88,16 @@ In this example implementation, both confidentiality and integrity levels are re - Level 3: High integrity (e.g., system data, administrative content) - Level 4: Critical integrity (e.g., security policies, system configuration) -## Use Cases +## Applicable Scenarios -This LBAC implementation example is suitable for: +This LBAC implementation is well-suited for: - Multi-level security environments -- Applications where data protection and data accuracy are both important +- Applications where both data protection and data accuracy matter ## Implementation Notes -- The model enforces mandatory access control (MAC) with dual security properties -- Security levels are assigned by system administrators -- Access decisions are based on both confidentiality and integrity levels -- The model prevents both information leakage and data corruption +- The model implements mandatory access control (MAC) with dual security properties +- System administrators assign security levels +- Access decisions consider both confidentiality and integrity levels +- The model prevents information leakage and data corruption diff --git a/docs/LogError.mdx b/docs/LogError.mdx index 3b3df77c..162dcdb5 100644 --- a/docs/LogError.mdx +++ b/docs/LogError.mdx @@ -8,31 +8,31 @@ authors: [hsluoyz] ## Logging -Casbin uses the built-in `log` to print logs to the console by default, like: +By default, Casbin uses the built-in `log` package to print messages to the console: ```log 2017/07/15 19:43:56 [Request: alice, data1, read ---> true] ``` -Logging is not enabled by default. You can toggle it via `Enforcer.EnableLog()` or the last parameter of `NewEnforcer()`. +Logging is disabled by default. Enable it using `Enforcer.EnableLog()` or the last parameter of `NewEnforcer()`. :::note -For Golang: We already support logging the model, enforce request, role, and policy in Golang. You can define your own log for logging Casbin. +For Golang: Casbin supports logging models, enforcement requests, roles, and policies. You can implement custom loggers for Casbin. ::: :::note -For Python: PyCasbin leverages the default Python logging mechanism. PyCasbin makes a call to `logging.getLogger()` to set the logger. No special logging configuration is needed other than initializing the logger in the parent application. If no logging is initialized within the parent application, you will not see any log messages from PyCasbin. At the same time, when you enable logs in PyCasbin, you can specify the logging configuration through the parameter `logging_config`. If no configuration is specified, it will use the [default log configuration](https://github.com/casbin/pycasbin/blob/c33cabfa0ac65cd09cf812a65e71794d64cb5132/casbin/util/log.py#L6C1-L6C1). For other PyCasbin extensions, you can refer to the [Django logging docs](https://docs.djangoproject.com/en/4.2/topics/logging/) if you are a Django user. For other Python users, you should refer to the [Python logging docs](https://docs.python.org/3/library/logging.config.html) to configure the logger. +For Python: PyCasbin uses Python's standard logging mechanism. PyCasbin calls `logging.getLogger()` to configure its logger. No special configuration is needed beyond initializing logging in your application. If you don't initialize logging, PyCasbin will produce no log output. When enabling logs in PyCasbin, you can specify configuration through the `logging_config` parameter. Without explicit configuration, PyCasbin uses the [default log configuration](https://github.com/casbin/pycasbin/blob/c33cabfa0ac65cd09cf812a65e71794d64cb5132/casbin/util/log.py#L6C1-L6C1). Django users should consult the [Django logging documentation](https://docs.djangoproject.com/en/4.2/topics/logging/). Other Python users should refer to the [Python logging documentation](https://docs.python.org/3/library/logging.config.html). ::: -### Use different loggers for different enforcers +### Configure Separate Loggers for Different Enforcers -Every enforcer can have its own logger to log information, and it can be changed at runtime. +Each enforcer can have its own logger, and loggers can be changed at runtime. -And you can use a proper logger via the last parameter of `NewEnforcer()`. If you are using this way to initialize your enforcer, you don't need to use the enabled parameter because the priority of the enabled field in the logger is higher. +You can specify a logger using the last parameter of `NewEnforcer()`. When using this method, the logger's enabled field takes precedence over the enforcer's enabled parameter. ```go // Set a default logger as enforcer e1's logger. @@ -46,19 +46,19 @@ e2.SetLogger(&YouOwnLogger) e3, _ := casbin.NewEnforcer("examples/rbac_model.conf", a, logger) ``` -#### Supported loggers +#### Supported Loggers -We provide some loggers to help you log information. +Casbin provides several logger implementations: ```mdx-code-block ``` -| Logger | Author | Description | -|-----------------------------------------------------------------------------------------------------|--------|------------------------------------------------------------------------------------------------------------------------------| -| [Default logger (built-in)](https://github.com/casbin/casbin/blob/master/log/default_logger.go) | Casbin | The default logger using golang log. | -| [Zap logger](https://github.com/casbin/zap-logger) | Casbin | Using [zap](https://github.com/uber-go/zap), provide json encoded log and you can customize more with your own zap-logger. | +| Logger | Author | Description | +|-----------------------------------------------------------------------------------------------------|--------|--------------------------------------------------------------------------------------------------------------------------------| +| [Default logger (built-in)](https://github.com/casbin/casbin/blob/master/log/default_logger.go) | Casbin | The default logger using Go's standard log package. | +| [Zap logger](https://github.com/casbin/zap-logger) | Casbin | Uses [zap](https://github.com/uber-go/zap) for JSON-encoded logs with additional customization options via zap-logger. | ```mdx-code-block @@ -67,29 +67,29 @@ We provide some loggers to help you log information. | Logger | Author | Description | |-----------------------------------------------------------------|--------|--------------------------------------------------------------------------| -| [psr3-bridge logger](https://github.com/php-casbin/psr3-bridge) | Casbin | Provides a [PSR-3](https://www.php-fig.org/psr/psr-3/) compliant bridge. | +| [psr3-bridge logger](https://github.com/php-casbin/psr3-bridge) | Casbin | Provides a [PSR-3](https://www.php-fig.org/psr/psr-3/) compliant bridge.| ```mdx-code-block ``` -#### How to write a logger +#### Implementing Custom Loggers -Your logger should implement the [Logger](https://github.com/casbin/casbin/blob/master/log/logger.go#L20) interface. +Custom loggers must implement the [Logger](https://github.com/casbin/casbin/blob/master/log/logger.go#L20) interface. -| Method | Type | Description | -|--------------|-----------|-------------------------------------------| -| EnableLog() | mandatory | Control whether to print the message. | -| IsEnabled() | mandatory | Show the current logger's enabled status. | -| LogModel() | mandatory | Log info related to the model. | -| LogEnforce() | mandatory | Log info related to enforcing. | -| LogRole() | mandatory | Log info related to the role. | -| LogPolicy() | mandatory | Log info related to the policy. | +| Method | Type | Description | +|--------------|-----------|--------------------------------------------------| +| EnableLog() | mandatory | Controls whether messages are printed. | +| IsEnabled() | mandatory | Returns the current logger's enabled status. | +| LogModel() | mandatory | Logs model-related information. | +| LogEnforce() | mandatory | Logs enforcement-related information. | +| LogRole() | mandatory | Logs role-related information. | +| LogPolicy() | mandatory | Logs policy-related information. | -You can pass your custom `logger` to `Enforcer.SetLogger()`. +Pass your custom logger to `Enforcer.SetLogger()`. -Here is an example of how to customize a logger for Golang: +Here's a Go example of implementing a custom logger: ```go import ( @@ -175,34 +175,34 @@ func (l *DefaultLogger) LogRole(roles []string) { } ``` -## Error handling +## Error Handling -Errors or panics may occur when you use Casbin for reasons like: +Errors or panics can occur in Casbin for several reasons: -1. Invalid syntax in the model file (.conf). -2. Invalid syntax in the policy file (.csv). -3. Custom errors from storage adapters, e.g., MySQL fails to connect. -4. Casbin's bug. +1. Invalid syntax in the model file (.conf) +2. Invalid syntax in the policy file (.csv) +3. Custom errors from storage adapters (e.g., MySQL connection failures) +4. Casbin bugs -There are five main functions you may need to be aware of for errors or panics: +Five primary functions may produce errors or panics: -| Function | Behavior on error | +| Function | Behavior on Error | |--------------------------------------------------------------------------------|-------------------| -| [NewEnforcer()](https://godoc.org/github.com/casbin/casbin#NewEnforcer) | Returns an error | -| [LoadModel()](https://godoc.org/github.com/casbin/casbin#Enforcer.LoadModel) | Returns an error | -| [LoadPolicy()](https://godoc.org/github.com/casbin/casbin#Enforcer.LoadPolicy) | Returns an error | -| [SavePolicy()](https://godoc.org/github.com/casbin/casbin#Enforcer.SavePolicy) | Returns an error | -| [Enforce()](https://godoc.org/github.com/casbin/casbin#Enforcer.Enforce) | Returns an error | +| [NewEnforcer()](https://godoc.org/github.com/casbin/casbin#NewEnforcer) | Returns an error | +| [LoadModel()](https://godoc.org/github.com/casbin/casbin#Enforcer.LoadModel) | Returns an error | +| [LoadPolicy()](https://godoc.org/github.com/casbin/casbin#Enforcer.LoadPolicy) | Returns an error | +| [SavePolicy()](https://godoc.org/github.com/casbin/casbin#Enforcer.SavePolicy) | Returns an error | +| [Enforce()](https://godoc.org/github.com/casbin/casbin#Enforcer.Enforce) | Returns an error | :::note -`NewEnforcer()` calls `LoadModel()` and `LoadPolicy()` internally. So you don't have to call the latter two when using `NewEnforcer()`. +`NewEnforcer()` calls both `LoadModel()` and `LoadPolicy()` internally, so you don't need to call them separately when using `NewEnforcer()`. ::: -## Enable and disable +## Enabling and Disabling Enforcement -The enforcer can be disabled via the `Enforcer.EnableEnforce()` function. When it's disabled, `Enforcer.Enforce()` will always return `true`. Other operations like adding or removing policies are not affected. Here's an example: +You can disable the enforcer using `Enforcer.EnableEnforce()`. When disabled, `Enforcer.Enforce()` always returns `true`. Other operations like policy management remain unaffected. Example: ```go e := casbin.NewEnforcer("examples/basic_model.conf", "examples/basic_policy.csv") diff --git a/docs/MACOverview.mdx b/docs/MACOverview.mdx index 30e6ad65..6c290ec9 100644 --- a/docs/MACOverview.mdx +++ b/docs/MACOverview.mdx @@ -8,30 +8,30 @@ authors: [hsluoyz] ## Overview -Mandatory Access Control (MAC) is a type of access control where the operating system or security kernel constrains the ability of a subject to access or perform operations on an object. In MAC systems, security policies are centrally controlled and cannot be changed by individual users. +Mandatory Access Control (MAC) is an access control framework where the operating system or security kernel enforces restrictions on resource access that individual users cannot override. In MAC systems, security policies are centrally managed and applied uniformly across the system. ## MAC Models in Casbin -Casbin supports several well-known MAC security models: +Casbin implements several established MAC security models: -- **BLP (Bell-LaPadula)**: A formal state transition model focusing on confidentiality -- **Biba**: An integrity-focused model that prevents unauthorized data modification -- **LBAC (Lattice-Based Access Control)**: A formal model that can combine confidentiality and integrity controls +- **BLP (Bell-LaPadula)**: A state transition model that enforces confidentiality properties +- **Biba**: An integrity-focused model designed to prevent unauthorized data modifications +- **LBAC (Lattice-Based Access Control)**: A formal framework that can enforce both confidentiality and integrity controls -## Key Characteristics +## Core Characteristics -MAC models share several important characteristics: +MAC models share these fundamental properties: -- **Centralized Policy Management**: Security policies are defined and enforced by the system -- **Security Labels**: Objects and subjects are assigned security labels or clearance levels -- **Formal Security Properties**: Each model enforces specific security properties (e.g., no read up, no write down) +- **Centralized Policy Management**: Security policies are defined and enforced system-wide +- **Security Labels**: Both subjects and objects are assigned security clearances or classification levels +- **Formal Security Properties**: Each model implements specific security guarantees (such as "no read up" or "no write down") -## Use Cases +## Common Use Cases -MAC models are particularly useful in: +MAC models are particularly applicable in: -- Government and military systems requiring strict confidentiality -- Systems requiring strong data integrity guarantees -- Multi-level security environments +- Government and military systems that require strict information confidentiality +- Applications requiring strong data integrity protections +- Multi-level security deployments -Explore the subsections in this category to learn more about each MAC model and how to implement them in Casbin. +See the related subsections for detailed information on implementing each MAC model in Casbin. diff --git a/docs/ManagementAPI.mdx b/docs/ManagementAPI.mdx index c6ff94a4..7ec139b6 100644 --- a/docs/ManagementAPI.mdx +++ b/docs/ManagementAPI.mdx @@ -6,13 +6,11 @@ keywords: [management, Filtered API] authors: [nodece] --- - - -The primitive API that provides full support for Casbin policy management. +The Management API provides comprehensive support for Casbin policy management operations. ## Filtered API -Almost all filtered api has the same parameters ``(fieldIndex int, fieldValues ...string)``. `fieldIndex` is the index where matching start, `fieldValues` denotes the values result should have. Note that empty string in fieldValues could be any word. +Filtered API methods share a common parameter signature: `(fieldIndex int, fieldValues ...string)`. The `fieldIndex` parameter specifies the starting index for matching, while `fieldValues` contains the expected values. Empty strings in `fieldValues` act as wildcards, matching any value. Example: @@ -25,18 +23,18 @@ p, bob, pen ,get ``` ```go -e.GetFilteredPolicy(1, "book") // will return: [["alice", "book", "read"], ["bob", "book", "read"], ["bob", "book", "write"]] +e.GetFilteredPolicy(1, "book") // returns: [["alice", "book", "read"], ["bob", "book", "read"], ["bob", "book", "write"]] -e.GetFilteredPolicy(1, "book", "read") // will return: [["alice", "book", "read"], ["bob", "book", "read"]] +e.GetFilteredPolicy(1, "book", "read") // returns: [["alice", "book", "read"], ["bob", "book", "read"]] -e.GetFilteredPolicy(0, "alice", "", "read") // will return: [[alice book read]] +e.GetFilteredPolicy(0, "alice", "", "read") // returns: [[alice book read]] -e.GetFilteredPolicy(0, "alice") // will return: [["alice", "book", "read"], ["alice", "pen", "get"]] +e.GetFilteredPolicy(0, "alice") // returns: [["alice", "book", "read"], ["alice", "pen", "get"]] ``` -## Reference +## API Reference -global variable `e` is Enforcer instance. +Throughout this reference, the variable `e` represents an Enforcer instance. ```mdx-code-block