Flask로 Python에서 ABAC 구현
역할 기반 접근 제어(RBAC)는 "편집자는 무엇을 할 수 있는가?"에 대한 답을 제공합니다. 그러나 실제 규칙에는 역할 이상의 정보가 필요한 경 우가 많습니다. 예를 들어 저자는 자신의 초안을 편집할 수 있음, 편집자는 자신의 부서에 속한 기사를 편집할 수 있음, 누구나 게시된 기사를 읽을 수 있음 등의 규칙은 사용자 및 리소스의 속성에 의존하며, 이것이 바로 속성 기반 접근 제어(ABAC)의 목적입니다.
이 튜토리얼에서는 Flask를 사용하여 작은 기사 API를 구축하고 모든 규칙을 Casbin 정책 파일에 포함합니다. 동일한 모델과 정책은 이 튜토리얼의 Go 및 Node.js 버전에서도 변경 없이 작동합니다. Python에서의 역할 기반 규칙은 FastAPI RBAC 튜토리얼을 참조하세요. RBAC와 ABAC 중 선택이 어렵다면 먼저 접근 제어 모델 선택하기를 읽어보시기 바랍니다.
1. 설치
pip install pycasbin flask
2. 모델 작성
다음 내용을 model.conf로 저장하십시오:
[request_definition]
r = sub, obj, act
[policy_definition]
p = sub_rule, obj_type, act
[policy_effect]
e = some(where (p.eft == allow))
[matchers]
m = r.obj.Type == p.obj_type && r.act == p.act && eval(p.sub_rule)
r.sub와r.obj는 Python 객체입니다. 매처(matcher)는r.obj.Type과 같은 속성을 읽습니다.- 각 정책 규칙은
sub_rule에 조건을 포함합니다.eval(p.sub_rule)은 요청에 대해 해당 조건을 평가하므로, 규칙이 모델 대신 정책에 존재하게 됩니다.
3. 정책 작성
다음 내용을 policy.csv로 저장하십시오:
p, r.obj.Status == 'published', article, read
p, r.sub.Name == r.obj.Owner, article, read
p, r.sub.Name == r.obj.Owner && r.obj.Status == 'draft', article, update
p, r.sub.Role == 'editor' && r.sub.Department == r.obj.Department, article, update
p, r.sub.Role == 'editor' && r.sub.Department == r.obj.Department, article, publish
각 줄은 "조건이 참일 때 기사에 대해 이 작업을 허용한다"는 의미로 읽으십시오:
- 누구나 게시된 기사를 읽을 수 있습니다.
- 저자는 초안을 포함한 자신의 기사를 읽을 수 있습니다.
- 저자는 기사가 초안인 동안 자신의 기사를 편집할 수 있습니다.
- 편집자는 자신의 부서에 속한 모든 기사를 편집할 수 있습니다.
- 편집자는 자신의 부서에 속한 기사를 게시할 수 있습니다.
조건은 모든 Casbin 구현에서 동일한 구문을 사용하며, PyCasbin은 &&와 ||를 Python의 and와 or로 변환합니다.
조건 내의 문자열 리터럴은 'published'처럼 큰따옴표 대신 작은따옴표를 사용하여 작성하십시오. 필드 중간에 큰따옴표가 있으면 CSV 파싱이 깨집니다. 조건에 쉼표가 필요한 경우 전체 필드를 큰따옴표로 감싸십시오.
4. 애플리케이션 작성
ABAC는 URL뿐만 아니라 리소스 자체를 필요로 하므로, 확인(check)은 기사가 로드된 후 실행됩니다. authorize 헬퍼는 기사를 로드하고 Casbin에 문의한 후, 결과가 '아니요(no)'일 경우 적절한 상태 코드로 중단(abort)합니다. 각 뷰(view)는 이를 먼저 호출합니다.
from dataclasses import asdict, dataclass
import casbin
from flask import Flask, abort, request
enforcer = casbin.Enforcer("model.conf", "policy.csv")
app = Flask(__name__)
@dataclass
class User:
Name: str
Role: str
Department: str
@dataclass
class Article:
Id: str
Title: str
Owner: str
Department: str
Status: str
Type: str = "article"
# In a real application these come from your database.
users = {
"alice": User("alice", "author", "engineering"),
"bob": User("bob", "editor", "engineering"),
"carol": User("carol", "editor", "sales"),
"dave": User("dave", "author", "engineering"),
}
articles = {
"1": Article("1", "Draft by alice", "alice", "engineering", "draft"),
"2": Article("2", "Published by alice", "alice", "engineering", "published"),
}
def authorize(article_id: str, action: str) -> Article:
"""Load the article and abort unless the current user may perform the action on it."""
# Replace this with the user from your session or JWT.
user = users.get(request.headers.get("X-User", ""))
if user is None:
abort(401)
article = articles.get(article_id)
if article is None:
abort(404)
if not enforcer.enforce(user, article, action):
abort(403)
return article
@app.get("/articles/<article_id>")
def read_article(article_id):
return asdict(authorize(article_id, "read"))
@app.put("/articles/<article_id>")
def update_article(article_id):
article = authorize(article_id, "update")
article.Title = (request.get_json(silent=True) or {}).get("title", article.Title)
return asdict(article)
@app.post("/articles/<article_id>/publish")
def publish_article(article_id):
article = authorize(article_id, "publish")
article.Status = "published"
return asdict(article)
데이터 클래스(dataclass)는 예제를 간결하게 유지하기 위해 사용됩니다. 정책에서 지정된 속성이 존재한다면 SQLAlchemy 또는 Django 모델 등 어떤 객체든 사용할 수 있습니다.
X-User 헤더는 예제를 간결하게 유지하기 위한 것입니다. Casbin은 인가(authorization)만 처리합니다. 실제 애플리케이션에서는 사용자가 Flask-Login이나 검증된 JWT와 같은 인증 레이어에서 제공됩니다.
5. 테스트
flask --app app run --port 5000
기사 1은 alice의 초안이며, 기사 2는 그녀의 게시된 기사로 둘 다 엔지니어링 부서에 속합니다.
curl -i -H "X-User: dave" http://localhost:5000/articles/1 # 403, someone else's draft
curl -i -H "X-User: dave" http://localhost:5000/articles/2 # 200, published
curl -i -X PUT -H "X-User: alice" -H "Content-Type: application/json" -d '{"title":"New title"}' http://localhost:5000/articles/1 # 200, her own draft
curl -i -X PUT -H "X-User: alice" http://localhost:5000/articles/2 # 403, no longer a draft
curl -i -X PUT -H "X-User: bob" http://localhost:5000/articles/2 # 200, editor in engineering
curl -i -X PUT -H "X-User: carol" http://localhost:5000/articles/2 # 403, editor in sales
curl -i -X POST -H "X-User: alice" http://localhost:5000/articles/1/publish # 403, authors cannot publish
curl -i -X POST -H "X-User: bob" http://localhost:5000/articles/1/publish # 200
curl -i -H "X-User: dave" http://localhost:5000/articles/1 # 200, now published
6. 런타임에 규칙 변경
조건은 정책 행이므로 서버가 실행 중일 때 추가하거나 제거할 수 있으며, SQLAlchemy 어댑터와 같은 어댑터를 통해 데이터베이스에 저장할 수 있습니다:
# Admins may edit any article.
enforcer.add_policy("r.sub.Role == 'admin'", "article", "update")
# Which rule allowed this request? Useful for audit logs.
enforcer.enforce_ex(users["bob"], articles["2"], "update")
# (True, ["r.sub.Role == 'editor' && r.sub.Department == r.obj.Department", 'article', 'update'])
ABAC 또는 RBAC?
- 권한이 직무 기능에 따라 결정되고 접근 중인 레코드에 의존하지 않는 경우 RBAC을 사용하세요. 감사(audit)가 더 쉽습니다: "에디터가 할 수 있는 모든 목록"은 간단한 쿼리입니다. Python용 RBAC 튜토리얼을 참조하세요.
- 해답이 레코드(소유자, 부서, 상태 또는 민감도 등)에 따라 달라지는 경우 ABAC을 사용하세요.
- 대부분의 애플리케이션은 두 가지를 모두 조합합니다: 역할은 사용자가 접근할 수 있는 기능을 결정하고, 속성은 해당 기능을 사용자가 건드릴 수 있는 레코드로 좁혀줍니다. 접근 제어 모델 비교에서 결합된 모델을 확인할 수 있습니다.
Comments are powered by giscus and GitHub Discussions. They load from giscus.app and GitHub only after you click the button below.