Go에서의 ABAC
역할 기반 접근 제어(RBAC)는 "에디터가 무엇을 할 수 있나요?"라는 질문에 답합니다. 많은 실제 규칙은 단순한 역할 이상을 필요로 합니다: 저자는 자신의 초안을 편집할 수 있음, 에디터는 자기 부서의 기사를 편집할 수 있음, 누구나 게시된 기사를 읽을 수 있음. 이러한 규칙은 사용자 및 리소스의 속성에 의존하며, 이것이 바로 속성 기반 접근 제어(ABAC)의 목적입니다.
이 튜토리얼에서는 표준 net/http 패키지를 사용하여 Go에서 작은 기사 API를 구축하고, 이러한 모든 규칙을 Casbin 정책 파일에 넣습니다. 동일한 모델과 정책은 이 튜토리얼의 Node.js 및 Python 버전에서도 변경 없이 작동합니다. RBAC와 ABAC 사이에서 아직 선택하지 못했다면 먼저 접근 제어 모델 선택하기를 읽어보세요.
1. 설치
http.ServeMux의 메서드 및 와일드카드 패턴을 사용하려면 Go 1.22 이상이 필요합니다.
go mod init example.com/abac
go get github.com/casbin/casbin/v3
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는 문자열이 아니라 Go 구조체입니다. 매처(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
각 줄을 "조건이 참일 때 기사에 대한 이 작업을 허용"으로 해석하세요:
- 누구나 게시된 기사를 읽을 수 있습니다.
- 저자는 초안을 포함하여 자신의 기사를 읽을 수 있습니다.
- 저자는 초안 상태인 동안 자신의 기사를 편집할 수 있습니다.
- 에디터는 자기 부서의 모든 기사를 편집할 수 있습니다.
- 에디터는 자기 부서의 기사를 게시할 수 있습니다.
조건 내의 문자열 리터럴은 'published'처럼 따옴표(single quotes)로 작성하세요. 필드 중간에 이중 따옴표(double quote)가 있으면 CSV 파싱이 깨집니다. 조건에 쉼표(comma)가 필요한 경우 전체 필드를 이중 따옴표로 감싸세요.
4. 서버 작성
ABAC는 URL뿐만 아니라 리소스 자체를 필요로 하므로, 체크는 기사가 로드된 후에 실행됩니다. authorize 헬퍼가 이를 수행하며, 응답이 '아니요'일 때 오류 응답을 작성합니다.
package main
import (
"encoding/json"
"log"
"net/http"
"sync"
"github.com/casbin/casbin/v3"
)
type User struct {
Name string
Role string
Department string
}
type Article struct {
ID string `json:"id"`
Type string `json:"-"`
Title string `json:"title"`
Owner string `json:"owner"`
Department string `json:"department"`
Status string `json:"status"`
}
// In a real application these come from your database.
var users = map[string]User{
"alice": {Name: "alice", Role: "author", Department: "engineering"},
"bob": {Name: "bob", Role: "editor", Department: "engineering"},
"carol": {Name: "carol", Role: "editor", Department: "sales"},
"dave": {Name: "dave", Role: "author", Department: "engineering"},
}
var (
mu sync.Mutex
articles = map[string]*Article{
"1": {ID: "1", Type: "article", Title: "Draft by alice", Owner: "alice", Department: "engineering", Status: "draft"},
"2": {ID: "2", Type: "article", Title: "Published by alice", Owner: "alice", Department: "engineering", Status: "published"},
}
)
type server struct {
e *casbin.Enforcer
}
// authorize loads the current user and asks Casbin whether they may perform act on the article.
func (s *server) authorize(w http.ResponseWriter, r *http.Request, a *Article, act string) bool {
// Replace this with the user from your session or JWT.
user, ok := users[r.Header.Get("X-User")]
if !ok {
http.Error(w, "unauthenticated", http.StatusUnauthorized)
return false
}
allowed, err := s.e.Enforce(user, *a, act)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return false
}
if !allowed {
http.Error(w, "forbidden", http.StatusForbidden)
return false
}
return true
}
func (s *server) article(w http.ResponseWriter, r *http.Request) *Article {
mu.Lock()
defer mu.Unlock()
a, ok := articles[r.PathValue("id")]
if !ok {
http.NotFound(w, r)
return nil
}
return a
}
func main() {
e, err := casbin.NewEnforcer("model.conf", "policy.csv")
if err != nil {
log.Fatal(err)
}
s := &server{e: e}
mux := http.NewServeMux()
mux.HandleFunc("GET /articles/{id}", func(w http.ResponseWriter, r *http.Request) {
a := s.article(w, r)
if a == nil || !s.authorize(w, r, a, "read") {
return
}
json.NewEncoder(w).Encode(a)
})
mux.HandleFunc("PUT /articles/{id}", func(w http.ResponseWriter, r *http.Request) {
a := s.article(w, r)
if a == nil || !s.authorize(w, r, a, "update") {
return
}
mu.Lock()
json.NewDecoder(r.Body).Decode(&struct {
Title *string `json:"title"`
}{&a.Title})
mu.Unlock()
json.NewEncoder(w).Encode(a)
})
mux.HandleFunc("POST /articles/{id}/publish", func(w http.ResponseWriter, r *http.Request) {
a := s.article(w, r)
if a == nil || !s.authorize(w, r, a, "publish") {
return
}
mu.Lock()
a.Status = "published"
mu.Unlock()
json.NewEncoder(w).Encode(a)
})
log.Fatal(http.ListenAndServe(":8080", mux))
}
Casbin은 리플렉션을 통해 구조체 필드를 읽으므로, 정책에서 사용되는 필드(Name, Owner, Status 등)는 반드시 export되어 있어야 합니다.
X-User 헤더는 예제를 간결하게 유지하기 위한 것입니다. Casbin은 인가(authorization)만 처리하며, 실제 애플리케이션에서는 인증된 JWT나 세션과 같은 인증 레이어에서 사용자가 제공됩니다.
5. 시도해 보기
go run .
기사 1은 alice의 초안이며, 기사 2는 그녀의 게시된 기사로 둘 다 엔지니어링 부서에 속합니다.
curl -i -H "X-User: dave" http://localhost:8080/articles/1 # 403, someone else's draft
curl -i -H "X-User: dave" http://localhost:8080/articles/2 # 200, published
curl -i -X PUT -H "X-User: alice" -d '{"title":"New title"}' \
http://localhost:8080/articles/1 # 200, her own draft
curl -i -X PUT -H "X-User: alice" -d '{"title":"x"}' \
http://localhost:8080/articles/2 # 403, no longer a draft
curl -i -X PUT -H "X-User: bob" -d '{"title":"x"}' \
http://localhost:8080/articles/2 # 200, editor in engineering
curl -i -X PUT -H "X-User: carol" -d '{"title":"x"}' \
http://localhost:8080/articles/2 # 403, editor in sales
curl -i -X POST -H "X-User: alice" http://localhost:8080/articles/1/publish # 403, authors cannot publish
curl -i -X POST -H "X-User: bob" http://localhost:8080/articles/1/publish # 200
curl -i -H "X-User: dave" http://localhost:8080/articles/1 # 200, now published
6. 런타임에 규칙 변경
조건은 정책 행이므로 서버가 실행 중일 때 추가하거나 제거할 수 있으며, 어댑터를 통해 데이터베이스에 저장할 수 있습니다:
// Admins may edit any article.
e.AddPolicy("r.sub.Role == 'admin'", "article", "update")
// Nobody may publish any more.
e.RemoveFilteredPolicy(1, "article", "publish")
어떤 규칙이 요청을 허용했는지 확인하려면 EnforceEx를 사용하세요. 이는 일치하는 규칙을 반환하며 감사 로그(audit logs)에 유용합니다:
ok, rule, _ := e.EnforceEx(users["bob"], *articles["2"], "update")
// true [r.sub.Role == 'editor' && r.sub.Department == r.obj.Department article update]
ABAC 또는 RBAC?
- 권한이 직무 기능에 따라 결정되고 접근 중인 특정 레코드에 의존하지 않는 경우 RBAC를 사용하세요. 감사(audit)가 더 쉽습니다: "편집자가 할 수 있는 모든 작업 나열하기"는 간단한 쿼리입니다. Go에서의 RBAC 튜토리얼을 참조하세요.
- 해답이 레코드 자체(소유자, 부서, 상태 또는 민감도 등)에 따라 달라지는 경우 ABAC를 사용하세요.
- 대부분의 애플리케이션은 두 모델을 모두 조합하여 사용합니다. 역할은 사용자가 접근할 수 있는 기능을 결정하고, 속성은 해당 기능이 적용될 수 있는 레코드로 범위를 좁힙니다. 접근 제어 모델 비교에서 결합된 모델을 확인할 수 있습니다.
다음 단계
- 전체 ABAC 참고 자료. ABAC에서는 JSON 요청 매개변수, 인용 규칙 및
eval()을 자세히 다룹니다. - 시간 및 장소 관련 규칙. 추가 요청 필드를 포함하세요. 예를 들어
ipMatch로 확인하는 IP 주소나 속성으로 전달되는 현재 시간 등이 있습니다. 함수를 참조하세요. - 거부(Deny) 규칙.
eft열을 추가하고 deny-override 효과를 사용하여 하나의 규칙이 다른 규칙들이 허용하는 것을 차단하도록 할 수 있습니다. Effector를 참조하세요. - 브라우저에서 실험하기. 온라인 에디터는 JSON 속성을 사용하여 ABAC 요청을 평가할 수 있습니다.
Comments are powered by giscus and GitHub Discussions. They load from giscus.app and GitHub only after you click the button below.