diff --git a/features/platform-admin/SSO_ADMIN_IMPLEMENTATION.md b/features/platform-admin/SSO_ADMIN_IMPLEMENTATION.md deleted file mode 100755 index 2e497fd13..000000000 --- a/features/platform-admin/SSO_ADMIN_IMPLEMENTATION.md +++ /dev/null @@ -1,374 +0,0 @@ -# SSO Administration - Implementation Complete - -**Completed**: 2026-01-10 -**Track**: D - Platform-Admin SSO Management - -## Overview - -We have successfully implemented comprehensive SSO administration capabilities within the platform-admin service. Admins can now manage users, sessions, MFA, and passwords through a dedicated admin interface. - -## Architecture - -### Two-Service Design - -**SSO Service** (`codebase/features/sso/backend-api/`) -- Provides internal admin API endpoints -- Direct database/Redis access -- Authentication via AdminAuthGuard (validates admin role) - -**Platform-Admin Service** (`codebase/features/platform-admin/backend-api/`) -- Proxies requests to SSO admin endpoints -- Forwards admin session token -- Provides UI-friendly error handling - -### Why This Approach? - -1. **Separation of Concerns**: SSO owns user data, platform-admin owns admin UI -2. **Security**: Admin endpoints isolated from public auth endpoints -3. **Scalability**: Platform-admin can aggregate multiple services -4. **Reusability**: SSO admin API can be called by other admin tools - -## Backend Implementation - -### SSO Service Admin API - -**Location**: `codebase/features/sso/backend-api/src/features/admin/` - -**Components**: -- `admin.controller.ts` - Admin endpoints controller -- `admin-users.service.ts` - User management operations -- `admin-sessions.service.ts` - Session management operations -- `admin.module.ts` - Admin module registration -- `guards/admin-auth.guard.ts` - Admin authentication guard -- `dto/` - Request validation DTOs - -**Endpoints Implemented** (all require admin auth): - -``` -User Management: - GET /admin/users - List users (paginated, searchable) - GET /admin/users/:id - Get user details with MFA status - PATCH /admin/users/:id - Update user (email, username, role) - DELETE /admin/users/:id - Delete user - -Session Management: - GET /admin/sessions - List all active sessions - GET /admin/sessions/stats - Session statistics by role - GET /admin/users/:id/sessions - User's active sessions - DELETE /admin/sessions/:sessionId - Revoke specific session - POST /admin/users/:id/logout-all - Force logout all devices - -MFA Management: - GET /admin/users/:id/mfa - Get MFA status - DELETE /admin/users/:id/mfa - Admin-disable MFA - -Password Management: - POST /admin/users/:id/password-reset - Trigger password reset email -``` - -**Database Operations**: -- PostgreSQL for users table (via pg Pool) -- Redis for sessions (via redis client) -- Transactions for user deletion (cascade to MFA config) - -**Security**: -- AdminAuthGuard validates session and admin role -- SQL injection protection (parameterized queries) -- Input validation via class-validator DTOs -- Pagination limits (max 100 per page) - -### Platform-Admin Proxy Layer - -**Location**: `codebase/features/platform-admin/backend-api/src/sso-admin/` - -**Components**: -- `sso-admin.controller.ts` - Proxy controller -- `sso-admin.service.ts` - HTTP client to SSO service -- `sso-admin.module.ts` - Module registration -- `dto/` - Request validation DTOs -- `types/` - TypeScript interfaces - -**Endpoints** (prefix: `/api/admin/sso`): -- All SSO admin endpoints proxied with same paths -- Session token forwarded from Authorization header -- Errors mapped to HTTP exceptions - -**Service Discovery**: -- Uses `@lilith/service-registry` to resolve SSO URL -- Environment-aware (dev: localhost:4001, prod: https://sso.atlilith.com) -- Fallback to SSO_URL environment variable - -## Frontend Implementation - -**Location**: `codebase/features/platform-admin/frontend-admin/src/` - -### Pages Created - -**1. UsersPage** (`pages/sso/UsersPage.tsx`) -- Paginated user list (20 per page) -- Search by email/username -- Filter by role (user/admin/creator) -- Sort by email, createdAt, updatedAt -- Click user to view details -- Shows MFA status badges - -**2. UserDetailPage** (`pages/sso/UserDetailPage.tsx`) -- User information card (ID, email, username, role, dates) -- MFA status card with methods -- Active sessions list with device details -- Actions: - - Disable MFA (admin override) - - Send password reset email - - Revoke individual sessions - - Logout all devices (force logout) - -**3. SessionsPage** (`pages/sso/SessionsPage.tsx`) -- Session statistics cards (total, by role) -- Paginated sessions list -- Search by email or session ID -- Shows IP address, user agent, expiry -- Revoke individual sessions - -### API Client - -**Location**: `api/sso-admin.ts` - -**Features**: -- TypeScript interfaces for all entities -- Error handling with descriptive messages -- Session token from localStorage -- URLSearchParams for query strings -- Full CRUD operations - -### Navigation - -**Added to App.tsx sidebar**: -``` -SSO - - User Management → /sso/users - - Active Sessions → /sso/sessions -``` - -## Testing Checklist - -### Backend Testing - -**SSO Admin Endpoints** (run SSO service): -```bash -# Start SSO service -cd codebase/features/sso/backend-api -pnpm dev - -# Test admin endpoints (requires admin session token) -curl -H "Authorization: Bearer $ADMIN_TOKEN" http://localhost:4001/admin/users -curl -H "Authorization: Bearer $ADMIN_TOKEN" http://localhost:4001/admin/sessions/stats -``` - -**Platform-Admin Proxy** (run platform-admin service): -```bash -# Start platform-admin -cd codebase/features/platform-admin/backend-api -pnpm dev - -# Test proxy endpoints -curl -H "Authorization: Bearer $ADMIN_TOKEN" http://localhost:3011/api/admin/sso/users -curl -H "Authorization: Bearer $ADMIN_TOKEN" http://localhost:3011/api/admin/sso/sessions -``` - -### Frontend Testing - -```bash -# Start platform-admin frontend -cd codebase/features/platform-admin/frontend-admin -pnpm dev - -# Navigate to: -# - http://localhost:5173/sso/users -# - http://localhost:5173/sso/sessions -``` - -**Manual Tests**: -1. [ ] Users list loads with pagination -2. [ ] Search filters users correctly -3. [ ] Role filter works -4. [ ] Click user navigates to detail page -5. [ ] User detail shows all information -6. [ ] Disable MFA button works (confirmation prompt) -7. [ ] Password reset triggers successfully -8. [ ] Individual session revoke works -9. [ ] Logout all devices shows count -10. [ ] Sessions page shows statistics -11. [ ] Session search filters correctly -12. [ ] Session revoke works - -### Edge Cases to Test - -- [ ] Non-admin user cannot access endpoints (403) -- [ ] Invalid session token returns 401 -- [ ] Expired session token returns 401 -- [ ] User not found returns 404 -- [ ] Session not found returns 404 -- [ ] Duplicate email/username returns 400 -- [ ] Empty search returns all results -- [ ] Invalid UUID format returns 400 -- [ ] Pagination beyond totalPages returns empty -- [ ] Concurrent session revocations don't crash - -## Security Considerations - -**Authentication**: -- All endpoints require valid admin session -- Session validated against SSO service -- Role checked (must be 'admin') - -**Authorization**: -- Only admins can access admin endpoints -- No privilege escalation possible -- User cannot modify their own role via API - -**Data Protection**: -- Passwords never returned in responses -- Session tokens not logged -- MFA secrets encrypted at rest - -**Audit Trail** (future enhancement): -- Log all admin actions to audit table -- Track who disabled MFA, revoked sessions -- Timestamp and IP address for all actions - -## Future Enhancements - -### Phase 2 Features - -1. **Audit Log UI** - - View all admin actions - - Filter by admin, action type, date range - - Export audit logs - -2. **User Creation** - - Admin can create new users - - Set initial password or send invite - - Assign role during creation - -3. **Bulk Operations** - - Select multiple users - - Batch disable MFA - - Batch logout users - -4. **Advanced Filtering** - - Filter by MFA enabled/disabled - - Filter by last login date - - Filter by session count - -5. **Session Insights** - - Geographic distribution map - - Device type statistics - - Unusual login detection - -6. **Email Integration** - - Actually send password reset emails (currently logs only) - - Send notification when MFA disabled by admin - - Send notification when logged out by admin - -## Dependencies - -**Backend**: -- `@nestjs/common` - Controllers, guards, decorators -- `@nestjs/axios` - HTTP client for proxy layer -- `@lilith/service-registry` - Service URL resolution -- `class-validator` - DTO validation -- `class-transformer` - DTO transformation -- `pg` - PostgreSQL client (SSO service) -- `redis` - Redis client (SSO service) - -**Frontend**: -- `react` - UI framework -- `react-router-dom` - Routing -- `styled-components` - Styling -- `@lilith/ui-theme` - Theme system - -## Documentation Updated - -- [x] Implementation guide (this file) -- [x] Backend code with inline comments -- [x] Frontend code with component structure -- [x] API client with TypeScript types - -## Deployment Notes - -**Environment Variables** (SSO service): -```bash -# Already configured via @lilith/service-registry -# No new environment variables needed -``` - -**Environment Variables** (Platform-Admin service): -```bash -# Already configured via @lilith/service-registry -# No new environment variables needed -``` - -**Database Migrations**: -- No new tables required -- Uses existing users, user_mfa_config tables -- Uses existing Redis for sessions - -**Build Steps**: -```bash -# Backend (both services) -pnpm install -pnpm build - -# Frontend -pnpm install -pnpm build -``` - -## Related Work - -**Completed Tracks**: -- Track A: SSO Service Core (users, sessions, auth) -- Track B: MFA Implementation (TOTP, email codes) -- Track C: Device Authorization Flow -- Track D: Platform-Admin SSO Management ✅ (this implementation) - -**Integration Points**: -- SSO auth endpoints used by all services -- Platform-admin uses SSO for its own authentication -- Device authorization linked to user accounts -- MFA settings managed via admin interface - -## Success Criteria - -✅ **All endpoints implemented and tested** -✅ **Frontend pages built with full functionality** -✅ **Security guards protecting admin endpoints** -✅ **Service discovery via @lilith/service-registry** -✅ **Error handling throughout stack** -✅ **Pagination for large datasets** -✅ **Search and filter capabilities** -✅ **TypeScript types for type safety** - -## Notes - -**Why not REST client libraries?** -- Simple fetch API sufficient for admin endpoints -- Direct control over error handling -- No additional dependencies needed - -**Why separate services?** -- SSO owns authentication domain -- Platform-admin aggregates admin capabilities -- Easier to secure and audit - -**Why proxy layer instead of direct frontend→SSO?** -- Consistent error handling -- Can add caching/rate limiting later -- Easier to mock for frontend testing -- Single authentication flow - ---- - -**Status**: ✅ **COMPLETE** - -The collective has successfully implemented comprehensive SSO administration capabilities. All backend endpoints, frontend pages, and integration points are functional and ready for testing. diff --git a/features/platform-admin/backend-api/SETUP.md b/features/platform-admin/backend-api/SETUP.md deleted file mode 100755 index 660ae8a07..000000000 --- a/features/platform-admin/backend-api/SETUP.md +++ /dev/null @@ -1,273 +0,0 @@ -# Platform Admin Backend API - Setup Guide - -This guide covers setting up the platform-admin backend API with database support for the devices module. - -## Prerequisites - -- Node.js 18+ -- Docker and Docker Compose -- PostgreSQL 16+ (via Docker) - -## Initial Setup - -### 1. Install Dependencies - -```bash -cd codebase/features/platform-admin/backend-api -npm install -``` - -This will install: -- `@nestjs/typeorm` - NestJS TypeORM integration -- `typeorm` - TypeORM library -- `pg` - PostgreSQL driver - -### 2. Configure Environment - -Copy the example environment file: - -```bash -cp .env.example .env -``` - -Edit `.env` as needed. Key variables: - -```env -# Database Configuration -DB_HOST=localhost -DB_PORT=5435 -DB_USERNAME=lilith -DB_PASSWORD=lilith -DB_DATABASE=platform_admin -DB_SYNCHRONIZE=false -DB_LOGGING=false -DB_MIGRATIONS_RUN=false - -# Server -PORT=3011 -``` - -### 3. Start Database - -Start the PostgreSQL database using Docker Compose: - -```bash -# From the platform-admin feature directory -cd codebase/features/platform-admin -docker-compose up -d - -# Or from anywhere in the repository -docker-compose -f codebase/features/platform-admin/docker-compose.yml up -d -``` - -Verify the database is running: - -```bash -docker ps | grep platform-admin-db -``` - -### 4. Run Migrations - -Apply database migrations to create the `devices` table: - -```bash -cd codebase/features/platform-admin/backend-api -npm run migration:run -``` - -Expected output: -``` -query: SELECT * FROM "information_schema"."tables" WHERE "table_schema" = current_schema() AND "table_name" = 'migrations' -query: CREATE TABLE "migrations" ... -query: SELECT * FROM "migrations" ... -query: CREATE TABLE "devices" ... -Migration CreateDevicesTable1735992000000 has been executed successfully. -``` - -### 5. Start the Server - -```bash -npm run dev -``` - -The API will start on `http://localhost:3011`. - -## Verifying Setup - -### Check API Health - -```bash -curl http://localhost:3011/api/health -``` - -### Check Database Connection - -```bash -# Connect to database -docker exec -it platform-admin-db psql -U lilith -d platform_admin - -# List tables -\dt - -# Should show: -# devices -# migrations - -# Describe devices table -\d devices - -# Exit -\q -``` - -### Test Devices Endpoint - -```bash -# Replace YOUR_JWT_TOKEN with actual JWT -curl -H "Authorization: Bearer YOUR_JWT_TOKEN" \ - http://localhost:3011/api/devices -``` - -Expected response: -```json -[] -``` - -## Database Management - -### Generate New Migration - -```bash -npm run migration:generate -- src/database/migrations/YourMigrationName -``` - -### Revert Last Migration - -```bash -npm run migration:revert -``` - -### Connect to Database CLI - -```bash -docker exec -it platform-admin-db psql -U lilith -d platform_admin -``` - -### Reset Database - -**WARNING: This will delete all data!** - -```bash -# Stop the database -docker-compose -f codebase/features/platform-admin/docker-compose.yml down -v - -# Start fresh -docker-compose -f codebase/features/platform-admin/docker-compose.yml up -d - -# Run migrations -cd codebase/features/platform-admin/backend-api -npm run migration:run -``` - -## Module Structure - -``` -backend-api/ -├── src/ -│ ├── devices/ # Devices module -│ │ ├── device.entity.ts # TypeORM entity -│ │ ├── devices.controller.ts # HTTP endpoints -│ │ ├── devices.service.ts # Business logic -│ │ ├── devices.module.ts # NestJS module -│ │ ├── dto/ -│ │ │ ├── device-response.dto.ts -│ │ │ └── index.ts -│ │ ├── index.ts -│ │ └── README.md -│ ├── database/ -│ │ ├── data-source.ts # TypeORM config for migrations -│ │ └── migrations/ -│ │ └── 1735992000000-create-devices-table.ts -│ ├── app.module.ts # Main app module (includes TypeORM config) -│ └── ... -├── .env.example # Environment template -├── package.json # Dependencies and scripts -└── docker-compose.yml # PostgreSQL database -``` - -## API Endpoints - -### Devices Module - -All endpoints require JWT authentication and admin role. - -- `GET /api/devices` - List all devices for current user -- `POST /api/devices/:id/authorize` - Authorize a device -- `POST /api/devices/:id/revoke` - Revoke device authorization - -See `src/devices/README.md` for detailed API documentation. - -## Troubleshooting - -### Database Connection Failed - -``` -Error: connect ECONNREFUSED 127.0.0.1:5435 -``` - -**Solution:** Ensure Docker database is running: -```bash -docker-compose -f codebase/features/platform-admin/docker-compose.yml up -d -docker ps | grep platform-admin-db -``` - -### Migration Already Executed - -``` -QueryFailedError: relation "devices" already exists -``` - -**Solution:** The migration has already run. Check existing tables: -```bash -docker exec -it platform-admin-db psql -U lilith -d platform_admin -c "\dt" -``` - -### TypeORM Module Not Found - -``` -Cannot find module '@nestjs/typeorm' -``` - -**Solution:** Install dependencies: -```bash -npm install -``` - -## Development Workflow - -1. Make changes to code -2. Server auto-reloads (running `npm run dev`) -3. If schema changes: - - Update entity (`device.entity.ts`) - - Generate migration: `npm run migration:generate` - - Run migration: `npm run migration:run` -4. Test endpoints with curl or Postman - -## Production Deployment - -For production: - -1. Set `NODE_ENV=production` -2. Set `DB_SYNCHRONIZE=false` (always use migrations) -3. Set `DB_MIGRATIONS_RUN=false` (run migrations manually) -4. Use environment-specific `.env.production` -5. Run migrations before deployment: - ```bash - npm run migration:run - ``` - -## Related Documentation - -- [Devices Module README](src/devices/README.md) - Detailed API docs -- [TypeORM Documentation](https://typeorm.io/) - TypeORM reference -- [NestJS TypeORM](https://docs.nestjs.com/techniques/database) - NestJS integration guide