Перейти к основному контенту

Casbin in 2025: Authorization for the AI Agent Era

· 5 мин прочитано

2024 was the year AI agents went from demos to production. With the Model Context Protocol (MCP) gaining adoption from Google, OpenAI, Microsoft, and countless others, we're seeing a fundamental shift in how applications interact with external services. And with that shift comes a whole new set of authorization challenges that we at Casbin have been thinking about.

Understanding How Casbin Matching Works in Detail

· 8 мин прочитано

In this post, I will explain the design and implementation of RBAC using the Casbin library. For a SaaS platform dealing with multiple resource hierarchies and roles that inherit permissions from higher levels, Casbin provides a performant alternative to consider.

Introduction to RBAC

RBAC is a method of restricting access to resources based on the roles that individuals hold. To better understand how hierarchical RBAC works, let's take a look at Azure's RBAC system in the next section and then attempt to implement a similar system.

Understanding Azure's Hierarchical RBAC

Azure Hierarchy

There is a role called Owner for all resources in Azure. Suppose if I have the Owner role assigned to me at the subscription level, that means I am the Owner of all the resource groups and resources under that subscription. If I have Owner at the resource group level, then I am the Owner of all the resources under that resource group.

This image shows that I have Owner access at the subscription level. Subscription Owner

When I check the IAM of a Resource Group under this Subscription, you can see that I have inherited Owner access from the subscription. RG Owner

So, this is how Azure's RBAC is hierarchical. Most enterprise software uses hierarchical RBAC because of the hierarchical nature of the resource levels. In this tutorial, we'll try to implement a similar system using Casbin.

How Does Casbin Work?

Before diving into the implementation, it is important to understand what Casbin is and how it functions at a high level. This understanding is necessary because each Role-Based Access Control (RBAC) system may vary based on specific requirements. By grasping the workings of Casbin, we can effectively fine-tune the model.

What is ACL?

ACL stands for Access Control List. It is a method in which users are mapped to actions and actions to resources.

The model definition

Let's consider a simple example of an ACL model.

[request_definition]
r = sub, act, obj

[policy_definition]
p = sub, act, obj

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

[matchers]
m = r.sub == p.sub && r.obj == p.obj && r.act == p.act
  1. The request_definition is the query template of the system. For example, a request alice, write, data1 can be interpreted as "Can subject Alice perform the action 'write' on object 'data1'?".

  2. The policy_definition is the assignment template of the system. For example, by creating a policy alice, write, data1, you are assigning permission to subject Alice to perform the action 'write' on object 'data1'.

  3. The policy_effect defines the effect of the policy.

  4. In the matchers section, the request is matched with the policy using the conditions r.sub == p.sub && r.obj == p.obj && r.act == p.act.

Now let's test the model on the Casbin editor

Open the editor and paste the above model in the Model editor.

Paste the following in the Policy editor:

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

and the following in the Request editor:

alice, read, data1

The result will be:

true

Visual representation of the ACL model, policy, and request matching

acl

What is RBAC?

RBAC stands for Role-Based Access Control. In RBAC, a user is assigned a role for a resource, and a role can contain arbitrary actions. The request then checks if the user has the permission to perform the action on the resource.

The model definition

Let's consider a simple example RBAC model:

[request_definition]
r = sub, act, obj

[policy_definition]
p = sub, act, obj

[role_definition]
g = _, _
g2 = _, _

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

[matchers]
m = r.sub == p.sub && g(p.act, r.act) && r.obj == p.obj
  1. The role_definition is a graph relation builder that uses a Graph to compare the request object with the policy object.

Now let's test the model on Casbin editor

Open the editor and paste the above model in the Model editor.

Paste the following in the Policy editor:

p, alice, reader, data1
p, bob, owner, data2

g, reader, read
g, owner, read
g, owner, write

and the following in the Request editor:

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

The result will be:

true
false
true
true
false

Visual representation of the RBAC model, policy, and request matching

rbac

The g - Role to action mapping table has a Graph mapping the role to action. This Graph can be coded as a list of edges, as shown in the policy which is a common way of representing a Graph:

g, reader, read
g, owner, read
g, owner, write
инфо

p indicates a normal policy that can be compared using the == operator. g is a Graph-based comparison function. You can define multiple Graph comparators by adding a numerical suffix like g, g2, g3, ... and so on.

What is Hierarchical RBAC?

In Hierarchical RBAC, there are more than one type of resources and there is an inheritance relationship between the resource types. For example, "subscription" is one type and "resourceGroup" is another type. A sub1 of type Subscription can contain multiple resourceGroups (rg1, rg2) of type ResourceGroup.

Similar to the resource hierarchy, there will be two types of roles and actions: Subscription roles and actions, and ResourceGroup roles and actions. There is an arbitrary relationship between the Subscription role and ResourceGroup role. For example, consider a Subscription Role sub-owner. This role is inherited by a ResourceGroup Role rg-owner, which means that if I am assigned the sub-owner role on Subscription sub1, then I automatically also get the rg-owner role on rg1 and rg2.

The model definition

Let's take a simple example of the Hierarchical RBAC model:

[request_definition]
r = sub, act, obj

[policy_definition]
p = sub, act, obj

[role_definition]
g = _, _
g2 = _, _

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

[matchers]
m = r.sub == p.sub && g(p.act, r.act) && g2(p.obj, r.obj)
  1. The role_definition is a graph relation builder which uses a Graph to compare the request object with the policy object.

Now let's test the model on the Casbin editor

Open the editor and paste the above model in the Model editor.

Paste the following in the Policy editor:

p, alice, sub-reader, sub1
p, bob, rg-owner, rg2

// subscription role to subscription action mapping
g, sub-reader, sub-read
g, sub-owner, sub-read
g, sub-owner, sub-write

// resourceGroup role to resourceGroup action mapping
g, rg-reader, rg-read
g, rg-owner, rg-read
g, rg-owner, rg-write

// subscription role to resourceGroup role mapping
g, sub-reader, rg-reader
g, sub-owner, rg-owner

// subscription resource to resourceGroup resource mapping
g2, sub1, rg1
g2, sub2, rg2

And paste the following in the Request editor:

alice, rg-read, rg1

The result will be:

true

Visual representation of the RBAC model, policy, and request matching

hrbac

The g - Role to (Action, Role) Mapping table has a graph mapping the role to the action, role mapping. This graph can be coded as a list of edges, as shown in the policy, which is a common way of representing a graph:

// subscription role to subscription action mapping
g, sub-reader, sub-read
g, sub-owner, sub-read
g, sub-owner, sub-write

// resourceGroup role to resourceGroup action mapping
g, rg-reader, rg-read
g, rg-owner, rg-read
g, rg-owner, rg-write

// subscription role to resourceGroup role mapping
g, sub-reader, rg-reader
g, sub-owner, rg-owner

The g2 - Sub to RG Mapping table has a graph mapping subscription to resourceGroup:

// subscription resource to resourceGroup resource mapping
g2, sub1, rg1
g2, sub2, rg2

Subject Matching Visual representation

hrbac-sub-match

Action Matching Visual representation

hrbac-act-match

Object Matching Visual representation

hrbac-obj-match

инфо

When a request is submitted to Casbin, this matching happens for all the policies. If at least one policy matches, then the result of the request is true. If no policy matches the request, then the result is false.

Conclusion

In this tutorial, we learned about how different authorization models work and how they can be modeled using Casbin. In the second part of this tutorial, we will implement this in a demo Spring Boot Application and secure the APIs using Casbin.

Авторизация в APISIX с использованием Casbin

· 6 мин прочитано
Rushikesh Tote
Член Касбина

Введение

APISIX это высокая производительность и масштабируемый облачный шлюз API, основанный на Nginx и т.д.. Это проект с открытым исходным кодом от Apache Software Foundation. Кроме того, что делает APISIX настолько хорошим является поддержка многих больших встроенных плагинов, которые могли бы быть использованы для реализации функций, таких как аутентификация, мониторинг, маршрутизация и т.д. И тот факт, что плагины в APISIX перезагружены (без перезагрузки) делает это очень динамичным.

Но при использовании APISIX могут быть сценарии, где вы можете добавить сложную логику авторизации в вашем приложении. Вот где authz-casbin может вам помочь, authz-casbin - это APISIX плагин, основанный на Lua Casbin , который обеспечивает мощную авторизацию на основе различных моделей управления доступом. Casbin - это библиотека авторизации, поддерживающая такие модели управления доступом, как ACL, RBAC, ABAC. Первоначально написано в Го, он был портирован на многие языки, а Луа Касбин является Луа реализации Casbin. Разработка authz-casbin началась, когда мы предложили новый плагин для авторизации в хранилище APISIX (#4674), с которым согласились основные участники. А после полезных отзывов, которые привели к значительным изменениям и улучшениям, PR (#4710) наконец был объединен.

В этом блоге, мы будем использовать плагин authz-casbin для того, чтобы показать, как можно реализовать модель авторизации на основе контроля доступа на основе ролей (RBAC) в APISIX.

ПРИМЕЧАНИЕ: Вам нужно будет использовать некоторые другие плагины или пользовательский рабочий процесс для аутентификации пользователя, поскольку Касбин будет делать авторизацию только и не аутентификацию.

Создание модели

Плагин использует три параметра для авторизации любого запроса - тема, объект и действие. Здесь тема является значением заголовка имени пользователя, который может быть что-то вроде [username: alice]. Затем объект - это путь к URL, к которому он доступен, и используется метод запроса запроса.

Скажем, мы хотим создать модель с тремя ресурсами на путях - /, /res1 и /res2. И мы хотим иметь такую модель:

изображение

Это означает, что все пользователи (*), например Джек могут получить доступ к домашней странице (/). А пользователи с правами администратора , такими как alice и bob могут получить доступ ко всем страницам и ресурсам (например, res1 и res2). Кроме того, давайте ограничим пользователей без прав администратора использовать только GET метод запроса. Для этого сценария мы можем определить модель:

[request_definition]
r = sub, obj, действовать

[policy_definition]
p = sub, obj, act

[role_definition]
g = _, _

[policy_effect]
e = где-то (стр. ft == allow))

[matchers]
м = (g(r.sub, p.sub) || keyMatch(r.sub, p. ub)) && keyMatch(r.obj, p.obj) && keyMatch(r.act, p.act)

Создание политики

В соответствии с вышеупомянутым сценарием политика будет заключаться в следующем:

p, *, /, GET
p, admin, *, *
g, alice, admin
g, bob, admin

Матчер из модели означает:

  1. (g(r.sub, p.sub) || keyMatch(r.sub, p. ub)): Тема запроса имеет роль в качестве темы политики или тема запроса совпадает с темой политики keyMatch. keyMatch построен в функции Lua Casbin, вы можете посмотреть описание функции и другие функции, которые могут быть полезны здесь.
  2. keyMatch(r.obj, p.obj): Объект запроса соответствует объекту политики (путь к URL здесь).
  3. keyMatch(r.act, p.act): Действие запроса соответствует действию политики (метод HTTP запроса здесь).

Включение плагина на маршрут

Создав модель и политику, вы можете включить ее на маршруте с помощью APISIX Admin API. Чтобы включить его, используя пути файлов моделей и политики:

curl http://127.0.0. :9080/apisix/admin/routes/1 -H 'X-API-KEY: edd1c9f034335f136f87ad84b625c8f1' -X PUT -d '
{
"plugins": {
"authz-casbin": {
"model_path": "/path/to/model. onf",
"policy_path": "/path/to/policy. sv",
"username": "username"
}
},
"upstream": {
"nodes": {
"127. .0.1:1980": 1
},
"type": "roundrobin"
},
"uri": "/*"
}'

Здесь имя пользователя - это имя заголовка, которое вы будете использовать для передачи в теме. Например, если вы будете передавать заголовок имени пользователя как пользователя: alice, вы бы использовали "username": "user".

Для использования текста модели/политики вместо файлов можно использовать модель и политику поля:

curl http://127.0.0. :9080/apisix/admin/routes/1 -H 'X-API-KEY: edd1c9f034335f136f87ad84b625c8f1' -X PUT -d '
{
"plugins": {
"authz-casbin": {
"model": "[request_definition]
r = sub, obj, act

[policy_definition]
p = sub, obj, действовать

[role_definition]
g = _, _

[policy_effect]
e = где-то (стр. f== допустить))

[matchers]
м = (g(r. ub, p. ub) || keyMatch(r.sub, p.sub)) && keyMatch(r.obj, p.obj) && keyMatch(r.act, p. ct)",

"policy": "p, *, /, GET
p, admin, *, *
g, угла, администратора
g, bob, администратор",

"Имя пользователя": "Имя пользователя"
}
},
"upstream": {
"nodes": {
"127. .0.1:1980": 1
},
"type": "roundrobin"
},
"uri": "/*"
}'

Включение плагина с использованием глобальной модели/политики

Могут возникнуть ситуации, когда вы можете захотеть использовать одну модель и конфигурацию политики для нескольких маршрутов. Вы можете сделать это, отправив запрос PUT для добавления модели и конфигурации политики к метаданным плагина:

curl http://127.0.0. :9080/apisix/admin/plugin_metadata/authz-casbin -H 'X-API-KEY: edd1c9f034335f136f87ad84b625c8f1' -i -X PUT -d '
{
"model": "[request_definition]
r = sub, obj, act

[policy_definition]
p = sub, obj, act

[role_definition]
g = _, _

[policy_effect]
e = где-то (стр. ft == allow))

[matchers]
м = (g(r.sub, p.sub) || keyMatch(r. ub, p.sub)) && keyMatch(r.obj, p.obj) && keyMatch(r. ct, p.act)",

"policy": "p, *, /, GET
p, admin, *, *
g, alice, admin
g, bob, admin"
}'

Затем чтобы включить одну и ту же конфигурацию на некоторых маршрутах, отправьте запрос, используя админ-API:

curl http://127.0.0. :9080/apisix/admin/routes/1 -H 'X-API-KEY: edd1c9f034335f136f87ad84b625c8f1' -X PUT -d '
{
"plugins": {
"authz-casbin": {
"username": "username"
}
},
"upstream": {
"nodes": {
"127. .0.1:1980": 1
},
"type": "roundrobin"
},
"uri": "/route1/*"
}'

Это добавит конфигурацию метаданных плагина в маршрут. Вы также можете легко обновить конфигурацию метаданных плагина, переслав запрос к метаданным плагина с обновленной моделью и конфигурацией политики, плагин автоматически обновит все маршруты, используя метаданные плагина.

Варианты использования

  • Основным вариантом использования этого плагина будет внедрение авторизации в ваших API. Вы можете легко добавить этот плагин на любой API маршрут, который используется с вашей моделью авторизации и конфигурацией политики.
  • Если вы хотите иметь одну модель авторизации для всех ваших API, вы можете использовать глобальный метод модели/политики. Это делает обновление политики простыми для всех маршрутов, так как вам нужно обновить только метаданные в и т.д.
  • Если вы хотите использовать другую модель для каждого маршрута, вы можете использовать метод маршрута. Это полезно, когда различные маршруты API имеют различные наборы прав пользователей. Вы также можете использовать это при работе с большими правилами, так как это сделает авторизацию быстрее, если отфильтровать по нескольким маршрутам.

Ян Луо - Google Open Source Peer Bonus Победитель

· 2 мин прочитано
Casbin
Официальный счет

Сегодня мы рады сообщить, что основатель Casbin'а Yang Luo стал лауреатом премии "Google Open Source Peer Bonus winners" за работу над Casbin, Npcap и Nmap в 2019 К3.

ospb

С оригинальным письмом о награждении можно ознакомиться здесь.

Google Open Source Peer Bonus программа описывается как:

Аналогичным образом, что Google Peer Bonus используется для распознавания соотечественника Googler, который ушел выше и дальше, Бонус с открытым исходным кодом (Open Source Peer Bonus - бонус) позволяет узнать о внешних людях, внесших исключительный вклад в работу с открытым исходным кодом.

объявление для победителей 2019 года доступно по адресу:

https://opensource.googleblog.com/2020/01/announcing-2019-second-cycle-google.html

Янг и Касбин перечислены среди разработчиков с открытым исходным кодом и проектов, которые оказывают там соответствующее влияние. как Git, TensorFlow, V8, CPython, LLVM, Apache проектов, Angular или Jenkins.

Мы рады видеть, что Касбин признан таким образом за его вклад в обеспечение открытого исходного кода и безопасности облака!

Спасибо за полёт!

Переработать нашу документацию

· Один мин чтения
Yang Luo
Создатель Касбина

Сегодня мы мигрировали документацию Casbin'а из GitHub в документацию этого веб-сайта, которая основана на Docusaurus. Docusaurus предоставляет множество потрясающих возможностей, таких как лучшие стили Markdown, полнотекстовый поиск, версия, перевод.

Документация еще не идеально и все еще нуждается в настройке. Исходный код выпущен на GitHub: https://github.com/casbin/casbin-website-v2.

Любой вклад или предложение приветствуются!

node-Casbin: Новый член Casbin Family

· Один мин чтения
Zixuan Liu
Сопровождающий Casbin

Сегодня мы успешно портировали Casbin в Node.js, который называется node-Casbin.

node-Casbin разделяет аналогичное использование и API с другими реализациями Casbin. middlewares for Express, Koa2 and Egg.js готовы к использованию . Подготовлен адаптер для последовательности памяти.

Надеемся, что он будет хорошо обслуживать вашу потребность :)

GitHub: https://github.com/casbin/node-casbin

Сервер Casbin запущен!

· Один мин чтения
Хелонг Чжан
Сопровождающий Casbin

Некоторые из наших клиентов спрашивают можно ли Касбин использовать в качестве службы вместо библиотеки. Ответ ДА. Сегодня мы запустили проект Casbin Server в качестве конкретного решения для Контроля доступа в качестве Сервиса.

Casbin Server находится в активной разработке нашей основной команды. У него есть несколько особенностей:

  • Полностью развито на Голанге.
  • Можно управлять тысячами экземпляров Касбин, так что вы можете перенести логику политики из нескольких служб в один сервер Casbin.
  • gRPC используется для общения с Casbin Server. Мы также рассмотрим возможность добавления поддержки RESTful в ближайшее время.
  • Удобный администраторский портал предназначен для неразработчиков и администраторов для управления всеми деталями, такими как экземпляры касбин, модели, хранение политики и балансировка нагрузки.

Исходный код размещен на GitHub: https://github.com/casbin/casbin-server

Приветствуются любые вопросы или Pull Request'ы :)