🔒 Security

RBAC

Role-Based Access Control

A security model that grants system access permissions based on a user's Role. Instead of granting permissions directly to individual users, permissions are defined for roles (admin, editor, viewer, etc.) and roles are assigned to users. 94.7% of organizations have experience using RBAC, and 86.6% currently adopt it as their top-priority access control model.

📖 Detailed Explanation

RBAC (Role-Based Access Control) is an access control model first formalized by NIST in 1992 that manages "who can do what" on a per-role basis. The core idea is simple: grant permissions (Permission) to roles (Role), and assign roles to users (User). For example, if the "editor" role is granted create, read, and update permissions, every user with the editor role has those permissions.

RBAC emerged to overcome the limitations of the ACL (Access Control List) approach. ACLs specify permissions per user directly for each resource, so management becomes exponentially more complex as users and resources increase. RBAC solves this problem by introducing an abstraction layer called roles. When a new employee joins, you only need to assign the appropriate role, and when they leave, you only need to revoke the role.

One of the core principles of RBAC is the Principle of Least Privilege. Users should be granted only the minimum permissions necessary to perform their duties. In addition, Separation of Duties (SoD) prevents a single user from holding mutually exclusive roles at the same time. For example, the roles of purchase requester and approver cannot be held by the same person.

In modern systems, RBAC is evolving into a hybrid approach combined with ABAC (attribute-based) rather than being used alone. Basic permissions are managed with RBAC, while fine-grained conditions (time, location, data sensitivity) are controlled with ABAC. Most cloud platforms, including Kubernetes, AWS IAM, and Azure RBAC, have adopted RBAC as their default access control model, and it is also used as a core component in Zero Trust architecture.

💻 Code Example

// RBAC 구현 예제 - Node.js/Express
const express = require('express');
const app = express();

// 1. 역할-권한 매핑 정의
const ROLE_PERMISSIONS = {
    admin: ['users:create', 'users:read', 'users:update', 'users:delete',
            'posts:create', 'posts:read', 'posts:update', 'posts:delete'],
    editor: ['posts:create', 'posts:read', 'posts:update', 'users:read'],
    viewer: ['posts:read', 'users:read']
};

// 2. 사용자-역할 매핑 (실제로는 DB에서 조회)
const USER_ROLES = {
    'user_001': ['admin'],
    'user_002': ['editor'],
    'user_003': ['viewer'],
    'user_004': ['editor', 'viewer']  // 복수 역할 가능
};

// 3. 권한 확인 함수
function hasPermission(userId, permission) {
    const userRoles = USER_ROLES[userId] || [];

    // 사용자의 모든 역할에서 권한 확인
    return userRoles.some(role => {
        const permissions = ROLE_PERMISSIONS[role] || [];
        return permissions.includes(permission);
    });
}

// 4. RBAC 미들웨어
function rbac(requiredPermission) {
    return (req, res, next) => {
        const userId = req.user?.id;  // 인증 미들웨어에서 설정

        if (!userId) {
            return res.status(401).json({
                error: 'Unauthorized',
                message: '인증이 필요합니다'
            });
        }

        if (!hasPermission(userId, requiredPermission)) {
            // 감사 로그 기록
            console.log(`[RBAC DENIED] User: ${userId}, Permission: ${requiredPermission}`);

            return res.status(403).json({
                error: 'Forbidden',
                message: `'${requiredPermission}' 권한이 필요합니다`
            });
        }

        // 감사 로그 기록
        console.log(`[RBAC GRANTED] User: ${userId}, Permission: ${requiredPermission}`);
        next();
    };
}

// 5. 라우트에 RBAC 적용
app.get('/api/users', rbac('users:read'), (req, res) => {
    res.json({ users: ['user1', 'user2'] });
});

app.post('/api/users', rbac('users:create'), (req, res) => {
    res.json({ message: 'User created' });
});

app.delete('/api/users/:id', rbac('users:delete'), (req, res) => {
    res.json({ message: 'User deleted' });
});

// 6. 역할 기반 UI 렌더링용 API
app.get('/api/my-permissions', (req, res) => {
    const userId = req.user?.id;
    const userRoles = USER_ROLES[userId] || [];

    const permissions = [...new Set(
        userRoles.flatMap(role => ROLE_PERMISSIONS[role] || [])
    )];

    res.json({ roles: userRoles, permissions });
});

app.listen(3000);
# RBAC 구현 예제 - Python/Flask
from functools import wraps
from flask import Flask, request, jsonify, g
from typing import List, Set
import logging

app = Flask(__name__)
logging.basicConfig(level=logging.INFO)

# 1. 역할-권한 매핑 (계층적 RBAC)
ROLE_HIERARCHY = {
    'admin': ['editor', 'viewer'],  # admin은 editor, viewer 권한 상속
    'editor': ['viewer'],            # editor는 viewer 권한 상속
    'viewer': []
}

ROLE_PERMISSIONS = {
    'admin': {'users:create', 'users:delete', 'settings:manage'},
    'editor': {'posts:create', 'posts:update', 'posts:delete'},
    'viewer': {'posts:read', 'users:read'}
}

# 2. 계층적 권한 계산
def get_effective_permissions(roles: List[str]) -> Set[str]:
    """역할 계층을 고려한 실제 권한 계산"""
    permissions = set()

    def collect_permissions(role: str, visited: set):
        if role in visited:
            return
        visited.add(role)

        # 현재 역할의 권한 추가
        permissions.update(ROLE_PERMISSIONS.get(role, set()))

        # 상속받는 역할의 권한 추가
        for inherited_role in ROLE_HIERARCHY.get(role, []):
            collect_permissions(inherited_role, visited)

    for role in roles:
        collect_permissions(role, set())

    return permissions

# 3. RBAC 데코레이터
def require_permission(permission: str):
    def decorator(f):
        @wraps(f)
        def wrapper(*args, **kwargs):
            user_id = g.get('user_id')
            user_roles = g.get('user_roles', [])

            if not user_id:
                return jsonify({'error': 'Unauthorized'}), 401

            effective_permissions = get_effective_permissions(user_roles)

            if permission not in effective_permissions:
                logging.warning(
                    f"[RBAC DENIED] user={user_id} "
                    f"permission={permission} roles={user_roles}"
                )
                return jsonify({
                    'error': 'Forbidden',
                    'required_permission': permission
                }), 403

            logging.info(
                f"[RBAC GRANTED] user={user_id} "
                f"permission={permission}"
            )
            return f(*args, **kwargs)
        return wrapper
    return decorator

# 4. 직무 분리(SoD) 검증
MUTUALLY_EXCLUSIVE_ROLES = [
    {'purchase_requester', 'purchase_approver'},
    {'developer', 'production_deployer'}
]

def validate_sod(user_roles: List[str]) -> bool:
    """직무 분리 규칙 위반 확인"""
    role_set = set(user_roles)
    for exclusive_set in MUTUALLY_EXCLUSIVE_ROLES:
        if len(role_set & exclusive_set) > 1:
            return False
    return True

# 5. 라우트 예제
@app.route('/api/posts', methods=['GET'])
@require_permission('posts:read')
def get_posts():
    return jsonify({'posts': ['post1', 'post2']})

@app.route('/api/posts', methods=['POST'])
@require_permission('posts:create')
def create_post():
    return jsonify({'message': 'Post created'})

@app.route('/api/users', methods=['DELETE'])
@require_permission('users:delete')
def delete_user():
    return jsonify({'message': 'User deleted'})

# 6. 역할 할당 API (관리자 전용)
@app.route('/api/roles/assign', methods=['POST'])
@require_permission('settings:manage')
def assign_role():
    data = request.json
    user_id = data.get('user_id')
    new_roles = data.get('roles', [])

    # 직무 분리 검증
    if not validate_sod(new_roles):
        return jsonify({
            'error': 'SoD Violation',
            'message': '상호 배타적인 역할을 동시에 할당할 수 없습니다'
        }), 400

    # 역할 할당 로직...
    return jsonify({'message': f'Roles assigned to {user_id}'})

if __name__ == '__main__':
    app.run(debug=True)
// RBAC 구현 예제 - Go/Gin
package main

import (
    "log"
    "net/http"
    "sync"

    "github.com/gin-gonic/gin"
)

// 역할-권한 매핑
var rolePermissions = map[string][]string{
    "admin":  {"users:create", "users:read", "users:update", "users:delete",
               "posts:create", "posts:read", "posts:update", "posts:delete"},
    "editor": {"posts:create", "posts:read", "posts:update", "users:read"},
    "viewer": {"posts:read", "users:read"},
}

// 사용자-역할 저장소 (실제로는 DB 사용)
type RBACStore struct {
    mu        sync.RWMutex
    userRoles map[string][]string
}

var store = &RBACStore{
    userRoles: map[string][]string{
        "user_001": {"admin"},
        "user_002": {"editor"},
        "user_003": {"viewer"},
    },
}

// 권한 확인 함수
func (s *RBACStore) HasPermission(userID, permission string) bool {
    s.mu.RLock()
    defer s.mu.RUnlock()

    roles, exists := s.userRoles[userID]
    if !exists {
        return false
    }

    for _, role := range roles {
        permissions, ok := rolePermissions[role]
        if !ok {
            continue
        }
        for _, p := range permissions {
            if p == permission {
                return true
            }
        }
    }
    return false
}

// RBAC 미들웨어
func RBACMiddleware(permission string) gin.HandlerFunc {
    return func(c *gin.Context) {
        userID := c.GetString("userID") // 인증 미들웨어에서 설정

        if userID == "" {
            c.JSON(http.StatusUnauthorized, gin.H{
                "error":   "Unauthorized",
                "message": "인증이 필요합니다",
            })
            c.Abort()
            return
        }

        if !store.HasPermission(userID, permission) {
            log.Printf("[RBAC DENIED] User: %s, Permission: %s", userID, permission)
            c.JSON(http.StatusForbidden, gin.H{
                "error":   "Forbidden",
                "message": permission + " 권한이 필요합니다",
            })
            c.Abort()
            return
        }

        log.Printf("[RBAC GRANTED] User: %s, Permission: %s", userID, permission)
        c.Next()
    }
}

// 인증 미들웨어 (예시)
func AuthMiddleware() gin.HandlerFunc {
    return func(c *gin.Context) {
        // 실제로는 JWT 토큰 검증 등
        userID := c.GetHeader("X-User-ID")
        if userID != "" {
            c.Set("userID", userID)
        }
        c.Next()
    }
}

func main() {
    r := gin.Default()
    r.Use(AuthMiddleware())

    // 라우트에 RBAC 적용
    api := r.Group("/api")
    {
        // 누구나 읽기 가능
        api.GET("/posts", RBACMiddleware("posts:read"), func(c *gin.Context) {
            c.JSON(http.StatusOK, gin.H{"posts": []string{"post1", "post2"}})
        })

        // editor 이상만 생성 가능
        api.POST("/posts", RBACMiddleware("posts:create"), func(c *gin.Context) {
            c.JSON(http.StatusOK, gin.H{"message": "Post created"})
        })

        // admin만 사용자 삭제 가능
        api.DELETE("/users/:id", RBACMiddleware("users:delete"), func(c *gin.Context) {
            c.JSON(http.StatusOK, gin.H{"message": "User deleted"})
        })
    }

    r.Run(":8080")
}

🗣️ Say It Like This in Practice

💬 In a Permission Design Meeting
"Let's set up the basic permission structure with RBAC. Let's start with three roles: admin, editor, and viewer, and we can break them down further later if needed. What matters is the principle of least privilege - grant each role only the permissions it truly needs, and approve exception requests with a time limit."
💬 In a code review
"The role check is hardcoded here. Please change it from if (user.role === 'admin') to the form hasPermission(user, 'users:delete'). If we later need to give the manager role delete permission too, we'll have to find and fix all of this code. Permissions should be checked per function, not per role."
💬 In response to a security audit
"We're conducting a quarterly access permission review. We identified 47 accounts with permissions that went unused last quarter and adjusted their roles, and revocation of permissions for departing employees is handled automatically within 24 hours through integration with the HR system. All permission changes are recorded in the audit log."

⚠️ Cautions & Best Practices

❌
Role Explosion

This is the phenomenon where the number of roles grows exponentially in pursuit of fine-grained control. Once hundreds of roles like "engineering_viewer_project_a_readonly_asia" accumulate, management becomes impossible. Keep roles to 20 or fewer, and handle detailed conditions with ABAC.

❌
Privilege Creep

This is the phenomenon where permissions keep accumulating because previous roles are not revoked when job duties change. Be sure to review existing roles upon department transfers or promotions, and conduct quarterly access permission reviews.

❌
Normalization of Exceptions

This is the pattern of temporarily granting admin permissions "because it's urgent" and never revoking them. Always set an expiration time for exception permissions and keep approval records. If possible, adopt a Just-In-Time (JIT) access approach.

✅
RBAC Best Practices

Define roles based on job functions, and break down permissions in a resource:action format (posts:delete). Allow multiple role assignments but apply Separation of Duties (SoD) rules, and record all permission changes in the audit log. Build automated provisioning/deprovisioning, and optimize with AI-based role mining.

🔗 Related Terms

📚 Learn More