streamflow/docs/RBAC_DEPLOYMENT.md

511 lines
12 KiB
Markdown
Raw Permalink Normal View History

# RBAC Deployment Guide
## Pre-Deployment Checklist
### 1. Verify Implementation
- ✅ All backend files pass syntax check
- ✅ Frontend components have no errors
- ✅ Translations complete (EN/RO)
- ✅ Documentation finalized
### 2. Database Backup
```bash
# Create backup before deploying RBAC changes
docker exec streamflow-backend npm run backup:create
```
### 3. Review Configuration
```bash
# Ensure JWT_SECRET is set
echo $JWT_SECRET
# Verify NODE_ENV for production
echo $NODE_ENV
```
---
## Deployment Steps
### Step 1: Stop Application
```bash
cd /home/iulian/projects/tv
docker-compose down
```
### Step 2: Pull Latest Changes
```bash
git pull origin main
# or copy updated files manually
```
### Step 3: Rebuild Docker Containers
```bash
docker-compose build --no-cache
```
### Step 4: Start Application
```bash
docker-compose up -d
```
### Step 5: Verify Database Initialization
```bash
# Check logs for RBAC initialization
docker-compose logs backend | grep -i "role"
# Expected output:
# ✓ Role seeded: admin
# ✓ Role seeded: moderator
# ✓ Role seeded: user
# ✓ Role seeded: viewer
# ✓ Permission audit log table created
```
### Step 6: Verify Routes
```bash
# Test RBAC API endpoints
curl -H "Authorization: Bearer YOUR_ADMIN_TOKEN" \
http://localhost:5000/api/rbac/roles
# Should return array of 4 default roles
```
---
## Post-Deployment Testing
### 1. Login as Admin
1. Navigate to `/login`
2. Login with admin credentials
3. Access `/security/rbac`
4. Verify RBAC Dashboard loads
### 2. Test Role Management
**Create Custom Role:**
1. Click "Create Role" button
2. Fill in:
- Role Key: `content_editor`
- Name: `Content Editor`
- Description: `Manages playlists and channels`
3. Select permissions:
- `playlists.view`, `playlists.create`, `playlists.edit`
- `channels.view`, `channels.edit`
4. Click "Create"
5. Verify role appears in list
**Edit Role:**
1. Click edit icon on custom role
2. Add permission: `playlists.delete`
3. Click "Save"
4. Verify permissions updated
**Delete Role:**
1. Click delete icon on custom role
2. Confirm deletion
3. Verify role removed
### 3. Test User Role Assignment
1. Go to "User Roles" tab
2. Select a test user
3. Click "Change Role"
4. Assign "moderator" role
5. Verify role assigned
6. Check audit log for `role_assigned` entry
### 4. Test Permission Checking
**As Moderator:**
1. Login as moderator user
2. Access `/security/rbac`
3. Should see error: "Insufficient permissions"
4. Access `/stats` - Should work ✅
5. Access `/settings` - Should only view, not edit
**As Regular User:**
1. Login as regular user
2. Access `/security` - Should not show admin features
3. Access own playlists - Should work ✅
4. Try to access user management - Should fail ❌
**As Viewer:**
1. Login as viewer user
2. Try to create playlist - Should fail ❌
3. View channels - Should work ✅
4. View favorites - Should work ✅
### 5. Test Audit Logging
1. Go to RBAC Dashboard > Audit Log tab
2. Verify all test actions logged:
- `role_created`
- `role_updated`
- `role_deleted`
- `role_assigned`
3. Check details show correct user, IP, timestamp
### 6. Test Permission Cache
1. Assign user to "moderator" role
2. Wait 5 minutes (cache TTL)
3. Verify user has new permissions
4. Or force refresh by reassigning role
---
## Verification Tests
### Backend API Tests
```bash
# Set your admin token
TOKEN="your_admin_jwt_token"
# Test 1: List all permissions
curl -H "Authorization: Bearer $TOKEN" \
http://localhost:5000/api/rbac/permissions | jq
# Test 2: List all roles
curl -H "Authorization: Bearer $TOKEN" \
http://localhost:5000/api/rbac/roles | jq
# Test 3: Get my permissions
curl -H "Authorization: Bearer $TOKEN" \
http://localhost:5000/api/rbac/my-permissions | jq
# Test 4: Create custom role
curl -X POST -H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{
"role_key": "test_role",
"name": "Test Role",
"description": "Testing role creation",
"permissions": ["playlists.view", "channels.view"]
}' \
http://localhost:5000/api/rbac/roles | jq
# Test 5: Get audit log
curl -H "Authorization: Bearer $TOKEN" \
http://localhost:5000/api/rbac/audit-log | jq
# Test 6: Get statistics
curl -H "Authorization: Bearer $TOKEN" \
http://localhost:5000/api/rbac/stats | jq
```
### Frontend Component Tests
1. **RBAC Dashboard Access**
- Admin: ✅ Full access
- Moderator: ❌ Access denied
- User: ❌ Access denied
- Viewer: ❌ Access denied
2. **My Permissions Tab**
- All roles: ✅ Can view own permissions
- Permissions grouped by category
- Correct permission counts
3. **Role Management**
- Create role: ✅ Works for admin
- Edit role: ✅ Works for admin (custom roles only)
- Delete role: ✅ Works for admin (custom roles only)
- System role protection: ✅ Cannot modify
4. **User Role Assignment**
- Assign role: ✅ Works for admin
- Self-assignment prevention: ✅ Cannot change own role
- Non-existent role: ❌ Error shown
---
## Monitoring & Maintenance
### Daily Checks
1. **Audit Log Review**
- Check for suspicious role changes
- Monitor permission grant patterns
- Review failed permission checks
2. **Role Distribution**
- Review `/api/rbac/stats`
- Ensure appropriate role distribution
- Identify over-privileged accounts
3. **Permission Cache Performance**
- Monitor cache hit rate (should be >90%)
- Check for cache invalidation patterns
### Weekly Maintenance
1. **Clean Old Audit Logs** (Optional)
```sql
DELETE FROM permission_audit_log
WHERE created_at < datetime('now', '-90 days');
```
2. **Review Custom Roles**
- Are all custom roles still needed?
- Can any be consolidated?
- Remove unused roles
3. **Permission Audit**
- Review user permissions
- Apply principle of least privilege
- Demote over-privileged users
### Monthly Review
1. **Security Assessment**
- Review role definitions
- Check for permission creep
- Validate default role permissions
2. **Performance Tuning**
- Analyze cache efficiency
- Check database query performance
- Review audit log size
3. **Documentation Update**
- Update custom role documentation
- Record permission changes
- Update deployment notes
---
## Troubleshooting
### Issue: RBAC routes not working
**Symptoms:** 404 errors on `/api/rbac/*` endpoints
**Solution:**
1. Verify route registration in `server.js`:
```javascript
app.use('/api/rbac', require('./routes/rbac'));
```
2. Restart server
3. Check logs for route loading errors
### Issue: Roles not seeded
**Symptoms:** Empty roles table, dashboard shows no roles
**Solution:**
1. Check database initialization logs:
```bash
docker-compose logs backend | grep -i "role seeded"
```
2. Manually initialize:
```bash
docker exec -it streamflow-backend node -e "
const { initializeRoles } = require('./middleware/rbac');
initializeRoles();
"
```
3. Restart application
### Issue: Permission checks failing
**Symptoms:** "Insufficient permissions" errors for valid users
**Solution:**
1. Clear permission cache:
```javascript
// In backend console
const { clearAllPermissionCache } = require('./middleware/rbac');
clearAllPermissionCache();
```
2. Verify user role:
```sql
SELECT id, username, role FROM users WHERE id = ?;
```
3. Verify role permissions:
```sql
SELECT * FROM roles WHERE role_key = 'user';
```
4. Check permission spelling (case-sensitive)
### Issue: Cannot delete custom role
**Symptoms:** "Cannot delete role that is assigned to users"
**Solution:**
1. Find users with that role:
```sql
SELECT id, username FROM users WHERE role = 'custom_role_key';
```
2. Reassign users to different role
3. Then delete custom role
### Issue: Audit log not recording
**Symptoms:** Empty audit log despite changes
**Solution:**
1. Verify table exists:
```sql
SELECT name FROM sqlite_master
WHERE type='table' AND name='permission_audit_log';
```
2. Check for INSERT errors in logs
3. Verify `logPermissionAction()` calls in code
### Issue: Frontend dashboard not loading
**Symptoms:** Blank page or React errors
**Solution:**
1. Check browser console for errors
2. Verify translations loaded:
```javascript
console.log(i18n.t('rbac.dashboard'));
```
3. Check API responses in Network tab
4. Verify authentication token valid
---
## Rollback Plan
If RBAC causes issues:
### Quick Rollback (Keep RBAC, Disable Checks)
1. Comment out RBAC middleware in routes:
```javascript
// Temporarily comment out
// const { requirePermission } = require('../middleware/rbac');
// Keep using requireAdmin
router.get('/users', authenticate, requireAdmin, ...);
```
2. Restart server
3. RBAC data preserved, enforcement disabled
### Full Rollback (Remove RBAC)
1. Restore database backup:
```bash
docker exec streamflow-backend npm run backup:restore -- backup-name.zip
```
2. Revert code changes:
```bash
git revert HEAD~5 # Revert last 5 commits
```
3. Rebuild and restart:
```bash
docker-compose down
docker-compose build --no-cache
docker-compose up -d
```
### Partial Rollback (Keep Tables, Remove UI)
1. Comment out RBAC Dashboard route in `App.jsx`
2. Remove RBAC link from Security Dashboard
3. Keep backend routes active (for future use)
---
## Performance Benchmarks
### Expected Performance
**Permission Check (Cached):**
- Response time: <5ms
- Database queries: 0
- Cache hit rate: >90%
**Permission Check (Uncached):**
- Response time: <50ms
- Database queries: 1
- Cache miss rate: <10%
**Role Assignment:**
- Response time: <100ms
- Database queries: 3
- Audit log writes: 1
**Audit Log Query:**
- Response time: <200ms (100 records)
- Database queries: 1
- Pagination supported
### Monitoring Queries
```sql
-- Check role distribution
SELECT r.name, COUNT(u.id) as user_count
FROM roles r
LEFT JOIN users u ON r.role_key = u.role
GROUP BY r.role_key;
-- Recent permission changes
SELECT action, COUNT(*) as count
FROM permission_audit_log
WHERE created_at >= datetime('now', '-7 days')
GROUP BY action;
-- Most active permission managers
SELECT u.username, COUNT(pal.id) as change_count
FROM permission_audit_log pal
JOIN users u ON pal.user_id = u.id
WHERE pal.created_at >= datetime('now', '-30 days')
GROUP BY u.id
ORDER BY change_count DESC
LIMIT 10;
```
---
## Security Checklist
### Pre-Production
- [ ] All default roles reviewed and approved
- [ ] System role permissions validated
- [ ] Custom roles documented
- [ ] Audit logging tested
- [ ] Permission cache working correctly
- [ ] All tests passing
- [ ] Documentation complete
### Production
- [ ] JWT_SECRET is strong and unique
- [ ] NODE_ENV=production
- [ ] HTTPS enabled
- [ ] Rate limiting active
- [ ] Audit logs monitored
- [ ] Backup strategy in place
- [ ] Rollback plan tested
### Post-Deployment
- [ ] All roles seeded correctly
- [ ] Permission checks working
- [ ] Audit log recording events
- [ ] Dashboard accessible to admin
- [ ] Users can view own permissions
- [ ] No performance degradation
- [ ] Logs show no errors
---
## Success Criteria
**Deployment Successful When:**
1. All 4 default roles visible in dashboard
2. Admin can create/edit/delete custom roles
3. Role assignment works correctly
4. Permission checks enforce access control
5. Audit log records all changes
6. Statistics show accurate data
7. Users can view own permissions
8. No errors in application logs
9. Performance within expected benchmarks
10. All security tests pass
---
## Support Resources
- **Documentation:** `/docs/RBAC_IMPLEMENTATION.md`
- **API Reference:** See documentation above
- **Frontend Guide:** Check RBACDashboard.jsx comments
- **Security Guide:** `/docs/SECURITY_IMPLEMENTATION_COMPLETE.md`
For issues or questions:
1. Check troubleshooting section
2. Review audit logs for clues
3. Enable debug logging
4. Contact development team
---
**Deployment Date:** 2024-12-13
**Version:** 1.0
**Status:** ✅ Production Ready