|
| 1 | +# RBAC (Role-Based Access Control) Implementation Plan |
| 2 | + |
| 3 | +## Executive Summary |
| 4 | + |
| 5 | +This document outlines the plan to add an optional, lightweight Role-Based Access Control system to the Cloudflare Workers Users Framework. The RBAC system will be completely optional, ensuring zero impact on existing deployments while providing powerful authorization capabilities for applications that need them. |
| 6 | + |
| 7 | +## High-Level Design |
| 8 | + |
| 9 | +### Core Principles |
| 10 | +1. **Optional by Default**: RBAC is disabled unless explicitly enabled via environment variable |
| 11 | +2. **Zero Breaking Changes**: Existing deployments continue working without modification |
| 12 | +3. **Performance-First**: Permissions cached in session to avoid repeated database queries |
| 13 | +4. **Simple Yet Flexible**: Resource:action permission model (e.g., "users:read", "posts:write") |
| 14 | +5. **Developer-Friendly**: Easy to understand, configure, and use |
| 15 | + |
| 16 | +### Architecture Overview |
| 17 | + |
| 18 | +``` |
| 19 | +┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ |
| 20 | +│ account-pages │────▶│ user-mgmt │────▶│ session-state │ |
| 21 | +│ (Frontend) │ │ (Worker) │ │ (Worker) │ |
| 22 | +└─────────────────┘ └─────────────────┘ └─────────────────┘ |
| 23 | + │ │ |
| 24 | + ▼ ▼ |
| 25 | + ┌─────────────┐ ┌─────────────┐ |
| 26 | + │ D1 Database │ │ KV Store │ |
| 27 | + │ + RBAC Tables│ │ + Permissions│ |
| 28 | + └─────────────┘ └─────────────┘ |
| 29 | +``` |
| 30 | + |
| 31 | +### Key Components |
| 32 | + |
| 33 | +1. **Environment Variable**: `RBAC_ENABLED=true` to enable the feature |
| 34 | +2. **Database Schema**: Four new tables (roles, permissions, user_roles, role_permissions) |
| 35 | +3. **Session Enhancement**: Permissions cached in session data for performance |
| 36 | +4. **Middleware**: `requirePermission()` middleware for route protection |
| 37 | +5. **Default Setup**: Two default roles (SUPER_ADMIN, MEMBER) with predefined permissions |
| 38 | + |
| 39 | +## Implementation Approach |
| 40 | + |
| 41 | +### Phase 1: Database and Core Infrastructure |
| 42 | +- Create RBAC database schema with migrations |
| 43 | +- Implement core permission checking functions |
| 44 | +- Add environment variable support |
| 45 | + |
| 46 | +### Phase 2: Session Integration |
| 47 | +- Enhance session creation to include user permissions |
| 48 | +- Modify session data structure to cache permissions |
| 49 | +- Update session-state worker to handle enhanced sessions |
| 50 | + |
| 51 | +### Phase 3: Authorization Middleware |
| 52 | +- Create permission checking middleware |
| 53 | +- Add middleware to protect existing endpoints (optional) |
| 54 | +- Implement permission utilities |
| 55 | + |
| 56 | +### Phase 4: Management APIs |
| 57 | +- Create RBAC management endpoints (/rbac/*) |
| 58 | +- Add role assignment functionality |
| 59 | +- Implement permission management |
| 60 | + |
| 61 | +### Phase 5: Migration and Documentation |
| 62 | +- Create migration scripts for existing users |
| 63 | +- Write comprehensive documentation |
| 64 | +- Add example implementations |
| 65 | + |
| 66 | +## Detailed Task List |
| 67 | + |
| 68 | +### 1. Database Schema Tasks |
| 69 | +- [ ] Create migration file `002-rbac.sql` with RBAC tables |
| 70 | + - [ ] Create `roles` table (id, name, description) |
| 71 | + - [ ] Create `permissions` table (id, name, description) |
| 72 | + - [ ] Create `user_roles` junction table |
| 73 | + - [ ] Create `role_permissions` junction table |
| 74 | +- [ ] Add default data migration |
| 75 | + - [ ] Insert default permissions (admin:all, users:read, users:write, etc.) |
| 76 | + - [ ] Insert default roles (SUPER_ADMIN, MEMBER) |
| 77 | + - [ ] Assign permissions to default roles |
| 78 | +- [ ] Create indexes for performance optimization |
| 79 | + |
| 80 | +### 2. Environment Configuration Tasks |
| 81 | +- [ ] Add `RBAC_ENABLED` to user-mgmt `wrangler.toml` |
| 82 | +- [ ] Add `SUPER_ADMIN_EMAIL` for bootstrapping first admin |
| 83 | +- [ ] Update `Env` interface in TypeScript with new variables |
| 84 | +- [ ] Add RBAC configuration to CLAUDE.md |
| 85 | + |
| 86 | +### 3. Type Definition Tasks |
| 87 | +- [ ] Create `types/rbac.ts` with RBAC-specific types |
| 88 | + - [ ] Define `Role` interface |
| 89 | + - [ ] Define `Permission` interface |
| 90 | + - [ ] Define `UserRole` interface |
| 91 | +- [ ] Update `SessionData` type to include permissions array |
| 92 | +- [ ] Add RBAC response types for API endpoints |
| 93 | + |
| 94 | +### 4. Core RBAC Functions |
| 95 | +- [ ] Create `src/rbac/permissions.ts` |
| 96 | + - [ ] Implement `getUserPermissions(userId)` function |
| 97 | + - [ ] Implement `hasPermission(permissions, required)` function |
| 98 | + - [ ] Implement `getUserRoles(userId)` function |
| 99 | +- [ ] Create `src/rbac/roles.ts` |
| 100 | + - [ ] Implement `assignRole(userId, roleId)` function |
| 101 | + - [ ] Implement `removeRole(userId, roleId)` function |
| 102 | + - [ ] Implement `createRole(name, description)` function |
| 103 | + |
| 104 | +### 5. Session Enhancement Tasks |
| 105 | +- [ ] Update session creation in `user-mgmt/src/session.ts` |
| 106 | + - [ ] Add permission fetching when RBAC is enabled |
| 107 | + - [ ] Include permissions in session data |
| 108 | +- [ ] Update session-state worker handlers |
| 109 | + - [ ] Ensure permissions are stored in KV |
| 110 | + - [ ] Handle larger session payloads |
| 111 | + |
| 112 | +### 6. Middleware Implementation |
| 113 | +- [ ] Create `src/middleware/rbac.ts` |
| 114 | + - [ ] Implement `requirePermission(permission)` middleware |
| 115 | + - [ ] Add support for checking multiple permissions |
| 116 | + - [ ] Handle "admin:all" special permission |
| 117 | +- [ ] Create `requireAnyPermission(permissions)` for OR logic |
| 118 | +- [ ] Create `requireAllPermissions(permissions)` for AND logic |
| 119 | + |
| 120 | +### 7. User Registration Updates |
| 121 | +- [ ] Modify registration handler to assign default role |
| 122 | + - [ ] Query MEMBER role ID |
| 123 | + - [ ] Insert user_roles record on registration |
| 124 | +- [ ] Add role assignment to user creation flow |
| 125 | + |
| 126 | +### 8. Management API Endpoints |
| 127 | +- [ ] Create `/rbac/roles` endpoints |
| 128 | + - [ ] GET /rbac/roles - List all roles |
| 129 | + - [ ] POST /rbac/roles - Create new role |
| 130 | + - [ ] PUT /rbac/roles/:id - Update role |
| 131 | + - [ ] DELETE /rbac/roles/:id - Delete role |
| 132 | +- [ ] Create `/rbac/permissions` endpoints |
| 133 | + - [ ] GET /rbac/permissions - List all permissions |
| 134 | + - [ ] POST /rbac/permissions - Create new permission |
| 135 | +- [ ] Create `/rbac/users/:userId/roles` endpoints |
| 136 | + - [ ] GET /rbac/users/:userId/roles - Get user's roles |
| 137 | + - [ ] POST /rbac/users/:userId/roles - Assign role to user |
| 138 | + - [ ] DELETE /rbac/users/:userId/roles/:roleId - Remove role from user |
| 139 | + |
| 140 | +### 9. Existing Endpoint Protection |
| 141 | +- [ ] Add optional permission checks to sensitive endpoints |
| 142 | + - [ ] DELETE /users/:id - requires "users:delete" |
| 143 | + - [ ] PUT /users/:id - requires "users:update" or own user |
| 144 | +- [ ] Update load-user endpoint to include roles/permissions when RBAC enabled |
| 145 | + |
| 146 | +### 10. Admin Bootstrapping |
| 147 | +- [ ] Create initialization script for first admin |
| 148 | + - [ ] Check for SUPER_ADMIN_EMAIL environment variable |
| 149 | + - [ ] Assign SUPER_ADMIN role to specified user |
| 150 | +- [ ] Add bootstrapping to worker startup (optional) |
| 151 | + |
| 152 | +### 11. Testing Tasks |
| 153 | +- [ ] Create test suite for RBAC functions |
| 154 | +- [ ] Test permission checking logic |
| 155 | +- [ ] Test middleware with various permission scenarios |
| 156 | +- [ ] Test session enhancement |
| 157 | +- [ ] Test backwards compatibility with RBAC disabled |
| 158 | + |
| 159 | +### 12. Migration Scripts |
| 160 | +- [ ] Create script to assign default role to existing users |
| 161 | +- [ ] Create script to promote specific users to admin |
| 162 | +- [ ] Document migration process for existing deployments |
| 163 | + |
| 164 | +### 13. Documentation Tasks |
| 165 | +- [ ] Update README.md with RBAC section |
| 166 | +- [ ] Create RBAC.md with detailed documentation |
| 167 | + - [ ] Configuration guide |
| 168 | + - [ ] Permission format explanation |
| 169 | + - [ ] API endpoint documentation |
| 170 | + - [ ] Migration guide |
| 171 | +- [ ] Add RBAC examples to account-pages |
| 172 | +- [ ] Update CLAUDE.md with RBAC information |
| 173 | + |
| 174 | +### 14. Frontend Examples |
| 175 | +- [ ] Add permission-based UI elements to account-pages |
| 176 | + - [ ] Show/hide admin features based on permissions |
| 177 | + - [ ] Display user's roles on profile page |
| 178 | +- [ ] Create admin panel example (future enhancement) |
| 179 | + |
| 180 | +### 15. Performance Optimization |
| 181 | +- [ ] Add database indexes for permission queries |
| 182 | +- [ ] Implement permission caching strategy |
| 183 | +- [ ] Monitor and optimize permission query performance |
| 184 | + |
| 185 | +## Migration Strategy |
| 186 | + |
| 187 | +1. **Deploy Code** - Deploy new code with RBAC_ENABLED=false |
| 188 | +2. **Run Migrations** - Execute database migrations to create RBAC tables |
| 189 | +3. **Assign Roles** - Run script to assign default roles to existing users |
| 190 | +4. **Bootstrap Admin** - Assign SUPER_ADMIN role to designated user |
| 191 | +5. **Enable RBAC** - Set RBAC_ENABLED=true and redeploy |
| 192 | + |
| 193 | +## Success Criteria |
| 194 | + |
| 195 | +- [ ] Existing deployments work unchanged when RBAC is disabled |
| 196 | +- [ ] New deployments can enable RBAC with minimal configuration |
| 197 | +- [ ] Permission checks add <5ms latency to protected requests |
| 198 | +- [ ] Clear documentation enables developers to implement RBAC quickly |
| 199 | +- [ ] Migration path is safe and reversible |
| 200 | + |
| 201 | +## Future Enhancements |
| 202 | + |
| 203 | +1. **Admin UI** - Dedicated Pages application for RBAC management |
| 204 | +2. **Dynamic Permissions** - Runtime permission registration |
| 205 | +3. **Permission Wildcards** - Support for pattern matching (e.g., "posts:*") |
| 206 | +4. **Audit Logging** - Track permission changes and access attempts |
| 207 | +5. **Session Revocation** - Immediate permission revocation capability |
0 commit comments