feat(auth): implement dynamic RBAC and privilege escalation defense
Summary of Changes: Dynamic RBAC & Privilege Escalation Defense
Overview
This pull request introduces a fully dynamic, database-driven Role-Based Access Control (RBAC) engine accompanied by comprehensive Privilege Escalation Defense mechanisms. It transitions the application from static, hard-coded role checks to granular, permission-based authorization (resource.action) while strictly maintaining 100% backward compatibility with existing legacy role workflows.
Key Features & Architectural Enhancements
-
Database Schema & Data Model
- Added relational models for
Role,Permission,UserRoleAssignment(user_roles), andRolePermission(role_permissions). - Retained the legacy enum field on users to ensure zero-breakage across existing test suites and services.
- Deployed migration and populated a deterministic seed catalog comprising 32 system permissions and 4 foundational system roles.
- Added relational models for
-
Privilege Escalation Defense Matrix
- Self-Escalation Barrier: Explicitly blocks any authenticated user from modifying, assigning, or revoking their own roles.
- Super Admin Isolation: Regular administrators cannot assign the Super Admin role, tamper with Super Admin accounts, or modify Super Admin role permissions.
- Last Active Super Admin Protection: Uses transactional atomic counting to guarantee the system never drops below at least one active Super Admin account.
- System Role Integrity: System roles are permanently protected against deletion, renaming, or deactivation.
- Mass Assignment & Injection Defense: Strips untrusted role or permission parameters from user update schemas; permissions are dynamically resolved server-side.
-
Authorization Engine & Middleware
- Implemented fail-closed (deny-by-default) middlewares:
requirePermission(permission)requireAnyPermission(...permissions)requireAllPermissions(...permissions)
- Integrated lightweight in-memory caching for resolved user roles and permissions, with automatic cache invalidation triggered upon any role or permission mutation.
- Dual-mode
requireRolemiddleware supporting both legacy enum values and dynamic role slugs.
- Implemented fail-closed (deny-by-default) middlewares:
-
RESTful Management APIs
- Roles: Full lifecycle management (list, query, create, update, delete, view assigned users).
- Permissions: Read-only registry inspection and system permission discovery.
- Role-Permission Bindings: Dynamic attachment and synchronization of permissions to roles.
- User-Role Assignments: Granular endpoints to inspect, replace, add, or revoke individual user roles.
-
Security Audit Logging
- Structured audit trails emitted for all role mutations, permission bindings, and blocked escalation attempts (
PRIVILEGE_ESCALATION_BLOCKED,SUPER_ADMIN_ASSIGN_ATTEMPT).
- Structured audit trails emitted for all role mutations, permission bindings, and blocked escalation attempts (