Advanced RBAC Permissions
Granular resource:action:scope permissions with custom roles
Building Block #17: Advanced RBAC Permissions
Status: 📋 Planned Dependencies: Building Block #03 (RBAC Implementation), All CORE Building Blocks (#11-14) When: Month 6 (ADD-ON Phase) Context: Solo Developer + AI
Definition
Implement advanced RBAC with granular permissions:
- Custom role creation (beyond Admin, Manager, Employee)
- Permission assignment with scopes (resource:action:scope)
- Scope-based filtering (own, team, department, company)
- Role builder UI for tenant admins
- Permission inheritance and role hierarchy
Dependencies
- ✅ Building Block #03: RBAC Implementation
- Basic role system exists (Admin, Manager, Employee)
- Permission model exists
- UserRole, RolePermission tables exist
- ✅ Building Blocks #11-14: CORE Features
- All resources exist (Employee, TimeOff, Document, Dashboard)
- Basic permission checks in place
- ✅ Building Block #09: Redis Caching
- Permission caching available
- Requires existing foundation patterns
Implementation Checklist
GATE 1: BUILD
Database Model Updates
- Update Role model (add isSystem, isCustom flags)
- isSystem (boolean) - for built-in roles (Admin, Manager, Employee)
- isCustom (boolean) - for tenant-created roles
- description
- priority (for hierarchy)
- Update Permission model (add scope support)
- resource (employees, time_off, documents, dashboards, goals, feed)
- action (read, create, update, delete, approve, export)
- scope (OWN, TEAM, DEPARTMENT, COMPANY)
- Add composite unique constraint
- Create RoleHierarchy model (optional, for inheritance)
- parentRoleId
- childRoleId
- @@unique([parentRoleId, childRoleId])
- Create PermissionOverride model (user-specific overrides)
- id (UUID)
- tenantId
- userId
- permissionId
- granted (boolean - true=grant, false=deny)
- createdAt
- Add indexes
- Permission(resource, action, scope)
- RoleHierarchy(parentRoleId)
- PermissionOverride(userId)
Permission Definition
- Define all resource:action:scope combinations
employees:read:own - View own profile employees:read:team - View team members (direct reports) employees:read:department - View department employees employees:read:company - View all employees employees:update:own - Update own profile employees:update:team - Update team members employees:update:department - Update department employees employees:update:company - Update all employees time_off:read:own - View own time-off time_off:read:team - View team time-off time_off:approve:team - Approve team time-off time_off:approve:department - Approve department time-off documents:read:own - View own documents documents:read:team - View team documents documents:read:company - View company documents documents:upload:own - Upload own documents documents:manage:company - Manage all documents dashboards:read:own - View own dashboards dashboards:read:shared - View shared dashboards dashboards:create:own - Create dashboards dashboards:manage:company - Manage all dashboards goals:read:own - View own goals goals:read:team - View team goals (as manager) goals:create:own - Create own goals goals:manage:team - Manage team goals feed:read:company - Read company feed feed:create:own - Create posts feed:moderate:company - Moderate all posts roles:read:company - View roles roles:manage:company - Create/edit custom roles (admin only)
Backend Implementation
- Create AdvancedRbacModule
- Update PermissionService
- Support scope-based permission checks
- Add
hasPermission(userId, resource, action, scope, targetId?) - Add permission inheritance from role hierarchy
- Add permission override support
- Cache computed permissions in Redis
- Create RoleBuilderService
- Create custom role with permissions
- Clone existing role
- Delete custom role (not system roles)
- Assign/remove users from roles
- Create RoleController
- GET /api/v1/roles (list all roles)
- GET /api/v1/roles/:id (get role with permissions)
- POST /api/v1/roles (create custom role)
- PUT /api/v1/roles/:id (update custom role)
- DELETE /api/v1/roles/:id (delete custom role)
- GET /api/v1/roles/:id/users (list users with role)
- POST /api/v1/roles/:id/users (assign user to role)
- DELETE /api/v1/roles/:id/users/:userId (remove user from role)
- Create PermissionController
- GET /api/v1/permissions (list all available permissions)
- GET /api/v1/permissions/user/:userId (get user's effective permissions)
- POST /api/v1/permissions/check (check if user has permission)
- POST /api/v1/permissions/override (add user permission override)
- DELETE /api/v1/permissions/override/:id (remove override)
- Update existing guards to use scope-based checks
- PermissionGuard enhancement for scope checking
- Add
@RequirePermission('employees:read:team')decorator - Add scope resolution (determine if target is own/team/dept/company)
- Update cache invalidation
- Invalidate on role change
- Invalidate on permission assignment
- Invalidate on user role change
- Add DTOs with validation
- CreateRoleDto (name, description, permissions[])
- AssignPermissionDto (permissionId, scope)
- PermissionCheckDto (resource, action, targetId)
Scope Resolution Logic
- Implement scope resolver
// Determine the scope required to access a resource resolveScope(userId: string, targetId: string, resource: string): Scope { // Own: targetId is user's own record // Team: targetId belongs to user's direct reports // Department: targetId belongs to user's department // Company: any record in tenant } - Implement permission checker with scope
async canAccess(userId: string, resource: string, action: string, targetId: string): boolean { const requiredScope = this.resolveScope(userId, targetId, resource); return this.hasPermission(userId, resource, action, requiredScope); }
Default Roles Configuration
- Define system roles with default permissions
EMPLOYEE: - employees:read:own - employees:update:own - time_off:read:own - time_off:create:own - documents:read:own - documents:upload:own - goals:read:own - goals:create:own - feed:read:company - feed:create:own - dashboards:read:own - dashboards:create:own MANAGER: - All EMPLOYEE permissions - employees:read:team - employees:update:team - time_off:read:team - time_off:approve:team - goals:read:team - goals:manage:team ADMIN: - All MANAGER permissions - employees:read:company - employees:update:company - documents:manage:company - dashboards:manage:company - roles:read:company - roles:manage:company - feed:moderate:company
Frontend Implementation
- Create role management page
- Create role builder UI
- Role name and description
- Permission selector (grouped by resource)
- Scope selector per permission
- Create role assignment UI
- View users with role
- Assign/remove users
- Create permission viewer component
- Show effective permissions for user
- Highlight inherited vs direct permissions
- Create permission override UI (for admin)
- Update existing UIs to respect granular permissions
- Hide/show actions based on permissions
- Filter data based on scope
GATE 2: TEST
- Test custom role creation
- Test permission assignment with scopes
- Test permission inheritance from roles
- Test scope resolution (own, team, department, company)
- Test permission override (grant/deny)
- Test cache invalidation on role changes
- Test that system roles cannot be deleted
- Test that custom roles can only be managed by admin
- Test tenant isolation (roles are per-tenant)
- Test backward compatibility with existing permissions
- Write unit tests for PermissionService
- Write integration tests for role management
- All tests passing
GATE 3: REVIEW & APPROVE
- Self-review implementation
- Verify scope-based access control works
- Check permission caching performance
- Verify existing features still work
- Test role builder UX
- Document approval reasoning
- Status: ✅ APPROVED
GATE 4: DOCUMENT
- Document advanced RBAC architecture
- Document permission scope system
- Document role hierarchy
- Document permission override system
- Document cache invalidation strategy
- Update API documentation
- Update
.cursorruleswith permission patterns - Update
CLAUDE.md - Update memory log
GATE 5: COMMIT & TAG
- Git commit with clear message: "Building Block #17: Advanced RBAC Permissions complete"
- Tag:
building-block-17-advanced-rbac - Push to main
- Update status tracker
Testing Requirements
Unit Tests
- Permission scope resolution
- Permission inheritance
- Cache invalidation logic
- Role validation
Integration Tests
- Custom role CRUD
- Permission assignment flow
- Scope-based access control
- Permission override
- Cache invalidation
Documentation Requirements
- Advanced RBAC architecture
- Permission scope documentation
- Role builder guide
- Permission override guide
- API endpoint documentation
- Migration guide from basic RBAC
Approval Criteria
Building block is complete when:
- ✅ Custom role creation working
- ✅ Permission scopes working (own, team, department, company)
- ✅ Scope-based access control working
- ✅ Permission inheritance working
- ✅ Permission overrides working
- ✅ Role builder UI working
- ✅ Cache invalidation working
- ✅ Backward compatible with basic RBAC
- ✅ All tests passing
- ✅ Documentation complete
AI Context
What AI needs to know:
- Permission format:
resource:action:scope - Scopes: OWN, TEAM, DEPARTMENT, COMPANY
- System roles: ADMIN, MANAGER, EMPLOYEE (cannot be deleted)
- Custom roles: Tenant-created, can be modified/deleted
- Permission inheritance: Role hierarchy (parent → child)
- Permission override: User-specific grant/deny
- Cache key:
permissions:{tenantId}:{userId} - Invalidate cache on any role/permission change
Patterns to follow:
- Use
@RequirePermission('resource:action:scope')decorator - Scope resolution: Determine required scope from target ID
- Permission check:
hasPermission(userId, resource, action, scope) - Cache computed permissions (union of all roles + overrides)
- Invalidate on: role change, permission change, user-role change
Design Decisions
Based on feature-phases.mdx guidance:
- ✅ Custom role creation
- ✅ Permission assignment with scopes
- ✅ Scope-based filtering (own, team, department, company)
- ✅ Role builder UI
- ❌ Complex role hierarchies (keep simple parent-child)
- ❌ Permission templates (future enhancement)
- ❌ Audit logging of permission changes (future)
Note: Backend already supports granular permissions from foundation (Building Block #03). This building block primarily adds:
- Scope-based filtering
- Custom role creation UI
- Enhanced permission management
Migration from Basic RBAC
Existing code using basic RBAC will continue to work:
- Old:
@RequirePermissions('employees:read')→ Works (defaults to COMPANY scope) - New:
@RequirePermissions('employees:read:team')→ Scope-specific
Last Updated: 2025-11-27