본문으로 건너뛰기

Express를 사용한 Node.js의 ABAC

역할 기반 접근 제어(RBAC)는 "편집자가 무엇을 할 수 있는가?"에 대한 답변을 제공합니다. 많은 실제 규칙은 역할 이상의 정보가 필요합니다: 저자는 자신의 초안을 편집할 수 있음, 편집자는 자신의 부서의 기사를 편집할 수 있음, 누구나 게시된 기사를 읽을 수 있음. 이러한 규칙은 사용자와 리소스의 속성에 의존하며, 이것이 바로 속성 기반 접근 제어(ABAC)의 목적입니다.

이 튜토리얼에서는 Express를 사용하여 작은 기사 API를 구축하고 이러한 모든 규칙을 Casbin 정책 파일에 정의합니다. 동일한 모델과 정책은 이 튜토리얼의 Go 및 Python 버전에서도 변경 없이 작동합니다. RBAC와 ABAC 중 어떤 것을 선택할지 고민 중이라면 먼저 접근 제어 모델 선택하기를 읽어보세요.

1. 설치​

npm install casbin express

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는 일반 JavaScript 객체입니다. 매처(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

각 줄을 "조건이 참일 때 기사에 대해 이 작업을 허용함"으로 해석하세요:

  1. 누구나 게시된 기사를 읽을 수 있습니다.
  2. 저자는 초안을 포함한 자신의 기사를 읽을 수 있습니다.
  3. 저자는 기사가 초안 상태일 때 자신의 기사를 편집할 수 있습니다.
  4. 편집자는 자신의 부서의 모든 기사를 편집할 수 있습니다.
  5. 편집자는 자신의 부서의 기사를 게시할 수 있습니다.
팁

조건 내에서 문자열 리터럴은 'published'처럼 작은따옴표를 사용하여 작성하세요. 필드 중간에 큰따옴표가 있으면 CSV 파싱이 깨집니다. 조건에 쉼표가 필요한 경우 전체 필드를 큰따옴표로 감싸세요.

4. 미들웨어 추가​

ABAC는 URL만이 아니라 리소스 자체가 필요합니다. authorize 미들웨어는 기사를 로드하고, Casbin에 문의한 후, 라우트 핸들러가 다시 로드하지 않도록 req에 기사를 넣습니다.

app.js
const express = require('express');
const { newEnforcer } = require('casbin');

// In a real application these come from your database.
const users = {
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' },
};

const articles = {
1: { Type: 'article', Id: '1', Title: 'Draft by alice', Owner: 'alice', Department: 'engineering', Status: 'draft' },
2: { Type: 'article', Id: '2', Title: 'Published by alice', Owner: 'alice', Department: 'engineering', Status: 'published' },
};

// Loads the article, then asks Casbin whether the current user may perform `action` on it.
function authorize(enforcer, action) {
return async (req, res, next) => {
// Replace this with the user from your session or JWT.
const user = users[req.get('X-User')];
if (!user) {
return res.status(401).json({ error: 'unauthenticated' });
}
const article = articles[req.params.id];
if (!article) {
return res.status(404).json({ error: 'not found' });
}
if (!(await enforcer.enforce(user, article, action))) {
return res.status(403).json({ error: 'forbidden' });
}
req.article = article;
next();
};
}

async function main() {
const enforcer = await newEnforcer('model.conf', 'policy.csv');

const app = express();
app.use(express.json());

app.get('/articles/:id', authorize(enforcer, 'read'), (req, res) => {
res.json(req.article);
});
app.put('/articles/:id', authorize(enforcer, 'update'), (req, res) => {
req.article.Title = req.body?.title ?? req.article.Title;
res.json(req.article);
});
app.post('/articles/:id/publish', authorize(enforcer, 'publish'), (req, res) => {
req.article.Status = 'published';
res.json(req.article);
});

app.listen(3000, () => console.log('listening on http://localhost:3000'));
}

main();
노트

X-User 헤더는 예제를 간결하게 유지하기 위해 사용됩니다. Casbin은 인가만 처리하며, 실제 애플리케이션에서는 검증된 JWT나 세션과 같은 인증 계층에서 사용자가 제공됩니다.

5. 테스트해 보기​

node app.js

기사 1은 alice의 초안이며, 기사 2는 her의 게시된 기사이고, 둘 다 engineering 부서에 속합니다.

curl -i -H "X-User: dave" http://localhost:3000/articles/1 # 403, someone else's draft
curl -i -H "X-User: dave" http://localhost:3000/articles/2 # 200, published
curl -i -X PUT -H "X-User: alice" -H "Content-Type: application/json" \
-d '{"title":"New title"}' http://localhost:3000/articles/1 # 200, her own draft
curl -i -X PUT -H "X-User: alice" http://localhost:3000/articles/2 # 403, no longer a draft
curl -i -X PUT -H "X-User: bob" http://localhost:3000/articles/2 # 200, editor in engineering
curl -i -X PUT -H "X-User: carol" http://localhost:3000/articles/2 # 403, editor in sales
curl -i -X POST -H "X-User: alice" http://localhost:3000/articles/1/publish # 403, authors cannot publish
curl -i -X POST -H "X-User: bob" http://localhost:3000/articles/1/publish # 200
curl -i -H "X-User: dave" http://localhost:3000/articles/1 # 200, now published

6. 런타임에 규칙 변경​

조건(condition)은 정책(policy) 행이므로 서버 실행 중에 추가하거나 삭제할 수 있으며, 어댑터를 통해 데이터베이스에 저장할 수 있습니다:

// Admins may edit any article.
await enforcer.addPolicy("r.sub.Role == 'admin'", 'article', 'update');

// Which rule allowed this request? Useful for audit logs.
const [ok, rule] = await enforcer.enforceEx(users.bob, articles[2], 'update');
// true [ "r.sub.Role == 'editor' && r.sub.Department == r.obj.Department", 'article', 'update' ]

ABAC 또는 RBAC?​

  • 권한이 직무 기능(job function)을 따르며 접근 중인 특정 레코드에 의존하지 않는 경우 RBAC를 사용하세요. 감사(audit)가 더 쉽습니다: "편집자가 할 수 있는 모든 작업 나열하기"는 단순한 쿼리로 가능합니다. Node.js RBAC 튜토리얼을 참조하세요.
  • 결과가 레코드(소유자, 부서, 상태 또는 민감도 등)에 따라 달라지는 경우 ABAC를 사용하세요.
  • 대부분의 애플리케이션은 두 모델을 모두 결합합니다: 역할(role)은 사용자가 도달할 수 있는 기능을 결정하고, 속성(attribute)은 사용자가 건드릴 수 있는 레코드로 범위를 좁힙니다. 접근 제어 모델 비교에서 결합된 모델을 확인할 수 있습니다.

다음 단계​

  • 전체 ABAC 참고 자료. ABAC에서는 JSON 요청 매개변수, 따옴표 규칙 및 eval()을 자세히 다룹니다.
  • NestJS. NestJS 튜토리얼에서는 가드(guard)와 데코레이터(decorator)를 보여주며, 동일한 ABAC 모델로 확장할 수 있습니다.
  • 브라우저에서 권한 확인. Casbin.js는 동일한 규칙을 사용하여 프론트엔드의 버튼을 표시하거나 숨깁니다.
  • 브라우저에서 실험. 온라인 에디터는 JSON 속성을 사용하여 ABAC 요청을 평가할 수 있습니다.

Comments are powered by giscus and GitHub Discussions. They load from giscus.app and GitHub only after you click the button below.