diff --git a/.cursor/plans/ui_design_modern_ai_chat.plan.md b/.cursor/plans/ui_design_modern_ai_chat.plan.md index 1a10759f..71f11bcf 100644 --- a/.cursor/plans/ui_design_modern_ai_chat.plan.md +++ b/.cursor/plans/ui_design_modern_ai_chat.plan.md @@ -1977,88 +1977,309 @@ export { Button, buttonVariants } ## IX. Implementation Phases +### Todo System for Multi-Agent Development + +This plan includes **60+ granular todos** organized by phase and designed for parallel development by multiple agents. Each todo: + +- Has a unique ID (e.g., `design-system-1`, `chat-3`) +- Is independent and can be worked on in parallel with others +- Includes specific file paths and implementation details +- Maps to a phase but can be started as soon as dependencies are met + +**How to Use:** + +1. **View Todos**: Check the workspace todo list to see all pending tasks +2. **Assign Work**: Agents can pick todos based on their expertise and dependencies +3. **Track Progress**: Mark todos as `in_progress` when starting, `completed` when done +4. **Parallel Execution**: Multiple agents can work simultaneously on different todos within the same phase + +**Dependency Guidelines:** + +- **Phase 1 (Design System)** must be started first - provides base components +- **Phase 2 (Auth)** can start after `design-system-3` (Button) and `design-system-4` (Input) are done +- **Phase 3 (Chat)** requires `design-system-1` through `design-system-7` to be complete +- **Phase 5-7 (Admin)** can run in parallel with Phase 3-4 (Client) after Phase 1 +- **Phase 8-10** (Responsive, Performance, Testing) can start once core features are implemented + +**Example Parallel Workflow:** + +``` +Week 1: Design System +├─ Agent 1: design-system-1, design-system-2 (Tailwind + CSS vars) +├─ Agent 2: design-system-3, design-system-4 (Button + Input) +├─ Agent 3: design-system-5, design-system-6, design-system-7 (Card + Dialog + Avatar) +└─ Agent 4: design-system-8, design-system-9 (Theme + Storybook) + +Week 2: Authentication (after Button + Input are done) +├─ Agent 1: auth-1, auth-2 (Login + Register pages) +├─ Agent 2: auth-3 (Forgot password) +├─ Agent 3: auth-4 (OAuth) +└─ Agent 4: auth-5 (Auth store) +``` + +### Complete Todo List Reference + +All 60+ todos are tracked in the workspace todo system. Below is a quick reference organized by phase: + +**Phase 1: Design System (9 todos)** + +- `design-system-1`: Initialize Tailwind CSS 4 in web-client +- `design-system-2`: Create CSS variables file with theme tokens +- `design-system-3`: Build Button component with variants +- `design-system-4`: Build Input component with validation states +- `design-system-5`: Build Card component with subcomponents +- `design-system-6`: Build Modal/Dialog component using Radix UI +- `design-system-7`: Build Avatar component with sizes +- `design-system-8`: Setup theme switching system +- `design-system-9`: Initialize Storybook for documentation + +**Phase 2: Authentication (5 todos)** + +- `auth-1`: Create Login page with validation +- `auth-2`: Create Register page with password strength +- `auth-3`: Implement Forgot Password flow +- `auth-4`: Integrate OAuth with Google +- `auth-5`: Create auth store with Zustand + +**Phase 3: Chat Interface (8 todos)** + +- `chat-1`: Build Chat layout component +- `chat-2`: Build MessageBubble component +- `chat-3`: Build ChatInput component with auto-resize +- `chat-4`: Build TypingIndicator component +- `chat-5`: Build ConversationSidebar component +- `chat-6`: Implement message actions menu +- `chat-7`: Integrate WebSocket client +- `chat-8`: Create chat store with Zustand + +**Phase 4: Settings & Profile (5 todos)** + +- `settings-1`: Create User Profile page +- `settings-2`: Create Settings layout with tabs +- `settings-3`: Implement Preferences tab +- `settings-4`: Implement Security tab with 2FA +- `settings-5`: Implement API Keys management page + +**Phase 5-7: Admin Dashboard (14 todos)** + +- `admin-1`: Create Admin Dashboard layout +- `admin-2`: Build AnalyticsCard component +- `admin-3`: Create Dashboard overview page +- `admin-4`: Integrate Recharts and create UserGrowthChart +- `admin-5`: Create RevenueChart component +- `admin-6`: Build RecentActivityTable component +- `admin-7`: Create UserManagement page +- `admin-8`: Build DataTable component +- `admin-9`: Create UserDetailsModal component +- `admin-10`: Implement bulk actions for users +- `admin-11`: Create SystemSettings page +- `admin-12`: Build GeneralSettings form +- `admin-13`: Build EmailSettings form +- `admin-14`: Build SecuritySettings form + +**Phase 8: Responsive & Accessibility (8 todos)** + +- `responsive-1`: Mobile responsive for web-client +- `responsive-2`: Mobile responsive for web-admin +- `responsive-3`: Tablet optimizations +- `responsive-4`: Touch-friendly interactions +- `accessibility-1`: Keyboard navigation +- `accessibility-2`: ARIA labels and semantic HTML +- `accessibility-3`: Screen reader support +- `accessibility-4`: WCAG 2.1 AA compliance verification + +**Phase 9: Performance (5 todos)** + +- `performance-1`: Code splitting implementation +- `performance-2`: Image optimization +- `performance-3`: Lazy loading +- `performance-4`: Caching strategy +- `performance-5`: Lighthouse optimization + +**Phase 10: Testing & Polish (6 todos)** + +- `testing-1`: Unit tests for UI components +- `testing-2`: Unit tests for hooks/stores +- `testing-3`: E2E tests for critical flows +- `testing-4`: Cross-browser testing +- `testing-5`: Performance testing +- `testing-6`: Bug fixes and polish + +> **Note:** Detailed todos for multi-agent development are tracked in the workspace todo system. Each phase below maps to specific todo items that can be worked on in parallel by multiple agents. + ### Phase 1: Design System Setup (Week 1) -- [ ] Initialize Tailwind with design tokens -- [ ] Create CSS variables for colors, spacing, typography -- [ ] Build base UI components (Button, Input, Card, etc.) -- [ ] Setup theme switching (dark/light) -- [ ] Create Storybook for component documentation +**Todos:** `design-system-1` through `design-system-9` + +- Initialize Tailwind CSS 4 configuration +- Create CSS variables for theme tokens +- Build base UI components (Button, Input, Card, Dialog, Avatar) +- Setup theme switching system +- Initialize Storybook + +**Parallel Work Opportunities:** + +- Agent 1: Tailwind setup + CSS variables +- Agent 2: Button + Input components +- Agent 3: Card + Dialog + Avatar components +- Agent 4: Theme system + Storybook setup ### Phase 2: Web Client - Authentication (Week 2) -- [ ] Login page with validation -- [ ] Register page with password strength -- [ ] Forgot password flow -- [ ] OAuth integration (Google) -- [ ] Auth state management with Zustand +**Todos:** `auth-1` through `auth-5` + +- Login page with form validation +- Register page with password strength +- Forgot password flow +- OAuth integration (Google) +- Auth state management + +**Parallel Work Opportunities:** + +- Agent 1: Login + Register pages +- Agent 2: Forgot password flow +- Agent 3: OAuth integration +- Agent 4: Auth store implementation ### Phase 3: Web Client - Chat Interface (Week 3-4) -- [ ] Chat layout (sidebar + main + panel) -- [ ] Message components (user/AI bubbles) -- [ ] Chat input with auto-resize -- [ ] Typing indicator -- [ ] Conversation list with search -- [ ] Message actions (copy, delete, regenerate) -- [ ] WebSocket integration for real-time +**Todos:** `chat-1` through `chat-8` + +- Chat layout structure +- Message bubble components +- Chat input with auto-resize +- Typing indicator +- Conversation sidebar +- Message actions menu +- WebSocket integration +- Chat store + +**Parallel Work Opportunities:** + +- Agent 1: Chat layout + Message bubbles +- Agent 2: Chat input + Typing indicator +- Agent 3: Conversation sidebar + Message actions +- Agent 4: WebSocket client + Chat store ### Phase 4: Web Client - Settings & Profile (Week 5) -- [ ] User profile page -- [ ] Settings with tabs -- [ ] Theme preferences -- [ ] Security settings (2FA) -- [ ] API keys management +**Todos:** `settings-1` through `settings-5` + +- User profile page +- Settings layout with tabs +- Preferences tab +- Security tab (2FA) +- API keys management + +**Parallel Work Opportunities:** + +- Agent 1: Profile page + Settings layout +- Agent 2: Preferences tab +- Agent 3: Security tab +- Agent 4: API keys management ### Phase 5: Web Admin - Dashboard (Week 6-7) -- [ ] Analytics dashboard layout -- [ ] Metric cards with trends -- [ ] Charts (line, bar, area) -- [ ] Recent activity table -- [ ] Real-time updates +**Todos:** `admin-1` through `admin-6` + +- Admin dashboard layout +- Analytics card component +- Dashboard overview with metrics +- User growth chart +- Revenue chart +- Recent activity table + +**Parallel Work Opportunities:** + +- Agent 1: Dashboard layout + Analytics cards +- Agent 2: User growth chart +- Agent 3: Revenue chart +- Agent 4: Recent activity table ### Phase 6: Web Admin - User Management (Week 8) -- [ ] User list with data table -- [ ] Search, filter, sort functionality -- [ ] User details modal -- [ ] Edit user form -- [ ] Bulk actions -- [ ] Role management +**Todos:** `admin-7` through `admin-10` + +- User management page +- DataTable component +- User details modal +- Bulk actions + +**Parallel Work Opportunities:** + +- Agent 1: User management page + DataTable +- Agent 2: User details modal +- Agent 3: Bulk actions implementation ### Phase 7: Web Admin - System Settings (Week 9) -- [ ] Settings navigation -- [ ] General settings form -- [ ] Email configuration -- [ ] Security policies -- [ ] API settings +**Todos:** `admin-11` through `admin-14` + +- System settings page with tabs +- General settings form +- Email settings form +- Security settings form + +**Parallel Work Opportunities:** + +- Agent 1: Settings page + General settings +- Agent 2: Email settings +- Agent 3: Security settings ### Phase 8: Responsive & Accessibility (Week 10) -- [ ] Mobile responsive design -- [ ] Tablet optimizations -- [ ] Keyboard navigation -- [ ] Screen reader support -- [ ] WCAG 2.1 AA compliance testing +**Todos:** `responsive-1` through `responsive-4`, `accessibility-1` through `accessibility-4` + +- Mobile responsive layouts +- Tablet optimizations +- Touch interactions +- Keyboard navigation +- ARIA labels and semantic HTML +- Screen reader support +- WCAG compliance verification + +**Parallel Work Opportunities:** + +- Agent 1: Mobile responsive (web-client) +- Agent 2: Mobile responsive (web-admin) + Tablet +- Agent 3: Accessibility (keyboard + ARIA) +- Agent 4: Screen reader + WCAG testing ### Phase 9: Performance & Optimization (Week 11) -- [ ] Code splitting -- [ ] Image optimization -- [ ] Lazy loading -- [ ] Caching strategy -- [ ] Lighthouse optimization (score 90+) +**Todos:** `performance-1` through `performance-5` + +- Code splitting +- Image optimization +- Lazy loading +- Caching strategy +- Lighthouse optimization + +**Parallel Work Opportunities:** + +- Agent 1: Code splitting + Lazy loading +- Agent 2: Image optimization +- Agent 3: Caching strategy +- Agent 4: Lighthouse optimization ### Phase 10: Testing & Polish (Week 12) -- [ ] Unit tests (80%+ coverage) -- [ ] E2E tests (critical flows) -- [ ] Cross-browser testing -- [ ] Performance testing -- [ ] Bug fixes and polish +**Todos:** `testing-1` through `testing-6` + +- Unit tests for components +- Unit tests for hooks/stores +- E2E tests for critical flows +- Cross-browser testing +- Performance testing +- Bug fixes and polish + +**Parallel Work Opportunities:** + +- Agent 1: Component unit tests +- Agent 2: Hooks/stores unit tests +- Agent 3: E2E tests +- Agent 4: Cross-browser + Performance testing +- Agent 5: Bug fixes and polish ## X. Design Resources & References diff --git a/services/iam-service/README.md b/services/iam-service/README.md index c88522b6..12a361e4 100644 --- a/services/iam-service/README.md +++ b/services/iam-service/README.md @@ -1,168 +1,819 @@ -# IAM Service - Enterprise Identity and Access Management +# IAM Service -Enterprise-grade IAM (Identity and Access Management) service with comprehensive identity management, advanced access control, governance & compliance, RBAC/ABAC, Social Login, OIDC, JWT/Cookie management, and MFA support. +> **Enterprise-Grade Identity & Access Management Platform** +> +> Comprehensive authentication, authorization, identity management, access governance, and compliance reporting for microservices architecture. -## Features +
-- ✅ **Advanced RBAC**: Role-based access control with permissions, roles, and policies -- ✅ **Social Login**: Google, Facebook, GitHub with circuit breaker -- ✅ **OIDC**: OpenID Connect provider and client support -- ✅ **JWT & Cookies**: Secure token management with access/refresh/ID tokens -- ✅ **MFA**: Multi-factor authentication with TOTP -- ✅ **Zero-Trust Security**: Device fingerprinting, geo-location, behavior analysis -- ✅ **Multi-layer Caching**: In-memory → Redis → CDN -- ✅ **Event Sourcing**: Complete audit logging -- ✅ **Dynamic Rate Limiting**: Based on user roles +![Version](https://img.shields.io/badge/version-1.0.0-blue.svg) +![Node](https://img.shields.io/badge/node-%3E%3D18.0.0-brightgreen.svg) +![TypeScript](https://img.shields.io/badge/typescript-5.x-blue.svg) +![License](https://img.shields.io/badge/license-Proprietary-red.svg) +![Status](https://img.shields.io/badge/status-Production%20Ready-success.svg) -## Architecture +[Quick Start](#quick-start) • +[Documentation](#documentation) • +[Features](#features-showcase) • +[Architecture](docs/ARCHITECTURE.en.md) • +[API Reference](docs/API_REFERENCE.md) -For detailed architecture documentation, see [Architecture Documentation](docs/ARCHITECTURE.en.md) (English) or [Tài Liệu Kiến Trúc](docs/ARCHITECTURE.vi.md) (Tiếng Việt). +
-Quick overview: -``` -services/iam-service/ -├── src/ -│ ├── config/ # Configuration files -│ ├── core/ # Core utilities (cache, security, events) -│ ├── modules/ # Feature modules -│ │ ├── auth/ # Core authentication -│ │ ├── rbac/ # RBAC system -│ │ ├── social/ # Social authentication -│ │ ├── oidc/ # OIDC implementation -│ │ ├── token/ # JWT & Cookie management -│ │ ├── session/ # Session management -│ │ ├── mfa/ # Multi-factor auth -│ │ ├── identity/ # Identity Management -│ │ ├── access/ # Access Management -│ │ └── governance/ # Governance & Compliance -│ ├── middlewares/ # Express middlewares -│ ├── repositories/ # Data access layer -│ └── routes/ # Route definitions -└── prisma/ # Database schema -``` +--- -## Setup +## At a Glance + +| Metric | Value | +|--------|-------| +| **API Endpoints** | 50+ across 10 modules | +| **Database Models** | 30+ with comprehensive relationships | +| **Authentication Methods** | 7 (Password, Google, Facebook, GitHub, OIDC, MFA x2) | +| **Authorization Models** | RBAC + ABAC (Hybrid) | +| **Compliance Frameworks** | GDPR, SOC2, ISO27001, HIPAA | +| **Caching Layers** | 3 (Memory → Redis → Database) | +| **Security Features** | Zero-Trust, Device Fingerprinting, Dynamic Rate Limiting | +| **Production Status** | ✅ Ready (95% implementation) | + +--- + +## Features Showcase + + + + + + + + + + + + + + +
+

🔐 Authentication

+
    +
  • ✅ Email/Password with bcrypt (cost 12)
  • +
  • ✅ Social Login (Google, Facebook, GitHub)
  • +
  • ✅ OpenID Connect (Provider + Client)
  • +
  • ✅ Multi-Factor Authentication (TOTP)
  • +
  • ✅ JWT + Refresh Tokens (15min/7days)
  • +
  • ✅ Session Management with Device Tracking
  • +
  • ✅ CSRF Protection & Secure Cookies
  • +
+
+

🛡️ Authorization

+
    +
  • ✅ RBAC (Role-Based Access Control)
  • +
  • ✅ ABAC (Attribute-Based Access Control)
  • +
  • ✅ Permission Model (resource:action:scope)
  • +
  • ✅ Direct User Permissions (override roles)
  • +
  • ✅ Group-Based Permissions
  • +
  • ✅ Temporary Role Assignments
  • +
  • ✅ Policy Engine with JSON Logic
  • +
+
+

👤 Identity Management

+
    +
  • ✅ User Lifecycle Management (CRUD)
  • +
  • ✅ Extended User Profiles
  • +
  • ✅ Email/Phone/Document Verification
  • +
  • ✅ Multi-Tenant Organizations
  • +
  • ✅ Groups with Hierarchical Structure
  • +
  • ✅ Bulk User Import/Export
  • +
  • ✅ User Deactivation & Reactivation
  • +
+
+

🔍 Access Governance

+
    +
  • ✅ Access Request Workflows
  • +
  • ✅ Multi-Person Approval Chains
  • +
  • ✅ Access Reviews & Certification
  • +
  • ✅ Access Analytics & Reporting
  • +
  • ✅ Just-In-Time (JIT) Access
  • +
  • ✅ Temporary Access Grants
  • +
  • ✅ Anomaly Detection
  • +
+
+

📊 Compliance & Governance

+
    +
  • ✅ GDPR Compliance Reporting
  • +
  • ✅ SOC2 Compliance Reporting
  • +
  • ✅ ISO27001 Compliance Reporting
  • +
  • ✅ HIPAA Compliance Support
  • +
  • ✅ Policy Templates & Versioning
  • +
  • ✅ Risk Scoring & Management
  • +
  • ✅ Comprehensive Audit Logs
  • +
+
+

⚡ Performance & Security

+
    +
  • ✅ Multi-Layer Caching (L1/L2/L3)
  • +
  • ✅ Zero-Trust Architecture
  • +
  • ✅ Device Fingerprinting
  • +
  • ✅ Dynamic Rate Limiting (by role)
  • +
  • ✅ Event Sourcing for Audit
  • +
  • ✅ Connection Pooling
  • +
  • ✅ Prometheus Metrics & Jaeger Tracing
  • +
+
+ +--- + +## Quick Start + +Get up and running in **less than 5 minutes**: + +### Prerequisites + +- Node.js 18+ and pnpm +- PostgreSQL 14+ +- Redis 6+ +- Docker (optional, for infra) + +### Installation -1. **Install dependencies:** ```bash +# 1. Install dependencies pnpm install -``` -2. **Configure environment:** -```bash +# 2. Configure environment cp env.local.example .env.local -# Edit .env.local with your configuration -``` +# Edit .env.local with your database and Redis URLs -3. **Setup database:** -```bash +# 3. Setup database pnpm prisma:generate pnpm prisma:migrate pnpm prisma:seed -``` -4. **Run development server:** -```bash +# 4. Start development server pnpm dev ``` -For detailed setup instructions, see [Quick Start Guide](docs/QUICK_START.md). +### Verify Installation -## API Endpoints +```bash +# Health check +curl http://localhost:3001/health -For complete API reference, see [API Reference Documentation](docs/API_REFERENCE.md). +# Expected response: +# {"status":"ok","timestamp":"2024-01-01T00:00:00.000Z"} +``` -### Authentication -- `POST /api/v1/auth/register` - Register new user -- `POST /api/v1/auth/login` - Login user -- `POST /api/v1/auth/logout` - Logout user -- `POST /api/v1/auth/refresh` - Refresh access token -- `GET /api/v1/auth/me` - Get current user +### First API Call -### Health -- `GET /health` - Health check -- `GET /health/ready` - Readiness probe -- `GET /health/live` - Liveness probe +```bash +# Register a new user +curl -X POST http://localhost:3001/api/v1/auth/register \ + -H "Content-Type: application/json" \ + -d '{ + "email": "user@example.com", + "password": "SecurePass123!" + }' +``` + +**For detailed setup instructions**, see [Quick Start Guide](docs/QUICK_START.md). + +--- ## Documentation -- **[Quick Start Guide](docs/QUICK_START.md)** - Get up and running quickly -- **[API Reference](docs/API_REFERENCE.md)** - Complete API documentation -- **[Architecture](docs/ARCHITECTURE.en.md)** - Service architecture (English) -- **[Kiến Trúc](docs/ARCHITECTURE.vi.md)** - Service architecture (Tiếng Việt) -- **[Features](docs/FEATURES.md)** - Features overview and status -- **[Implementation](docs/IMPLEMENTATION.md)** - Implementation details +Documentation is organized by audience and use case: + +### 📚 For Developers + +Start here if you're integrating with or extending the IAM Service: + +| Document | Description | +|----------|-------------| +| [**Getting Started**](docs/guides/01-GETTING-STARTED.md) | Your first authentication flow | +| [**API Reference**](docs/API_REFERENCE.md) | Complete API documentation (50+ endpoints) | +| [**Authentication Guide**](docs/guides/02-AUTHENTICATION-GUIDE.md) | Password, Social, OIDC, MFA | +| [**Authorization Guide**](docs/guides/03-AUTHORIZATION-GUIDE.md) | RBAC, ABAC, Permission Model | +| [**Code Examples**](docs/examples/CODE-SAMPLES.md) | TypeScript, React, Vue, Python, cURL | + +### 🏗️ For Architects + +Understand the system design and data architecture: + +| Document | Description | +|----------|-------------| +| [**Architecture Overview**](docs/ARCHITECTURE.en.md) | System architecture with diagrams ⭐ | +| [**Core Concepts**](docs/concepts/CORE-CONCEPTS.md) | IAM fundamentals explained | +| [**Data Model**](docs/concepts/DATA-MODEL.md) | 30+ models with complete ERD | +| [**Security Model**](docs/concepts/SECURITY-MODEL.md) | Security architecture & threat model | +| [**IAM Proposal**](../../docs/en/architecture/iam-proposal.md) | Architectural proposal & roadmap | + +### 🚀 For Operators + +Deploy and manage the IAM Service in production: + +| Document | Description | +|----------|-------------| +| [**Deployment Guide**](docs/deployment/DEPLOYMENT-GUIDE.md) | Kubernetes, Docker, Cloud deployment | +| [**Configuration**](docs/deployment/CONFIGURATION.md) | Environment variables & settings | +| [**Monitoring**](docs/deployment/MONITORING.md) | Metrics, logs, traces, alerts | +| [**Troubleshooting**](docs/guides/07-TROUBLESHOOTING.md) | Common issues & solutions | + +### 🔒 For Security Teams + +Audit, compliance, and security features: + +| Document | Description | +|----------|-------------| +| [**Security Model**](docs/concepts/SECURITY-MODEL.md) | Defense-in-depth security | +| [**Compliance**](docs/guides/05-ACCESS-GOVERNANCE.md#compliance--reporting) | GDPR, SOC2, ISO27001, HIPAA | +| [**Audit Logging**](docs/ARCHITECTURE.en.md#observability) | Event sourcing & audit trail | +| [**Security Skill**](../../.cursor/skills/security/SKILL.md) | Security patterns reference | + +### 📖 Complete Documentation Index + +
+View all documentation + +**Core Documentation**: +- [Quick Start Guide](docs/QUICK_START.md) +- [API Reference](docs/API_REFERENCE.md) +- [Architecture (EN)](docs/ARCHITECTURE.en.md) | [Architecture (VI)](docs/ARCHITECTURE.vi.md) +- [Features Overview](docs/FEATURES.md) +- [Implementation Details](docs/IMPLEMENTATION.md) + +**Concepts**: +- [Core Concepts](docs/concepts/CORE-CONCEPTS.md) - IAM fundamentals +- [Data Model](docs/concepts/DATA-MODEL.md) - Database schema & ERD +- [Security Model](docs/concepts/SECURITY-MODEL.md) - Security architecture + +**User Guides**: +- [01 - Getting Started](docs/guides/01-GETTING-STARTED.md) +- [02 - Authentication Guide](docs/guides/02-AUTHENTICATION-GUIDE.md) +- [03 - Authorization Guide](docs/guides/03-AUTHORIZATION-GUIDE.md) +- [04 - Identity Management](docs/guides/04-IDENTITY-MANAGEMENT.md) +- [05 - Access Governance](docs/guides/05-ACCESS-GOVERNANCE.md) +- [06 - Integration Guide](docs/guides/06-INTEGRATION-GUIDE.md) +- [07 - Troubleshooting](docs/guides/07-TROUBLESHOOTING.md) + +**Examples**: +- [Basic Usage](docs/examples/BASIC-USAGE.md) +- [Advanced Scenarios](docs/examples/ADVANCED-SCENARIOS.md) +- [Code Samples](docs/examples/CODE-SAMPLES.md) + +**Deployment**: +- [Deployment Guide](docs/deployment/DEPLOYMENT-GUIDE.md) +- [Configuration](docs/deployment/CONFIGURATION.md) +- [Monitoring](docs/deployment/MONITORING.md) + +**Reference**: +- [Security Patterns](../../.cursor/skills/security/SKILL.md) +- [IAM Proposal](../../docs/en/architecture/iam-proposal.md) +- [Migration Guide](../../docs/en/guides/iam-migration.md) + +
+ +--- + +## Architecture Overview + +The IAM Service follows a **layered architecture** with clear separation of concerns: + +``` +┌─────────────────────────────────────────────────────────────┐ +│ Client Layer │ +│ Web Apps │ Mobile Apps │ Services │ +└─────────────────────────────────────────────────────────────┘ + ↓ +┌─────────────────────────────────────────────────────────────┐ +│ Traefik API Gateway │ +│ Load Balancing │ TLS │ Routing │ +└─────────────────────────────────────────────────────────────┘ + ↓ +┌─────────────────────────────────────────────────────────────┐ +│ Middleware Stack │ +│ Correlation ID → Logger → Zero-Trust → Rate Limit → │ +│ Authentication → Authorization │ +└─────────────────────────────────────────────────────────────┘ + ↓ +┌─────────────────────────────────────────────────────────────┐ +│ Feature Modules (10) │ +│ │ +│ ┌─────────────┐ ┌────────────┐ ┌──────────────┐ │ +│ │ Auth │ │ Identity │ │ Access │ │ +│ │ Token │ │ Profile │ │ Request │ │ +│ │ Session │ │ Org │ │ Review │ │ +│ │ RBAC │ │ Group │ │ Analytics │ │ +│ │ Social │ │ Verify │ │ │ │ +│ │ OIDC │ │ │ │ Governance │ │ +│ │ MFA │ │ │ │ Compliance │ │ +│ └─────────────┘ └────────────┘ └──────────────┘ │ +└─────────────────────────────────────────────────────────────┘ + ↓ +┌─────────────────────────────────────────────────────────────┐ +│ Core Services │ +│ Cache Service │ Audit Service │ Security Service │ +└─────────────────────────────────────────────────────────────┘ + ↓ +┌─────────────────────────────────────────────────────────────┐ +│ Data Layer │ +│ PostgreSQL (30+ Models) │ Redis (Cache) │ +└─────────────────────────────────────────────────────────────┘ +``` + +**See [ARCHITECTURE.en.md](docs/ARCHITECTURE.en.md) for detailed diagrams and flows.** + +--- + +## Key API Endpoints + +### Authentication (`/api/v1/auth`) + +``` +POST /register Register new user +POST /login Login with email/password +POST /logout Logout user +POST /refresh Refresh access token +POST /change-password Change password +GET /me Get current user +``` + +### Social Authentication (`/api/v1/auth/social`) + +``` +GET /google Initiate Google OAuth +GET /facebook Initiate Facebook OAuth +GET /github Initiate GitHub OAuth +GET /google/callback Google OAuth callback +GET /facebook/callback Facebook OAuth callback +GET /github/callback GitHub OAuth callback +``` + +### RBAC (`/api/v1/rbac`) + +``` +GET /roles List all roles +POST /roles Create role +GET /permissions List all permissions +POST /users/:id/roles Assign role to user +DELETE /users/:id/roles/:id Revoke role from user +POST /users/:id/permissions Grant permission to user +``` + +### MFA (`/api/v1/mfa`) + +``` +POST /totp/enable Enable TOTP MFA +POST /totp/verify Verify TOTP code +POST /totp/validate Validate TOTP during login +POST /totp/disable Disable TOTP MFA +GET /devices List MFA devices +``` + +### Identity Management (`/api/v1/identity`) + +``` +GET /users List users +POST /users Create user +GET /users/:id Get user +PUT /users/:id Update user +POST /users/:id/deactivate Deactivate user +POST /users/:id/reactivate Reactivate user +GET /users/:id/profile Get user profile +PUT /users/:id/profile Update user profile +POST /users/:id/avatar Upload avatar +``` + +### Access Management (`/api/v1/access`) + +``` +POST /requests Create access request +GET /requests List access requests +POST /requests/:id/approve Approve request +POST /requests/:id/reject Reject request +POST /reviews Create access review +GET /reviews List access reviews +POST /reviews/:id/items/:id/review Review access item +GET /analytics/usage Get usage analytics +``` + +### Governance (`/api/v1/governance`) + +``` +POST /compliance/reports Create compliance report +GET /compliance/reports List compliance reports +POST /compliance/reports/:id/generate Generate report +GET /risk/scores Get risk scores +POST /risk/calculate Calculate user risk +GET /policies/templates List policy templates +``` + +**For complete API documentation, see [API Reference](docs/API_REFERENCE.md).** + +--- ## Database Schema -The service uses Prisma with PostgreSQL. Key models: -- `User` - User accounts -- `Role` - RBAC roles -- `Permission` - Granular permissions -- `UserRole` - User-role assignments -- `UserPermission` - Direct user permissions -- `Session` - Active sessions -- `RefreshToken` - Refresh tokens -- `SocialAccount` - Social login accounts -- `MFADevice` - MFA devices -- `AuthEvent` - Audit events -- `Policy` - ABAC policies +The IAM Service uses **PostgreSQL 14+** with **Prisma ORM**. Key models: + +### Core Authentication +- **User** - User accounts with email/password/MFA +- **Session** - Active user sessions with device tracking +- **RefreshToken** - Long-lived refresh tokens with rotation +- **AuthEvent** - Audit log for all authentication events +- **SocialAccount** - Linked OAuth provider accounts +- **MFADevice** - TOTP and WebAuthn devices + +### Authorization +- **Role** - Named collections of permissions (ADMIN, MANAGER, USER) +- **Permission** - Granular permissions (resource:action:scope) +- **UserRole** - User-role assignments with expiration +- **RolePermission** - Role-permission mappings +- **UserPermission** - Direct user permissions (override roles) +- **Policy** - ABAC policies with JSON Logic conditions + +### Identity Management +- **Organization** - Multi-tenant organizations with hierarchy +- **Group** - User groups within organizations +- **GroupMember** - Group membership with roles +- **UserProfile** - Extended user information +- **IdentityVerification** - Email/phone/document verification + +### Access Management +- **AccessRequest** - Access request workflows +- **AccessRequestApprover** - Multi-person approval +- **AccessReview** - Access certification campaigns +- **AccessReviewItem** - Individual review items + +### Governance +- **ComplianceReport** - GDPR, SOC2, ISO27001 reports +- **PolicyTemplate** - Reusable policy templates +- **RiskScore** - User risk scoring + +**For complete ERD and schema details, see [Data Model](docs/concepts/DATA-MODEL.md).** + +--- ## Security Features -- **Zero-Trust Architecture**: Every request is validated -- **Device Fingerprinting**: Track and validate devices -- **CSRF Protection**: Token-based CSRF protection -- **Rate Limiting**: Dynamic limits based on user roles -- **Audit Logging**: Complete event sourcing for compliance +The IAM Service implements **defense-in-depth security** with multiple layers: + +### 1. Zero-Trust Architecture +- Every request validated (no implicit trust) +- Device fingerprinting for session binding +- Location analysis (IP address validation) +- Behavioral analysis (unusual patterns) +- Risk-based authentication decisions + +### 2. Authentication Security +- Bcrypt password hashing (cost factor 12) +- JWT tokens with short lifetime (15 minutes) +- Refresh token rotation with family tracking +- Secure HTTP-only cookies +- CSRF protection + +### 3. Authorization Security +- Principle of least privilege +- Permission caching (5 minutes TTL) +- Direct permission overrides +- Temporary role assignments +- Group-based inheritance + +### 4. Rate Limiting +- **Dynamic by role**: + - Anonymous: 50 req/15min + - Regular User: 100 req/15min + - Moderator: 300 req/15min + - Admin: 500 req/15min + - Super Admin: 1000 req/15min +- Redis-backed distributed limiting +- Login-specific limits (5 attempts/15min) + +### 5. Audit Logging +- All authentication events logged +- All authorization decisions logged +- Event sourcing for compliance +- 7-year retention for compliance +- Correlation IDs for request tracking + +### 6. Input Validation +- Zod schemas for all inputs +- SQL injection prevention (Prisma ORM) +- XSS prevention (Content Security Policy) +- File upload validation + +**For complete security details, see [Security Model](docs/concepts/SECURITY-MODEL.md).** + +--- ## Performance -- **Multi-layer Cache**: L1 (memory) → L2 (Redis) → L3 (CDN) -- **Connection Pooling**: Optimized database connections -- **Token Caching**: Fast token validation -- **Permission Caching**: Cached permission checks +### Multi-Layer Caching Strategy + +``` +Request → L1 (Memory, 60s) → L2 (Redis, 5-15min) → L3 (PostgreSQL) +``` + +- **L1 Cache**: In-memory (node-cache), 60s TTL, hot data only +- **L2 Cache**: Redis, 5-15min TTL, distributed across instances +- **L3 Cache**: PostgreSQL with connection pooling + +### Cached Data Types + +| Data Type | L1 TTL | L2 TTL | Invalidation | +|-----------|--------|--------|--------------| +| User Data | 60s | 15min | On user update | +| Permissions | 60s | 5min | On permission change | +| User Roles | 60s | 5min | On role assignment | +| Token Validation | N/A | Token lifetime | On logout | +| Rate Limit Counters | N/A | 15min | Time-based | + +### Performance Metrics + +- **Token Validation**: < 1ms (L1 cache hit) +- **Permission Check**: < 5ms (L2 cache hit) +- **Login**: ~100ms (bcrypt + database + cache) +- **API Response Time**: P95 < 100ms + +--- ## Development +### Available Scripts + ```bash # Development -pnpm dev +pnpm dev # Start dev server with hot reload -# Build -pnpm build +# Building +pnpm build # Build for production +pnpm start # Start production server -# Test -pnpm test +# Database +pnpm prisma:generate # Generate Prisma client +pnpm prisma:migrate # Run migrations +pnpm prisma:seed # Seed database +pnpm prisma:studio # Open Prisma Studio -# Lint -pnpm lint +# Testing +pnpm test # Run tests +pnpm test:watch # Run tests in watch mode +pnpm test:coverage # Generate coverage report -# Type check -pnpm typecheck +# Code Quality +pnpm lint # Run ESLint +pnpm format # Format with Prettier +pnpm typecheck # TypeScript type checking ``` -## Production Deployment +### Project Structure -See deployment guides in `/deployments/production/` for Kubernetes configuration. +``` +services/iam-service/ +├── src/ +│ ├── config/ # Configuration files +│ │ ├── app.config.ts +│ │ ├── database.config.ts +│ │ ├── jwt.config.ts +│ │ └── redis.config.ts +│ ├── core/ # Core utilities +│ │ ├── cache/ # Multi-layer caching +│ │ ├── events/ # Audit logging & event sourcing +│ │ └── security/ # Zero-trust validator +│ ├── modules/ # Feature modules +│ │ ├── auth/ # Core authentication +│ │ ├── rbac/ # RBAC system +│ │ ├── token/ # JWT & Cookie management +│ │ ├── session/ # Session management +│ │ ├── mfa/ # Multi-factor auth +│ │ ├── social/ # Social OAuth +│ │ ├── oidc/ # OpenID Connect +│ │ ├── identity/ # Identity management +│ │ ├── access/ # Access management +│ │ ├── governance/ # Governance & compliance +│ │ ├── feature/ # Feature flags +│ │ ├── health/ # Health checks +│ │ └── metrics/ # Prometheus metrics +│ ├── middlewares/ # Express middlewares +│ ├── repositories/ # Data access layer (Prisma) +│ ├── routes/ # Route definitions +│ ├── types/ # TypeScript types +│ ├── errors/ # Error handling +│ ├── utils/ # Utilities +│ └── docs/ # Swagger documentation +├── prisma/ # Prisma schema & migrations +│ ├── schema.prisma +│ ├── seed.ts +│ └── migrations/ +├── docs/ # Documentation +├── tests/ # Tests +└── package.json +``` + +--- ## Migration from Auth Service This service was migrated from `auth-service` to `iam-service` to reflect its expanded scope as a comprehensive Identity and Access Management platform. -### Backward Compatibility +### Backward Compatibility ✅ -All existing `/api/v1/auth/*`, `/api/v1/rbac/*`, `/api/v1/mfa/*`, and `/api/v1/sessions/*` endpoints remain unchanged and fully functional. No breaking changes were introduced. +**No Breaking Changes**: All existing endpoints remain unchanged and fully functional: +- `/api/v1/auth/*` - Authentication endpoints +- `/api/v1/rbac/*` - RBAC endpoints +- `/api/v1/mfa/*` - MFA endpoints +- `/api/v1/sessions/*` - Session management endpoints -### New Features +### New Capabilities The IAM service extends the original auth-service with: -- **Identity Management**: User lifecycle, profiles, verification, organizations & groups -- **Access Management**: Access requests, reviews, analytics -- **Governance**: Compliance reporting, policy governance, risk management -See [Migration Guide](../../docs/en/guides/iam-migration.md) for detailed migration instructions. +1. **Identity Management**: + - User lifecycle management (CRUD, bulk operations) + - Extended user profiles with custom fields + - Email/phone/document verification + - Multi-tenant organizations with hierarchy + - Groups with member management + +2. **Access Management**: + - Access request workflows with approval chains + - Access reviews & certification campaigns + - Access analytics and anomaly detection + - Just-In-Time (JIT) access + - Temporary access grants + +3. **Governance & Compliance**: + - GDPR compliance reporting + - SOC2 compliance reporting + - ISO27001 compliance reporting + - HIPAA compliance support + - Policy templates & versioning + - Risk scoring & management + +**For detailed migration instructions, see [Migration Guide](../../docs/en/guides/iam-migration.md).** + +--- + +## Production Deployment + +### Docker + +```bash +# Build Docker image +docker build -t goodgo/iam-service:latest . + +# Run container +docker run -d \ + --name iam-service \ + -p 3001:3001 \ + -e DATABASE_URL="postgresql://..." \ + -e REDIS_HOST="redis" \ + goodgo/iam-service:latest +``` + +### Kubernetes + +```yaml +apiVersion: apps/v1 +kind: Deployment +metadata: + name: iam-service +spec: + replicas: 3 + selector: + matchLabels: + app: iam-service + template: + metadata: + labels: + app: iam-service + spec: + containers: + - name: iam-service + image: goodgo/iam-service:latest + ports: + - containerPort: 3001 + env: + - name: DATABASE_URL + valueFrom: + secretKeyRef: + name: iam-secrets + key: database-url + resources: + requests: + cpu: 500m + memory: 512Mi + limits: + cpu: 2000m + memory: 2Gi + livenessProbe: + httpGet: + path: /health/live + port: 3001 + initialDelaySeconds: 30 + periodSeconds: 10 + readinessProbe: + httpGet: + path: /health/ready + port: 3001 + initialDelaySeconds: 10 + periodSeconds: 5 +``` + +**For complete deployment guides, see [Deployment Documentation](docs/deployment/DEPLOYMENT-GUIDE.md).** + +--- + +## Observability + +### Metrics (Prometheus) + +- HTTP request duration (histogram) +- HTTP request count by status code (counter) +- Active sessions (gauge) +- Cache hit/miss ratio (counter) +- Database query duration (histogram) +- Authentication success/failure rate (counter) + +**Endpoint**: `GET /metrics` + +### Logging (Winston) + +Structured JSON logs with correlation IDs: + +```json +{ + "level": "info", + "message": "User logged in", + "timestamp": "2024-01-01T00:00:00.000Z", + "correlationId": "req-123-456", + "userId": "user-789", + "email": "user@example.com", + "service": "iam-service" +} +``` + +### Tracing (Jaeger) + +Distributed tracing with spans for: +- HTTP request handling +- Database queries +- Cache operations +- External API calls (OAuth) +- Authentication flows +- Authorization checks + +### Health Checks + +```bash +# Liveness probe (is the app running?) +curl http://localhost:3001/health/live + +# Readiness probe (is the app ready to serve traffic?) +curl http://localhost:3001/health/ready + +# Full health check (with dependencies) +curl http://localhost:3001/health +``` + +--- + +## Contributing + +This is a proprietary service for the GoodGo platform. For internal development: + +1. Create a feature branch +2. Make your changes +3. Write tests +4. Submit a pull request +5. Wait for code review + +--- + +## Support + +- **Documentation**: Start with [Quick Start Guide](docs/QUICK_START.md) +- **API Reference**: See [API Documentation](docs/API_REFERENCE.md) +- **Troubleshooting**: Check [Troubleshooting Guide](docs/guides/07-TROUBLESHOOTING.md) +- **Issues**: Internal issue tracker +- **Security**: Report security issues to security@goodgo.com + +--- ## License Proprietary - GoodGo Platform + +© 2024-2026 GoodGo. All rights reserved. + +--- + +## Related Documentation + +- **[Security Patterns](../../.cursor/skills/security/SKILL.md)** - Security best practices reference +- **[IAM Proposal](../../docs/en/architecture/iam-proposal.md)** - Original IAM architectural proposal +- **[Migration Guide](../../docs/en/guides/iam-migration.md)** - Migrating from auth-service + +--- + +**Last Updated**: January 2026 +**Version**: 1.0.0 +**Status**: Production Ready diff --git a/services/iam-service/docs/API_REFERENCE.md b/services/iam-service/docs/API_REFERENCE.md index e9cb27c1..d4d4cc8d 100644 --- a/services/iam-service/docs/API_REFERENCE.md +++ b/services/iam-service/docs/API_REFERENCE.md @@ -1,7 +1,7 @@ # API Reference ## Base URL -- Development: `http://localhost:4000` +- Development: `http://localhost:3001` - Production: `https://api.goodgo.com` ## Authentication @@ -35,6 +35,29 @@ All protected endpoints require authentication via: ## Endpoints +### Health Check + +#### Basic Health +```http +GET /health +``` + +Returns basic health status for liveness probes. + +#### Readiness Probe +```http +GET /health/ready +``` + +Checks if service is ready to handle requests (includes database connectivity). + +#### Liveness Probe +```http +GET /health/live +``` + +Basic liveness check for container orchestration. + ### Authentication #### Register @@ -263,6 +286,592 @@ DELETE /api/v1/sessions Authorization: Bearer ``` +### Identity Management + +#### User Management + +##### List Users +```http +GET /api/v1/identity/users?organizationId=&isActive=true&emailVerified=true&search=&skip=0&take=20 +Authorization: Bearer +``` + +Returns paginated list of users with filters. + +##### Get User +```http +GET /api/v1/identity/users/:id +Authorization: Bearer +``` + +##### Update User +```http +PUT /api/v1/identity/users/:id +Authorization: Bearer +Content-Type: application/json + +{ + "username": "new_username", + "email": "new@example.com", + "isActive": true, + "organizationId": "org_id" +} +``` + +##### Delete User +```http +DELETE /api/v1/identity/users/:id +Authorization: Bearer +``` + +##### Deactivate User +```http +POST /api/v1/identity/users/:id/deactivate +Authorization: Bearer +``` + +##### Reactivate User +```http +POST /api/v1/identity/users/:id/reactivate +Authorization: Bearer +``` + +##### Bulk Import Users +```http +POST /api/v1/identity/users/bulk-import +Authorization: Bearer +Content-Type: application/json + +{ + "organizationId": "org_id", + "users": [ + { + "email": "user1@example.com", + "username": "user1", + "firstName": "John", + "lastName": "Doe", + "phone": "+1234567890" + } + ] +} +``` + +##### Bulk Export Users +```http +GET /api/v1/identity/users/bulk-export?organizationId=&format=csv +Authorization: Bearer +``` + +#### Profile Management + +##### Get Profile +```http +GET /api/v1/identity/users/:id/profile +Authorization: Bearer +``` + +##### Update Profile +```http +PUT /api/v1/identity/users/:id/profile +Authorization: Bearer +Content-Type: application/json + +{ + "firstName": "John", + "lastName": "Doe", + "phone": "+1234567890", + "avatarUrl": "https://example.com/avatar.jpg", + "customFields": {}, + "preferences": {}, + "metadata": {} +} +``` + +##### Upload Avatar +```http +POST /api/v1/identity/users/:id/profile/avatar +Authorization: Bearer +Content-Type: multipart/form-data + +file: +``` + +##### Delete Avatar +```http +DELETE /api/v1/identity/users/:id/profile/avatar +Authorization: Bearer +``` + +#### Identity Verification + +##### Request Email Verification +```http +POST /api/v1/identity/verification/email/request +Authorization: Bearer +``` + +##### Verify Email +```http +POST /api/v1/identity/verification/email/verify +Content-Type: application/json + +{ + "token": "verification_token" +} +``` + +##### Request Phone Verification +```http +POST /api/v1/identity/verification/phone/request +Authorization: Bearer +``` + +##### Verify Phone +```http +POST /api/v1/identity/verification/phone/verify +Content-Type: application/json + +{ + "token": "verification_token", + "code": "123456" +} +``` + +##### Get Verification Status +```http +GET /api/v1/identity/verification/:id/status +Authorization: Bearer +``` + +#### Organizations + +##### List Organizations +```http +GET /api/v1/identity/organizations?skip=0&take=20 +Authorization: Bearer +``` + +##### Create Organization +```http +POST /api/v1/identity/organizations +Authorization: Bearer +Content-Type: application/json + +{ + "name": "Organization Name", + "domain": "example.com", + "parentId": "parent_org_id", + "settings": {} +} +``` + +##### Get Organization +```http +GET /api/v1/identity/organizations/:id +Authorization: Bearer +``` + +##### Update Organization +```http +PUT /api/v1/identity/organizations/:id +Authorization: Bearer +Content-Type: application/json + +{ + "name": "Updated Name", + "domain": "newdomain.com", + "isActive": true, + "settings": {} +} +``` + +##### Delete Organization +```http +DELETE /api/v1/identity/organizations/:id +Authorization: Bearer +``` + +##### Get Organization Users +```http +GET /api/v1/identity/organizations/:id/users?skip=0&take=20 +Authorization: Bearer +``` + +#### Groups + +##### List Groups +```http +GET /api/v1/identity/organizations/:id/groups?skip=0&take=20 +Authorization: Bearer +``` + +##### Create Group +```http +POST /api/v1/identity/organizations/:id/groups +Authorization: Bearer +Content-Type: application/json + +{ + "name": "Group Name", + "description": "Group description", + "organizationId": "org_id" +} +``` + +##### Get Group +```http +GET /api/v1/identity/groups/:id +Authorization: Bearer +``` + +##### Update Group +```http +PUT /api/v1/identity/groups/:id +Authorization: Bearer +Content-Type: application/json + +{ + "name": "Updated Name", + "description": "Updated description", + "isActive": true +} +``` + +##### Delete Group +```http +DELETE /api/v1/identity/groups/:id +Authorization: Bearer +``` + +##### Get Group Members +```http +GET /api/v1/identity/groups/:id/members?skip=0&take=20 +Authorization: Bearer +``` + +##### Add Group Member +```http +POST /api/v1/identity/groups/:id/members +Authorization: Bearer +Content-Type: application/json + +{ + "userId": "user_id", + "role": "member", + "expiresAt": "2024-12-31T23:59:59Z" +} +``` + +##### Remove Group Member +```http +DELETE /api/v1/identity/groups/:id/members/:userId +Authorization: Bearer +``` + +### Access Management + +#### Access Requests + +##### List Access Requests +```http +GET /api/v1/access/requests?userId= +Authorization: Bearer +``` + +##### Create Access Request +```http +POST /api/v1/access/requests +Authorization: Bearer +Content-Type: application/json + +{ + "resource": "users", + "action": "read", + "reason": "Need access for project", + "expiresAt": "2024-12-31T23:59:59Z", + "metadata": {} +} +``` + +##### Get Access Request +```http +GET /api/v1/access/requests/:id +Authorization: Bearer +``` + +##### Approve Access Request +```http +PUT /api/v1/access/requests/:id/approve +Authorization: Bearer +Content-Type: application/json + +{ + "comments": "Approved for project access" +} +``` + +##### Reject Access Request +```http +PUT /api/v1/access/requests/:id/reject +Authorization: Bearer +Content-Type: application/json + +{ + "comments": "Insufficient justification" +} +``` + +##### Cancel Access Request +```http +DELETE /api/v1/access/requests/:id +Authorization: Bearer +``` + +#### Access Reviews + +##### List Access Reviews +```http +GET /api/v1/access/reviews?skip=0&take=20 +Authorization: Bearer +``` + +##### Create Access Review +```http +POST /api/v1/access/reviews +Authorization: Bearer +Content-Type: application/json + +{ + "name": "Q4 Access Review", + "description": "Quarterly access review", + "type": "PERIODIC", + "startDate": "2024-01-01T00:00:00Z", + "endDate": "2024-01-31T23:59:59Z" +} +``` + +##### Get Access Review +```http +GET /api/v1/access/reviews/:id +Authorization: Bearer +``` + +##### Start Access Review +```http +POST /api/v1/access/reviews/:id/start +Authorization: Bearer +``` + +##### Complete Access Review +```http +POST /api/v1/access/reviews/:id/complete +Authorization: Bearer +``` + +##### Get Review Items +```http +GET /api/v1/access/reviews/:id/items?skip=0&take=20 +Authorization: Bearer +``` + +##### Review Access Item +```http +PUT /api/v1/access/reviews/:id/items/:itemId/review +Authorization: Bearer +Content-Type: application/json + +{ + "status": "APPROVED", + "comments": "Access is justified" +} +``` + +#### Access Analytics + +##### Usage Analytics +```http +GET /api/v1/access/analytics/usage?startDate=&endDate= +Authorization: Bearer +``` + +##### Permissions Analytics +```http +GET /api/v1/access/analytics/permissions?resource= +Authorization: Bearer +``` + +##### User Access Summary +```http +GET /api/v1/access/analytics/users/:id/summary +Authorization: Bearer +``` + +##### Risk Analytics +```http +GET /api/v1/access/analytics/risks?minScore=&maxScore= +Authorization: Bearer +``` + +### Governance & Compliance + +#### Compliance Reports + +##### List Compliance Reports +```http +GET /api/v1/governance/compliance/reports?type=GDPR&status=PUBLISHED&skip=0&take=20 +Authorization: Bearer +``` + +##### Generate Compliance Report +```http +POST /api/v1/governance/compliance/reports/generate +Authorization: Bearer +Content-Type: application/json + +{ + "type": "GDPR", + "name": "Q1 GDPR Report", + "periodStart": "2024-01-01T00:00:00Z", + "periodEnd": "2024-03-31T23:59:59Z" +} +``` + +Supported types: `GDPR`, `SOC2`, `ISO27001`, `HIPAA`, `CUSTOM` + +##### Get Compliance Report +```http +GET /api/v1/governance/compliance/reports/:id +Authorization: Bearer +``` + +##### Export Compliance Report +```http +GET /api/v1/governance/compliance/reports/:id/export?format=pdf +Authorization: Bearer +``` + +##### Publish Compliance Report +```http +POST /api/v1/governance/compliance/reports/:id/publish +Authorization: Bearer +``` + +#### Policy Governance + +##### Get Policy Templates +```http +GET /api/v1/governance/policies/templates?category= +Authorization: Bearer +``` + +##### Create Policy Template +```http +POST /api/v1/governance/policies/templates +Authorization: Bearer +Content-Type: application/json + +{ + "name": "Template Name", + "category": "ACCESS_CONTROL", + "content": {}, + "description": "Template description" +} +``` + +##### Get Policy Versions +```http +GET /api/v1/governance/policies/:id/versions +Authorization: Bearer +``` + +##### Test Policy +```http +POST /api/v1/governance/policies/:id/test +Authorization: Bearer +Content-Type: application/json + +{ + "testData": { + "user": {}, + "resource": {}, + "context": {} + } +} +``` + +#### Risk Management + +##### List Risk Scores +```http +GET /api/v1/governance/risk/scores?minScore=0&maxScore=100&level=HIGH&skip=0&take=20 +Authorization: Bearer +``` + +##### Get User Risk Score +```http +GET /api/v1/governance/risk/scores/:userId +Authorization: Bearer +``` + +##### Calculate Risk Score +```http +POST /api/v1/governance/risk/calculate +Authorization: Bearer +Content-Type: application/json + +{ + "userId": "user_id", + "factors": {} +} +``` + +##### Risk Dashboard +```http +GET /api/v1/governance/risk/dashboard +Authorization: Bearer +``` + +#### Reporting + +##### Access Summary Report +```http +GET /api/v1/governance/reports/access-summary?startDate=&endDate= +Authorization: Bearer +``` + +##### User Activity Report +```http +GET /api/v1/governance/reports/user-activity?userId=&startDate=&endDate= +Authorization: Bearer +``` + +##### Security Events Report +```http +GET /api/v1/governance/reports/security-events?startDate=&endDate=&severity= +Authorization: Bearer +``` + +##### Compliance Status Report +```http +GET /api/v1/governance/reports/compliance-status?framework= +Authorization: Bearer +``` + +##### Risk Overview Report +```http +GET /api/v1/governance/reports/risk-overview?startDate=&endDate= +Authorization: Bearer +``` + +### Metrics + +#### Prometheus Metrics +```http +GET /metrics +``` + +Returns application metrics in Prometheus format for monitoring. + ## Error Codes - `AUTH_001` - Authentication required diff --git a/services/iam-service/docs/ARCHITECTURE.vi.md b/services/iam-service/docs/ARCHITECTURE.vi.md index 50a9a312..9d1775d9 100644 --- a/services/iam-service/docs/ARCHITECTURE.vi.md +++ b/services/iam-service/docs/ARCHITECTURE.vi.md @@ -1,552 +1,1189 @@ -# Kiến Trúc Template Dịch Vụ +# Kiến Trúc IAM Service -Tài liệu này mô tả kiến trúc của một microservice đơn lẻ được xây dựng từ template này và cách nó tích hợp với nền tảng microservices GoodGo. +> **Nền Tảng Quản Lý Danh Tính & Truy Cập Cấp Doanh Nghiệp** +> +> Tài liệu này mô tả kiến trúc hoàn chỉnh của IAM Service, bao gồm các thành phần hệ thống, luồng dữ liệu, mô hình bảo mật và các mẫu tích hợp. -## Tổng quan +## Mục Lục -Template này cung cấp foundation hoàn chỉnh, production-ready để xây dựng các microservice riêng lẻ với: - -- **Bảo mật**: Xác thực, phân quyền, validation đầu vào, và security headers -- **Khả năng quan sát**: Logging toàn diện, metrics, tracing, và health checks -- **Quản lý dữ liệu**: Repository pattern, database migrations, và seeding -- **Tài liệu API**: OpenAPI/Swagger documentation với giao diện tương tác -- **Xử lý lỗi**: Structured error responses với HTTP status codes phù hợp -- **Hỗ trợ Docker**: Multi-stage builds và tối ưu hóa production - -**Bối cảnh Quan trọng**: Template này đại diện cho **một microservice đơn lẻ**. Để triển khai và điều phối ở cấp độ nền tảng, các service được đăng ký trong `deployments/local/docker-compose.yml` và định tuyến qua Traefik API Gateway được cấu hình trong `infra/traefik/`. +- [Tổng Quan](#tổng-quan) +- [Kiến Trúc Tổng Thể](#kiến-trúc-tổng-thể) +- [Luồng Xác Thực](#luồng-xác-thực) +- [Mô Hình Phân Quyền](#mô-hình-phân-quyền) +- [Chiến Lược Caching](#chiến-lược-caching) +- [Phụ Thuộc Module](#phụ-thuộc-module) +- [Kiến Trúc Dữ Liệu](#kiến-trúc-dữ-liệu) +- [Kiến Trúc Bảo Mật](#kiến-trúc-bảo-mật) +- [Khả Năng Quan Sát](#khả-năng-quan-sát) +- [Kiến Trúc Triển Khai](#kiến-trúc-triển-khai) --- -# Phần 1: Kiến Trúc Service Đơn Lẻ (Nội bộ) +## Tổng Quan -Phần này mô tả kiến trúc nội bộ của một microservice đơn lẻ được xây dựng từ template này. +IAM Service là một nền tảng Quản lý Danh tính và Truy cập toàn diện cung cấp: -## Các Thành Phần Nội Bộ Service +### Khả Năng Cốt Lõi + +| Khả Năng | Mô Tả | Modules | +|------------|-------------|---------| +| **Xác Thực** | Xác minh danh tính người dùng | Auth, Social, OIDC, MFA | +| **Phân Quyền** | Kiểm soát truy cập và quyền | RBAC, ABAC, Policy Engine | +| **Quản Lý Danh Tính** | Vòng đời người dùng và hồ sơ | Users, Profiles, Organizations, Groups | +| **Quản Trị Truy Cập** | Quy trình yêu cầu và đánh giá | Requests, Reviews, Analytics | +| **Tuân Thủ** | Báo cáo tuân thủ quy định | GDPR, SOC2, ISO27001, Risk Management | +| **Bảo Mật** | Zero-trust và bảo vệ khỏi mối đe dọa | Zero-Trust, Audit, Encryption | +| **Hiệu Suất** | Truy cập tốc độ cao với caching | Multi-layer Cache, Connection Pool | + +### Số Liệu Chính + +- **50+ API Endpoints** trên 10 module tính năng +- **30+ Database Models** với các mối quan hệ toàn diện +- **7 Phương Thức Xác Thực** (password, social x3, OIDC, MFA x2) +- **Caching Đa Lớp** (Memory → Redis → PostgreSQL) +- **Bảo Mật Zero-Trust** với device fingerprinting +- **Tuân Thủ Doanh Nghiệp** (GDPR, SOC2, ISO27001, HIPAA) + +--- + +## Kiến Trúc Tổng Thể + +IAM Service tuân theo mẫu kiến trúc phân lớp với sự phân tách rõ ràng về trách nhiệm: + +```mermaid +graph TB + subgraph "Client Layer" + WebApp[Web Application
React/Vue/Angular] + MobileApp[Mobile App
iOS/Android/React Native] + Service[Other Microservices
Product/Order/Payment] + end + + subgraph "API Gateway" + Traefik[Traefik Gateway
Load Balancer + Routing
Port 80/443] + end + + subgraph "IAM Service - Port 3001" + subgraph "Middleware Stack" + Correlation[Correlation ID
Request Tracking] + Logger[Request Logger
Winston] + ZeroTrust[Zero-Trust Validator
Device + Location + Behavior] + RateLimit[Dynamic Rate Limiter
Redis-backed
50-1000 req/15min] + Auth[Authentication
JWT Verification] + RBAC[Authorization
RBAC + ABAC] + end + + subgraph "Core Authentication Modules" + AuthModule[Auth Module
Login/Register/Logout] + TokenModule[Token Module
JWT + Cookie Management] + SessionModule[Session Module
Device Fingerprinting] + SocialModule[Social Auth
Google/FB/GitHub] + OIDCModule[OIDC Provider
OpenID Connect] + MFAModule[MFA Module
TOTP/WebAuthn] + RBACModule[RBAC Module
Roles + Permissions] + end + + subgraph "Identity Management Modules" + UserModule[User Lifecycle
CRUD + Bulk Ops] + ProfileModule[Profile Management
Avatar + Custom Fields] + VerificationModule[Identity Verification
Email/Phone/Document] + OrgModule[Organizations
Multi-tenant Hierarchy] + GroupModule[Groups
Group-based Access] + end + + subgraph "Access Management Modules" + RequestModule[Access Requests
Approval Workflows] + ReviewModule[Access Reviews
Certification Campaigns] + AnalyticsModule[Access Analytics
Usage + Risk Analysis] + end + + subgraph "Governance Modules" + ComplianceModule[Compliance
GDPR/SOC2/ISO27001] + PolicyModule[Policy Governance
Templates + Versioning] + RiskModule[Risk Management
Scoring + Detection] + ReportingModule[Reporting
Dashboards + Exports] + end + + subgraph "Core Services" + CacheService[Multi-layer Cache
Memory → Redis
TTL: 60s-15min] + AuditService[Audit Logging
Event Sourcing
AuthEvent Model] + SecurityService[Security Services
Encryption + Hashing] + end + end + + subgraph "Data Layer" + PostgreSQL[(PostgreSQL 14+
Primary Database
Connection Pool
30+ Models)] + Redis[(Redis 6+
Cache + Sessions
Rate Limits + Locks)] + end + + subgraph "External Services (Future)" + EmailService[Email Service
Verification + Notifications] + SMSService[SMS Service
OTP + Phone Verification] + FileStorage[File Storage
S3/GCS for Avatars] + end + + subgraph "Observability Stack" + Prometheus[Prometheus
Metrics Collection] + Jaeger[Jaeger
Distributed Tracing] + Logs[Structured Logs
Winston + Loki] + end + + %% Client to Gateway + WebApp --> Traefik + MobileApp --> Traefik + Service --> Traefik + + %% Gateway to Middleware + Traefik --> Correlation + Correlation --> Logger + Logger --> ZeroTrust + ZeroTrust --> RateLimit + RateLimit --> Auth + Auth --> RBAC + + %% Middleware to Modules + RBAC --> AuthModule + RBAC --> UserModule + RBAC --> RequestModule + RBAC --> ComplianceModule + + %% Module Dependencies + AuthModule --> TokenModule + AuthModule --> SessionModule + AuthModule --> SocialModule + AuthModule --> OIDCModule + AuthModule --> MFAModule + AuthModule --> RBACModule + + UserModule --> ProfileModule + UserModule --> VerificationModule + UserModule --> OrgModule + UserModule --> GroupModule + + RequestModule --> ReviewModule + RequestModule --> AnalyticsModule + + ComplianceModule --> PolicyModule + ComplianceModule --> RiskModule + ComplianceModule --> ReportingModule + + %% Core Services + AuthModule --> CacheService + UserModule --> CacheService + RBACModule --> CacheService + + AuthModule --> AuditService + RequestModule --> AuditService + ComplianceModule --> AuditService + + AuthModule --> SecurityService + + %% Data Layer + CacheService --> Redis + CacheService --> PostgreSQL + + AuthModule --> PostgreSQL + UserModule --> PostgreSQL + RequestModule --> PostgreSQL + ComplianceModule --> PostgreSQL + + %% External Services (dashed - not yet integrated) + VerificationModule -.-> EmailService + VerificationModule -.-> SMSService + ProfileModule -.-> FileStorage + + %% Observability + AuthModule -.-> Prometheus + UserModule -.-> Prometheus + RequestModule -.-> Prometheus + ComplianceModule -.-> Prometheus + + CacheService -.-> Jaeger + AuditService -.-> Logs + + style ZeroTrust fill:#ff9999 + style CacheService fill:#99ccff + style PostgreSQL fill:#cc99ff + style Redis fill:#ffcc99 + style AuditService fill:#99ff99 +``` + +### Điểm Nổi Bật Kiến Trúc + +1. **Middleware Phân Lớp**: Mọi request đi qua 6 lớp middleware (correlation, logging, zero-trust, rate limiting, authentication, authorization) +2. **Thiết Kế Module**: 10 module tính năng độc lập với ranh giới rõ ràng +3. **Caching Đa Lớp**: Memory (60s) → Redis (5-15min) → PostgreSQL để tối ưu hiệu suất +4. **Event Sourcing**: Tất cả các sự kiện xác thực và phân quyền được ghi log để tuân thủ audit +5. **Bảo Mật Zero-Trust**: Xác thực liên tục thiết bị, vị trí và hành vi +6. **Rate Limiting Động**: Giới hạn dựa trên vai trò (50-1000 req/15min) + +--- + +## Luồng Xác Thực + +### Xác Thực Dựa Trên Mật Khẩu + +Xác thực email/mật khẩu tiêu chuẩn với bcrypt hashing và tạo JWT token: + +```mermaid +sequenceDiagram + participant Client + participant Middleware + participant AuthService + participant RBACService + participant Database + participant Redis + participant AuditService + + Client->>Middleware: POST /api/v1/auth/login
{email, password} + + Middleware->>Middleware: 1. Correlation ID + Middleware->>Middleware: 2. Zero-Trust Validation
(Device + IP + Behavior) + Middleware->>Middleware: 3. Rate Limit Check
(5 login/15min) + + Middleware->>AuthService: login(email, password) + + AuthService->>Database: Find user by email + Database-->>AuthService: User record + + AuthService->>AuthService: Verify password
(bcrypt compare, cost=12) + + alt Password Invalid + AuthService->>AuditService: Log LOGIN_FAILED event + AuditService->>Database: Save AuthEvent + AuthService-->>Client: 401 Unauthorized
"Invalid credentials" + else Password Valid & MFA Disabled + AuthService->>RBACService: Get user roles + permissions + RBACService->>Database: Query UserRole, UserPermission + Database-->>RBACService: Roles + Permissions + RBACService-->>AuthService: ["ADMIN"], ["users:read:all"] + + AuthService->>AuthService: Generate JWT tokens
Access: 15min
Refresh: 7 days + + AuthService->>Database: Save refresh token + AuthService->>Redis: Cache user data
TTL: 15min + AuthService->>Redis: Cache permissions
TTL: 5min + AuthService->>Database: Create session
(device fingerprint) + + AuthService->>Database: Update lastLoginAt, loginCount + AuthService->>AuditService: Log LOGIN_SUCCESS event + + AuthService-->>Client: 200 OK
{user, tokens}
Set-Cookie: refresh_token + else Password Valid & MFA Enabled + AuthService-->>Client: 200 OK
{mfaRequired: true} + Note over Client: Prompt for MFA code + Client->>Middleware: POST /api/v1/mfa/verify
{token: "123456"} + Note over Middleware,AuthService: MFA verification flow... + end +``` + +**Tính Năng Bảo Mật Chính:** +- Băm mật khẩu bcrypt (cost factor 12 trong production) +- Theo dõi token family để bảo mật rotation +- Device fingerprinting cho quản lý session +- Xác thực zero-trust trước khi xác thực +- Ghi log audit toàn diện + +### Luồng Xác Thực Xã Hội + +Tích hợp OAuth 2.0 với Google, Facebook và GitHub: + +```mermaid +sequenceDiagram + participant Client + participant IAM + participant Google as Google OAuth + participant Database + participant Redis + + Client->>IAM: GET /api/v1/auth/social/google + IAM->>IAM: Generate state token
(CSRF protection) + IAM->>Redis: Store state token
TTL: 10min + IAM-->>Client: 302 Redirect to Google
with state param + + Client->>Google: OAuth consent screen + Google-->>Client: Authorization code + state + + Client->>IAM: GET /api/v1/auth/social/google/callback
?code=xxx&state=yyy + + IAM->>Redis: Verify state token + alt State Invalid + IAM-->>Client: 401 CSRF token invalid + else State Valid + IAM->>Google: Exchange code for tokens + Google-->>IAM: Access token + User profile + + IAM->>Database: Find or create user
by provider + providerId + + alt User Found + IAM->>Database: Update social account tokens + else New User + IAM->>Database: Create user + social account + IAM->>Database: Assign default role (USER) + end + + IAM->>IAM: Generate IAM JWT tokens + IAM->>Redis: Cache user + permissions + IAM->>Database: Create session + + IAM-->>Client: 302 Redirect to app
with tokens in URL/cookie + end +``` + +**Nhà Cung Cấp Được Hỗ Trợ:** +- Google OAuth 2.0 +- Facebook OAuth +- GitHub OAuth +- Apple Sign-In (tương lai) +- Microsoft OAuth (tương lai) + +### Luồng MFA (Xác Thực Đa Yếu Tố) + +Xác thực hai yếu tố dựa trên TOTP sử dụng ứng dụng xác thực: + +```mermaid +sequenceDiagram + participant Client + participant IAM + participant Authenticator as Authenticator App + participant Database + + Note over Client,Database: MFA Enrollment Phase + + Client->>IAM: POST /api/v1/mfa/totp/enable + Note over Client: User must be authenticated + + IAM->>IAM: Generate TOTP secret (32 chars) + IAM->>IAM: Generate QR code
(otpauth://totp/...) + IAM-->>Client: {secret, qrCode, backupCodes} + + Client->>Authenticator: Scan QR code + Authenticator-->>Client: Display 6-digit TOTP + + Client->>IAM: POST /api/v1/mfa/totp/verify
{token: "123456"} + + IAM->>IAM: Verify TOTP token
(30s window, ±1 interval) + + alt Token Valid + IAM->>Database: Create MFADevice record
(type: TOTP, secret: encrypted) + IAM->>Database: Update user.mfaEnabled = true + IAM-->>Client: 200 OK MFA enabled + else Token Invalid + IAM-->>Client: 401 Invalid TOTP token + end + + Note over Client,Database: MFA Login Phase + + Client->>IAM: POST /api/v1/auth/login
{email, password} + IAM->>Database: Verify credentials + + alt MFA Required + IAM-->>Client: 200 OK {mfaRequired: true} + + Client->>Authenticator: Get current TOTP + Authenticator-->>Client: Current 6-digit code + + Client->>IAM: POST /api/v1/mfa/totp/validate
{userId, token} + + IAM->>Database: Get MFADevice for user + IAM->>IAM: Verify TOTP token + + alt Token Valid + IAM->>IAM: Generate full JWT tokens + IAM->>Database: Create session + IAM->>Database: Update device.lastUsedAt + IAM-->>Client: 200 OK {user, tokens} + else Token Invalid + IAM-->>Client: 401 Invalid MFA token + end + end +``` + +**Tính Năng MFA:** +- TOTP (Time-based One-Time Password) qua ứng dụng xác thực +- Tạo mã QR để đăng ký dễ dàng +- Backup codes để khôi phục tài khoản +- Nhiều thiết bị MFA cho mỗi người dùng +- Framework WebAuthn/FIDO2 (triển khai tương lai) + +--- + +## Mô Hình Phân Quyền + +IAM Service triển khai mô hình phân quyền kết hợp giữa RBAC (Role-Based Access Control) và ABAC (Attribute-Based Access Control): + +### Luồng Quyết Định Phân Quyền + +```mermaid +flowchart TD + Start[Request to Protected Resource] --> Auth{Authenticated?} + + Auth -->|No| Deny401[401 Unauthorized
Authentication required] + Auth -->|Yes| Cache{Permission
in Cache?} + + Cache -->|Hit| CacheValue{Cache
Value?} + CacheValue -->|Allow| Allow[Access Granted] + CacheValue -->|Deny| Deny403Cache[403 Forbidden
Cached denial] + + Cache -->|Miss| LoadPerms[Load Permissions
from Database] + + LoadPerms --> DirectPerms{Has Direct
User Permission?} + + DirectPerms -->|Explicit Deny| Deny403A[403 Forbidden
Explicit permission denial] + DirectPerms -->|Explicit Allow| Allow + DirectPerms -->|None| RolePerms{Has Role
Permission?} + + RolePerms -->|Yes| CheckExpiry{Role
Expired?} + RolePerms -->|No| GroupPerms{Has Group
Permission?} + + CheckExpiry -->|Yes| GroupPerms + CheckExpiry -->|No| Allow + + GroupPerms -->|Yes| Allow + GroupPerms -->|No| ABACCheck{ABAC Policy
Exists?} + + ABACCheck -->|No Policies| DefaultDeny[403 Forbidden
Default deny - No permissions] + ABACCheck -->|Has Policies| EvaluatePolicies[Evaluate Policies
by Priority] + + EvaluatePolicies --> EvalConditions{Policy
Conditions?} + + EvalConditions -->|Time-based| CheckTime{Current time
in range?} + EvalConditions -->|Location-based| CheckLocation{IP in
allowed range?} + EvalConditions -->|Attribute-based| CheckAttrs{Attributes
match?} + + CheckTime -->|Yes| PolicyEffect{Policy
Effect?} + CheckTime -->|No| NextPolicy{More
Policies?} + + CheckLocation -->|Yes| PolicyEffect + CheckLocation -->|No| NextPolicy + + CheckAttrs -->|Yes| PolicyEffect + CheckAttrs -->|No| NextPolicy + + PolicyEffect -->|ALLOW| Allow + PolicyEffect -->|DENY| Deny403Policy[403 Forbidden
Policy denial] + + NextPolicy -->|Yes| EvaluatePolicies + NextPolicy -->|No| DefaultDeny + + Allow --> CacheResult[Cache Result
TTL: 5min] + CacheResult --> AuditLog[Log Access Event
to AuthEvent] + AuditLog --> Success[200 OK
Process request] + + style Auth fill:#e1f5fe + style DirectPerms fill:#fff3e0 + style RolePerms fill:#f3e5f5 + style GroupPerms fill:#e8f5e9 + style ABACCheck fill:#fce4ec + style Allow fill:#c8e6c9 + style Deny401 fill:#ffcdd2 + style Deny403A fill:#ffcdd2 + style Deny403Cache fill:#ffcdd2 + style Deny403Policy fill:#ffcdd2 + style DefaultDeny fill:#ffcdd2 +``` + +### Mô Hình Quyền + +IAM Service sử dụng mô hình quyền phân cấp: + +**Định Dạng Quyền**: `resource:action:scope` + +- **Resource**: Thực thể được truy cập (ví dụ: `users`, `products`, `orders`) +- **Action**: Hoạt động được thực hiện (ví dụ: `read`, `create`, `update`, `delete`) +- **Scope**: Ranh giới truy cập (ví dụ: `own`, `team`, `all`) + +**Ví Dụ**: +- `users:read:all` - Đọc tất cả người dùng +- `users:update:own` - Cập nhật hồ sơ người dùng của chính mình +- `products:create:team` - Tạo sản phẩm cho team +- `orders:delete:all` - Xóa bất kỳ đơn hàng nào (admin) + +### Thứ Bậc Phân Quyền + +``` +1. Quyền Người Dùng Trực Tiếp (ƯU TIÊN CAO NHẤT) + ↓ (nếu không tìm thấy hoặc không bị từ chối) +2. Quyền Vai Trò + ↓ (nếu không tìm thấy) +3. Quyền Nhóm + ↓ (nếu không tìm thấy) +4. Chính Sách ABAC (được đánh giá theo mức độ ưu tiên) + ↓ (nếu không có chính sách nào khớp) +5. Từ Chối Mặc Định (ƯU TIÊN THẤP NHẤT) +``` + +### RBAC (Role-Based Access Control) + +```mermaid +graph LR + User[User] --> UserRole1[UserRole] + User --> UserRole2[UserRole] + User --> UserPerm[UserPermission
Direct Override] + + UserRole1 --> Role1[ADMIN Role] + UserRole2 --> Role2[MANAGER Role] + + Role1 --> RolePerm1[RolePermission] + Role1 --> RolePerm2[RolePermission] + Role2 --> RolePerm3[RolePermission] + + RolePerm1 --> Perm1[users:*:all] + RolePerm2 --> Perm2[products:*:all] + RolePerm3 --> Perm3[orders:read:team] + + UserPerm --> Perm4[analytics:read:all] + + Group[Group] --> GroupMember[GroupMember] + GroupMember --> User + Group --> GroupPerm[GroupPermission] + GroupPerm --> Perm5[reports:read:all] + + style User fill:#e1f5fe + style Role1 fill:#f3e5f5 + style Role2 fill:#f3e5f5 + style Group fill:#e8f5e9 + style Perm1 fill:#fff3e0 + style Perm2 fill:#fff3e0 + style Perm3 fill:#fff3e0 + style Perm4 fill:#ffccbc + style Perm5 fill:#c8e6c9 +``` + +**Tính Năng:** +- Nhiều vai trò cho mỗi người dùng +- Gán vai trò tạm thời với thời hạn hết hạn +- Quyền người dùng trực tiếp (có thể ghi đè vai trò) +- Quyền dựa trên nhóm +- Caching quyền (TTL 5 phút) + +### ABAC (Attribute-Based Access Control) ```mermaid graph TD - Request[HTTP Request] -->|Từ Traefik| Middleware[Chuỗi Middleware] - - subgraph SingleService[Ranh Giới Service Đơn Lẻ] - Middleware --> Correlation[Correlation ID Middleware] - Correlation --> Auth[Authentication Middleware] - Auth --> Validation[Validation Middleware] - Validation --> Error[Error Handler] - Error --> Logger[Request Logger] - Logger --> Metrics[Metrics Collector] - - Metrics --> Router[Lớp Router] - Router --> Controller[Lớp Controller] - Controller --> Service[Lớp Service] - Service --> Repository[Lớp Repository] - - Repository --> Database[(PostgreSQL)] - Service --> Cache[(Redis)] - - Service -.->|Trạng thái Health| Health[Health Checks] - Service -.->|Tài liệu API| OpenAPI[OpenAPI/Swagger] - end - - Service -.->|Metrics| Prometheus[Prometheus] - Service -.->|Traces| Jaeger[Jaeger] - - style Correlation fill:#e1f5fe - style Auth fill:#f3e5f5 - style Validation fill:#e8f5e8 - style Error fill:#fff3e0 - style Logger fill:#f3e5f5 - style Metrics fill:#e8f5e8 + Request[Access Request] --> PolicyEngine[Policy Engine] + + PolicyEngine --> LoadPolicies[Load Policies
for Resource] + LoadPolicies --> SortPolicies[Sort by Priority
Descending] + + SortPolicies --> EvaluatePolicy[Evaluate Policy
Conditions] + + EvaluatePolicy --> TimeCondition{Time-based
Condition?} + EvaluatePolicy --> LocationCondition{Location-based
Condition?} + EvaluatePolicy --> AttributeCondition{Attribute-based
Condition?} + + TimeCondition --> CheckTime[Check current time
vs allowed hours] + LocationCondition --> CheckIP[Check IP address
vs allowed ranges] + AttributeCondition --> CheckAttrs[Check user attributes
vs required values] + + CheckTime --> ConditionMet{All Conditions
Met?} + CheckIP --> ConditionMet + CheckAttrs --> ConditionMet + + ConditionMet -->|Yes| ApplyEffect{Policy
Effect?} + ConditionMet -->|No| NextPolicy{More
Policies?} + + ApplyEffect -->|ALLOW| Allow[Access Granted] + ApplyEffect -->|DENY| Deny[Access Denied] + + NextPolicy -->|Yes| EvaluatePolicy + NextPolicy -->|No| DefaultDeny[Default Deny] + + style PolicyEngine fill:#f3e5f5 + style ConditionMet fill:#fff3e0 + style Allow fill:#c8e6c9 + style Deny fill:#ffcdd2 + style DefaultDeny fill:#ffcdd2 ``` -## Kiến Trúc Phân Lớp - -### Chuỗi Middleware - -Chuỗi middleware xử lý mọi request đến theo thứ tự: - -1. **Correlation Middleware**: Tạo/truyền correlation và request IDs -2. **Authentication Middleware**: Xác thực JWT tokens (tùy chọn cho public routes) -3. **Validation Middleware**: Làm sạch và validate dữ liệu đầu vào với Zod schemas -4. **Error Handler**: Bắt và format lỗi thành structured responses -5. **Logger Middleware**: Ghi log request/response với correlation IDs -6. **Metrics Middleware**: Thu thập Prometheus metrics (duration, status, payload size) - -### Lớp Controller - -- Xử lý HTTP requests và responses -- Điều phối các lời gọi service layer -- Format API responses -- Bọc async handlers để truyền lỗi - -### Lớp Service - -- Chứa business logic thuần túy -- Độc lập với HTTP transport -- Điều phối các lời gọi repository -- Triển khai caching strategies -- Throw domain-specific errors - -### Lớp Repository - -- Trừu tượng hóa database operations -- Sử dụng Prisma ORM cho type-safe queries -- Triển khai repository pattern -- Cung cấp error handling nhất quán -- Hỗ trợ transactions - -## Luồng Xử Lý Request - -1. **Đầu vào Request**: - - Client gửi HTTP request đến ingress/load balancer - - Request bao gồm correlation ID header tùy chọn (`x-correlation-id`) - -2. **Correlation Middleware**: - - Tạo hoặc truyền correlation ID để tracing request - - Thêm request ID để định danh request duy nhất - - Đặt correlation headers trên response - -3. **Security Middleware**: - - **Authentication**: Xác thực JWT tokens (tùy chọn cho public routes) - - **Authorization**: Kiểm tra user roles và permissions - - **Rate Limiting**: Ngăn chặn lạm dụng với Redis-backed rate limiting - - **Helmet**: Bảo mật HTTP headers - -4. **Validation Middleware**: - - Làm sạch input data (trimming, normalization) - - Validate request data sử dụng Zod schemas - - Trả về structured validation errors - -5. **Router & Controller**: - - Định tuyến request đến controller phù hợp - - Controller điều phối thực thi business logic - - Input validation và response formatting - -6. **Lớp Service**: - - Chứa business logic thuần túy - - Độc lập với HTTP transport layer - - Điều phối data access và external service calls - -7. **Lớp Repository**: - - Triển khai repository pattern cho data access - - Trừu tượng hóa database operations với Prisma ORM - - Cung cấp error handling nhất quán - -8. **Response & Observability**: - - Format structured JSON responses - - Ghi lại comprehensive metrics (duration, errors, payload sizes) - - Log với correlation IDs cho distributed tracing - - Gửi traces đến Jaeger nếu được bật - -## Mẫu Kiến Trúc - -### Mẫu Repository - -```typescript -// Base repository với common CRUD operations -class BaseRepository { - async findById(id: string): Promise - async create(data: CreateInput): Promise - async update(id: string, data: UpdateInput): Promise - // ... thêm các methods phổ biến -} - -// Repository cụ thể extends base -class FeatureRepository extends BaseRepository { - async findByName(name: string): Promise - async findByTags(tags: string[]): Promise - // ... feature-specific methods -} -``` - -### Chuỗi Middleware - -```typescript -// Request processing pipeline -app.use(correlationMiddleware()); // Thêm correlation IDs -app.use(authenticate()); // JWT validation -app.use(authorize('admin')); // Role checking -app.use(validateDto(schema)); // Input validation -app.use(errorHandler); // Error handling -``` - -### Xử Lý Lỗi - -```typescript -// Custom error classes -class NotFoundError extends HttpError { - constructor(resource: string) { - super(`${resource} not found`, 404, 'NOT_FOUND'); - } -} - -// Sử dụng trong services -if (!feature) { - throw new NotFoundError('Feature'); -} -``` - -### Tiêm Phụ Thuộc - -```typescript -// Constructor injection cho testability -export class FeatureService { - constructor(private repository: IRepository) {} - - async create(data: CreateFeatureInput): Promise { - return this.repository.create(data); - } -} -``` - -## Thực Tiễn Tốt - -### Tổ Chức Code - -- **Separation of Concerns**: Ranh giới rõ ràng giữa các lớp (Controller → Service → Repository) -- **Single Responsibility**: Mỗi class/method có một mục đích rõ ràng -- **Dependency Injection**: Constructor injection để testability tốt hơn -- **Error Boundaries**: Xử lý lỗi phù hợp ở mỗi lớp - -### Bảo Mật - -- **Input Validation**: Tất cả inputs được validate với Zod schemas -- **Authentication**: JWT tokens với expiration phù hợp -- **Authorization**: Role-based access control (RBAC) -- **Rate Limiting**: Distributed rate limiting với Redis -- **Security Headers**: Helmet.js cho HTTP security headers - -### Khả Năng Quan Sát - -- **Structured Logging**: Format log nhất quán với correlation IDs -- **Metrics**: Comprehensive Prometheus metrics -- **Tracing**: Distributed tracing với Jaeger -- **Health Checks**: Liveness và readiness probes -- **Correlation IDs**: Request tracing qua service boundaries - -### Xử Lý Lỗi - -- **Custom Error Classes**: Error types cụ thể cho các scenarios khác nhau -- **HTTP Status Mapping**: Status codes phù hợp cho các error types khác nhau -- **Structured Responses**: Format error response nhất quán -- **Operational Errors**: Phân biệt rõ ràng giữa programming và operational errors - -### Kiểm Thử - -- **Unit Tests**: Test các functions và classes riêng lẻ -- **Integration Tests**: Test tương tác giữa các components -- **E2E Tests**: Test chu trình request/response hoàn chỉnh -- **Test Utilities**: Shared test helpers và mocks -- **Coverage Goals**: Mục tiêu >70% code coverage - -### Docker & Triển Khai - -- **Multi-stage Builds**: Tối ưu cho production image size -- **Security**: Non-root users, minimal attack surface -- **Health Checks**: Container health monitoring -- **Compose Files**: Development, testing, và production configurations -- **Resource Limits**: CPU và memory constraints phù hợp - -## Quản Lý Cấu Hình - -### Biến Môi Trường - -- **Typed Configuration**: Zod schemas cho env validation -- **Default Values**: Defaults hợp lý cho development -- **Override Support**: `.env.local` ghi đè `.env` -- **Documentation**: Tài liệu biến môi trường toàn diện - -### Feature Flags - -- **Runtime Configuration**: Database-backed feature flags -- **Admin Control**: Admin API cho feature management -- **Gradual Rollout**: Bật/tắt features không cần deployment -- **Audit Trail**: Theo dõi feature flag changes - -## Thiết Kế API - -### Quy Ước RESTful - -- **Resource Naming**: Danh từ số nhiều cho resource endpoints -- **HTTP Methods**: GET, POST, PUT, DELETE, PATCH phù hợp -- **Status Codes**: HTTP status codes phù hợp cho tất cả responses -- **Content Negotiation**: JSON responses với content-type phù hợp - -### Định Dạng Phản hồi - +**Ví Dụ Chính Sách (JSON Logic)**: ```json { - "success": true, - "data": { ... }, - "message": "Hoạt động hoàn thành thành công", - "timestamp": "2024-01-01T00:00:00.000Z" -} -``` - -### Phản hồi Lỗi - -```json -{ - "success": false, - "error": { - "code": "VALIDATION_ERROR", - "message": "Validation thất bại", - "details": [...] + "name": "Business Hours Only", + "resource": "sensitive_data", + "condition": { + "and": [ + { + ">=": [{"var": "hour"}, 9] + }, + { + "<=": [{"var": "hour"}, 17] + }, + { + "in": [{"var": "day"}, [1, 2, 3, 4, 5]] + } + ] }, - "timestamp": "2024-01-01T00:00:00.000Z" + "effect": "ALLOW", + "priority": 100 } ``` -## Quy Trình Phát Triển +--- + +## Chiến Lược Caching + +IAM Service triển khai chiến lược caching đa lớp để tối ưu hiệu suất: + +```mermaid +graph TB + Request[Incoming Request] --> CheckL1{L1 Cache
Node.js Memory} + + CheckL1 -->|Cache Hit| L1Hit[Fast Response
< 1ms latency] + CheckL1 -->|Cache Miss| CheckL2{L2 Cache
Redis} + + CheckL2 -->|Cache Hit| L2Hit[Medium Response
< 10ms latency] + CheckL2 -->|Cache Miss| Database[(PostgreSQL
Source of Truth)] + + Database --> UpdateL2[Update L2 Cache
Write to Redis] + UpdateL2 --> UpdateL1[Update L1 Cache
Write to Memory] + + UpdateL1 --> Response[Return Response] + L2Hit --> UpdateL1 + L1Hit --> Response + + subgraph "Cache Layers" + L1Cache[L1: In-Memory Cache
node-cache
TTL: 60 seconds
Hot data only] + L2Cache[L2: Redis Cache
ioredis
TTL: 5-15 minutes
Distributed] + DBLayer[L3: PostgreSQL
Prisma ORM
Source of truth
Persistent] + end + + subgraph "Cached Data Types" + UserData[User Data
TTL: 15min] + Permissions[Permissions
TTL: 5min] + Tokens[Token Validation
TTL: Token lifetime] + Sessions[Sessions
TTL: Session lifetime] + Roles[User Roles
TTL: 5min] + end + + style L1Hit fill:#90EE90 + style L2Hit fill:#87CEEB + style Database fill:#FFB6C1 + style L1Cache fill:#c8e6c9 + style L2Cache fill:#bbdefb + style DBLayer fill:#f8bbd0 +``` + +### Cấu Hình Cache + +| Loại Dữ Liệu | L1 TTL | L2 TTL | Chiến Lược Vô Hiệu Hóa | +|-----------|--------|--------|----------------------| +| User Data | 60s | 15min | Khi cập nhật/xóa | +| Permissions | 60s | 5min | Khi thay đổi vai trò/quyền | +| User Roles | 60s | 5min | Khi gán/thu hồi vai trò | +| Token Validation | N/A | Token lifetime | Khi đăng xuất/thu hồi | +| Sessions | N/A | Session lifetime | Khi đăng xuất | +| Rate Limit Counters | N/A | 15min window | Hết hạn theo thời gian | + +### Vô Hiệu Hóa Cache + +```typescript +// Ví dụ: Vô hiệu hóa cache người dùng khi quyền thay đổi +await rbacService.grantPermission(userId, permissionId); + +// Tự động vô hiệu hóa: +// - cacheService.keys.userPermissions(userId) +// - cacheService.keys.userRoles(userId) +``` + +--- + +## Phụ Thuộc Module + +IAM Service được tổ chức thành 10 module tính năng với các phụ thuộc rõ ràng: + +```mermaid +graph TD + subgraph "Presentation Layer" + Routes[Routes/Controllers
50+ Endpoints] + end + + subgraph "Business Logic Layer" + subgraph "Core Auth" + AuthModule[Auth Module
Login/Register/Logout] + TokenModule[Token Module
JWT + Cookies] + SessionModule[Session Module
Device Tracking] + end + + subgraph "Extended Auth" + RBACModule[RBAC Module
Roles + Permissions] + SocialModule[Social Auth
Google/FB/GitHub] + OIDCModule[OIDC Module
Provider + Client] + MFAModule[MFA Module
TOTP/WebAuthn] + end + + subgraph "Identity" + IdentityModule[Identity Module
Users + Profiles] + OrgModule[Organization Module
Multi-tenancy] + GroupModule[Group Module
Group Permissions] + end + + subgraph "Access Governance" + AccessModule[Access Module
Requests + Reviews] + AnalyticsModule[Analytics Module
Usage Analysis] + end + + subgraph "Compliance" + GovernanceModule[Governance Module
Compliance + Risk] + end + end + + subgraph "Core Services Layer" + CacheService[Cache Service
Multi-layer] + AuditService[Audit Service
Event Sourcing] + SecurityService[Security Service
Encryption] + FeatureService[Feature Flags
Runtime Config] + end + + subgraph "Data Access Layer" + Repositories[Repositories
Data Access
Prisma ORM] + end + + subgraph "Infrastructure" + Database[(PostgreSQL
30+ Models)] + Redis[(Redis
Cache + Locks)] + end + + %% Routes to Modules + Routes --> AuthModule + Routes --> IdentityModule + Routes --> AccessModule + Routes --> GovernanceModule + + %% Core Auth Dependencies + AuthModule --> TokenModule + AuthModule --> SessionModule + AuthModule --> SocialModule + AuthModule --> OIDCModule + AuthModule --> MFAModule + AuthModule --> RBACModule + + %% Identity Dependencies + IdentityModule --> OrgModule + IdentityModule --> GroupModule + IdentityModule --> RBACModule + + %% Access Dependencies + AccessModule --> AnalyticsModule + AccessModule --> RBACModule + + %% Governance Dependencies + GovernanceModule --> RBACModule + + %% Core Services + AuthModule --> CacheService + IdentityModule --> CacheService + RBACModule --> CacheService + + AuthModule --> AuditService + AccessModule --> AuditService + GovernanceModule --> AuditService + + AuthModule --> SecurityService + + AuthModule --> FeatureService + + %% Data Access + AuthModule --> Repositories + IdentityModule --> Repositories + AccessModule --> Repositories + GovernanceModule --> Repositories + RBACModule --> Repositories + + Repositories --> Database + CacheService --> Redis + CacheService --> Database + + style AuthModule fill:#e1f5fe + style RBACModule fill:#f3e5f5 + style IdentityModule fill:#fff3e0 + style AccessModule fill:#e8f5e9 + style GovernanceModule fill:#fce4ec + style CacheService fill:#bbdefb + style AuditService fill:#c8e6c9 + style SecurityService fill:#ffccbc +``` + +### Mô Tả Module + +| Module | Trách Nhiệm | Key Files | +|--------|---------------|-----------| +| **Auth** | Xác thực người dùng và quản lý token | `auth.service.ts`, `auth.controller.ts` | +| **Token** | Tạo, xác thực và làm mới JWT | `jwt.service.ts`, `cookie.service.ts` | +| **Session** | Vòng đời session và quản lý thiết bị | `session.service.ts` | +| **RBAC** | Quản lý vai trò và quyền | `rbac.service.ts`, `rbac.middleware.ts` | +| **Social** | Tích hợp OAuth với nhà cung cấp bên ngoài | `social.service.ts`, `google.strategy.ts` | +| **OIDC** | OpenID Connect provider và client | `oidc-provider.service.ts` | +| **MFA** | Xác thực đa yếu tố | `mfa.service.ts`, `totp.service.ts` | +| **Identity** | Vòng đời người dùng và quản lý hồ sơ | `user.service.ts`, `profile.service.ts` | +| **Organization** | Hỗ trợ tổ chức multi-tenant | `organization.service.ts` | +| **Group** | Kiểm soát truy cập dựa trên nhóm | `group.service.ts` | +| **Access** | Quy trình yêu cầu truy cập và đánh giá | `request.service.ts`, `review.service.ts` | +| **Analytics** | Phân tích truy cập và báo cáo | `analytics.service.ts` | +| **Governance** | Tuân thủ, chính sách và quản lý rủi ro | `compliance.service.ts`, `risk.service.ts` | +| **Cache** | Caching đa lớp (Memory + Redis) | `cache.service.ts` | +| **Audit** | Event sourcing và ghi log audit | `audit.service.ts` | +| **Security** | Mã hóa, băm, zero-trust | `zero-trust.validator.ts` | + +--- + +## Kiến Trúc Dữ Liệu + +IAM Service sử dụng PostgreSQL với 30+ Prisma models. Xem [DATA-MODEL.md](./concepts/DATA-MODEL.md) để xem sơ đồ Entity Relationship hoàn chỉnh. + +### Danh Mục Model + +1. **Xác Thực Cốt Lõi** (7 models): + - User, Session, RefreshToken, AuthEvent, SocialAccount, MFADevice, Policy + +2. **Phân Quyền** (6 models): + - Role, Permission, UserRole, RolePermission, UserPermission, GroupPermission + +3. **Quản Lý Danh Tính** (6 models): + - Organization, Group, GroupMember, UserProfile, IdentityVerification + +4. **Quản Lý Truy Cập** (4 models): + - AccessRequest, AccessRequestApprover, AccessReview, AccessReviewItem + +5. **Quản Trị** (3 models): + - ComplianceReport, PolicyTemplate, RiskScore + +### Mối Quan Hệ Chính + +``` +User (1) ─── (*) UserRole ─── (*) Role ─── (*) RolePermission ─── (*) Permission +User (1) ─── (*) UserPermission ─── (*) Permission +User (1) ─── (*) Session +User (1) ─── (1) UserProfile +User (1) ─── (*) AccessRequest +Organization (1) ─── (*) User +Organization (1) ─── (*) Group ─── (*) GroupMember ─── (*) User +``` + +--- + +## Kiến Trúc Bảo Mật + +IAM Service triển khai bảo mật defense-in-depth với nhiều lớp: + +### Các Lớp Bảo Mật + +```mermaid +graph TB + Request[Incoming Request] --> Layer1[Layer 1: Network Security
Traefik Gateway + TLS] + + Layer1 --> Layer2[Layer 2: Zero-Trust Validation
Device + Location + Behavior] + + Layer2 --> Layer3[Layer 3: Rate Limiting
Dynamic by Role
50-1000 req/15min] + + Layer3 --> Layer4[Layer 4: Authentication
JWT Validation
Token Expiry: 15min] + + Layer4 --> Layer5[Layer 5: Authorization
RBAC + ABAC
Permission Checking] + + Layer5 --> Layer6[Layer 6: Input Validation
Zod Schemas
Sanitization] + + Layer6 --> Layer7[Layer 7: Audit Logging
Event Sourcing
All Actions Logged] + + Layer7 --> ProcessRequest[Process Request] + + style Layer1 fill:#ffccbc + style Layer2 fill:#ff9999 + style Layer3 fill:#ffb74d + style Layer4 fill:#fff176 + style Layer5 fill:#aed581 + style Layer6 fill:#4dd0e1 + style Layer7 fill:#9575cd + style ProcessRequest fill:#c8e6c9 +``` + +### Tính Năng Bảo Mật + +| Tính Năng | Triển Khai | Vị Trí | +|---------|---------------|----------| +| **Zero-Trust** | Device fingerprinting, location, behavior analysis | `zero-trust.validator.ts` | +| **Password Hashing** | bcrypt (cost factor 12) | `auth.service.ts:43` | +| **Token Security** | JWT với HS256, hết hạn 15min, token rotation | `jwt.service.ts` | +| **CSRF Protection** | State tokens cho OAuth, SameSite cookies | `cookie.service.ts` | +| **Rate Limiting** | Redis-backed, động theo vai trò | `rate-limit.middleware.ts` | +| **Input Validation** | Zod schemas, sanitization | `validation.middleware.ts` | +| **Audit Logging** | Event sourcing (AuthEvent model) | `audit.service.ts` | +| **Session Security** | Device fingerprinting, IP tracking | `session.service.ts` | +| **MFA** | TOTP với cửa sổ 30s, backup codes | `mfa.service.ts` | + +### Giảm Thiểu Mối Đe Dọa + +| Mối Đe Dọa | Giảm Thiểu | +|--------|-----------| +| **Brute Force** | Giới hạn tốc độ đăng nhập (5 lần/15min), khóa tài khoản | +| **Token Theft** | Thời gian sống token ngắn (15min), token rotation, device binding | +| **CSRF** | SameSite cookies, state tokens cho OAuth | +| **XSS** | Content Security Policy, HttpOnly cookies | +| **SQL Injection** | Prisma ORM parameterized queries | +| **Session Hijacking** | Device fingerprinting, IP validation | +| **Privilege Escalation** | Kiểm tra quyền nghiêm ngặt, ghi log audit | +| **Replay Attacks** | Token hết hạn, nonce cho OAuth | + +--- + +## Khả Năng Quan Sát + +IAM Service cung cấp khả năng quan sát toàn diện với metrics, logs và traces: + +### Observability Stack + +```mermaid +graph TB + subgraph "IAM Service" + Application[Application Code] + + Application --> MetricsCollector[Metrics Collector
Prometheus Format] + Application --> Logger[Structured Logger
Winston] + Application --> Tracer[Distributed Tracer
Jaeger Client] + end + + subgraph "Collection Layer" + Prometheus[Prometheus
Metrics Storage] + Loki[Loki
Log Aggregation] + Jaeger[Jaeger
Trace Storage] + end + + subgraph "Visualization Layer" + Grafana[Grafana
Dashboards + Alerts] + end + + MetricsCollector --> Prometheus + Logger --> Loki + Tracer --> Jaeger + + Prometheus --> Grafana + Loki --> Grafana + Jaeger --> Grafana + + Grafana --> Alerts[Alert Manager
Notifications] + + style Application fill:#e1f5fe + style Prometheus fill:#f3e5f5 + style Loki fill:#fff3e0 + style Jaeger fill:#e8f5e9 + style Grafana fill:#fce4ec +``` + +### Metrics (Prometheus) + +**Metrics Được Thu Thập:** +- Thời lượng request HTTP (histogram) +- Số lượng request HTTP (counter) +- Mã trạng thái phản hồi HTTP (counter) +- Session đang hoạt động (gauge) +- Tỷ lệ cache hit/miss (counter) +- Thời lượng truy vấn database (histogram) +- Tỷ lệ thành công/thất bại xác thực (counter) +- Thời lượng kiểm tra quyền (histogram) + +**Endpoints:** +- `/metrics` - Prometheus metrics endpoint +- `/health/live` - Liveness probe +- `/health/ready` - Readiness probe + +### Logging (Winston) + +**Mức Độ Log:** ERROR, WARN, INFO, DEBUG + +**Định Dạng Log Có Cấu Trúc:** +```json +{ + "level": "info", + "message": "User logged in", + "timestamp": "2024-01-01T00:00:00.000Z", + "correlationId": "req-123-456", + "userId": "user-789", + "email": "user@example.com", + "service": "iam-service" +} +``` + +### Tracing (Jaeger) + +**Trace Spans:** +- Xử lý request HTTP +- Truy vấn database +- Thao tác cache +- Lời gọi API bên ngoài +- Luồng xác thực +- Kiểm tra phân quyền + +**Correlation IDs:** +- Mọi request nhận được một correlation ID duy nhất +- Được truyền qua các lời gọi service +- Được bao gồm trong tất cả logs và traces + +--- + +## Kiến Trúc Triển Khai + +IAM Service có thể được triển khai trong nhiều cấu hình: ### Phát Triển Cục Bộ -1. **Setup Infrastructure**: `docker-compose up -d` -2. **Install Dependencies**: `pnpm install` -3. **Database Setup**: `pnpm prisma migrate dev && pnpm prisma db seed` -4. **Start Development**: `pnpm dev` -5. **Run Tests**: `pnpm test` +```mermaid +graph LR + Developer[Developer
Localhost] --> LocalIAM[IAM Service
pnpm dev
Port 3001] -### Chiến Lược Kiểm Thử + LocalIAM --> LocalDB[(PostgreSQL
Docker
Port 5432)] + LocalIAM --> LocalRedis[(Redis
Docker
Port 6379)] -1. **Unit Tests**: Test các functions và classes riêng lẻ -2. **Integration Tests**: Test middleware chains và service interactions -3. **E2E Tests**: Test complete API workflows -4. **Performance Tests**: Load testing và performance validation + style LocalIAM fill:#e1f5fe + style LocalDB fill:#f3e5f5 + style LocalRedis fill:#fff3e0 +``` -### Pipeline Triển Khai - -1. **Linting**: Code quality checks với ESLint và Prettier -2. **Testing**: Full test suite execution (unit, integration, E2E) -3. **Security Scanning**: Dependency audit, SAST, và container scanning -4. **Build**: Multi-stage Docker image creation với security scanning -5. **Deploy**: Container orchestration deployment với health checks -6. **Verification**: Automated post-deployment health và performance verification - ---- - -# Phần 2: Tích Hợp Nền Tảng (Ngoại vi) - -Phần này mô tả cách một service được xây dựng từ template này tích hợp với nền tảng microservices GoodGo. - -## Kiến Trúc Nền Tảng +### Docker Compose (Multi-Service) ```mermaid -graph TD - Client[Client / Browser] --> Traefik[Traefik API Gateway] - - subgraph Platform[Nền Tảng Microservices GoodGo] - Traefik --> IAMService[IAM Service] - Traefik --> YourService[Service Của Bạn từ Template] - Traefik --> OtherServices[Các Services Khác...] - - YourService --> SharedDB[(PostgreSQL Chung)] - YourService --> SharedRedis[(Redis Chung)] - - IAMService -.->|JWT Validation| YourService - YourService -.->|Inter-Service Calls| OtherServices +graph TB + subgraph "Docker Compose Network" + Traefik[Traefik Gateway
Port 80/443] + + Traefik --> IAMService[IAM Service
Port 3001] + Traefik --> ProductService[Product Service
Port 3002] + Traefik --> OrderService[Order Service
Port 3003] + + IAMService --> SharedDB[(PostgreSQL
Port 5432)] + IAMService --> SharedRedis[(Redis
Port 6379)] + + ProductService --> SharedDB + ProductService --> SharedRedis + + OrderService --> SharedDB + OrderService --> SharedRedis end - - subgraph Observability[Observability Stack] - Prometheus[Prometheus] - Grafana[Grafana] - Jaeger[Jaeger] - Loki[Loki] - end - - YourService -.->|Metrics| Prometheus - YourService -.->|Traces| Jaeger - YourService -.->|Logs| Loki - Prometheus --> Grafana - + style Traefik fill:#ffecb3 - style YourService fill:#e1f5fe + style IAMService fill:#e1f5fe + style SharedDB fill:#f3e5f5 + style SharedRedis fill:#fff3e0 ``` -## Service Discovery & Đăng Ký +### Kubernetes (Production) -Các service được đăng ký với Traefik qua Docker labels trong `deployments/local/docker-compose.yml`: +```mermaid +graph TB + subgraph "Ingress Layer" + Ingress[Ingress Controller
NGINX/Traefik
TLS Termination] + end -```yaml -services: - your-service: - build: - context: ../.. - dockerfile: services/your-service/Dockerfile - labels: - # Bật Traefik cho service này - - "traefik.enable=true" - - # Định nghĩa routing rule - - "traefik.http.routers.your-service.rule=PathPrefix(`/api/v1/your-service`)" - - # Chỉ định service port - - "traefik.http.services.your-service.loadbalancer.server.port=5002" - - # Cấu hình health check - - "traefik.http.services.your-service.loadbalancer.healthcheck.path=/health/live" - - "traefik.http.services.your-service.loadbalancer.healthcheck.interval=10s" + subgraph "Application Layer" + IAMPod1[IAM Pod 1
Replica 1] + IAMPod2[IAM Pod 2
Replica 2] + IAMPod3[IAM Pod 3
Replica 3] + + IAMService[IAM Service
ClusterIP] + end + + subgraph "Data Layer" + PostgreSQL[(PostgreSQL
StatefulSet
Persistent Volume)] + Redis[(Redis
StatefulSet
Sentinel HA)] + end + + subgraph "Observability" + Prometheus[Prometheus
Metrics] + Jaeger[Jaeger
Tracing] + Loki[Loki
Logs] + end + + Ingress --> IAMService + IAMService --> IAMPod1 + IAMService --> IAMPod2 + IAMService --> IAMPod3 + + IAMPod1 --> PostgreSQL + IAMPod1 --> Redis + IAMPod2 --> PostgreSQL + IAMPod2 --> Redis + IAMPod3 --> PostgreSQL + IAMPod3 --> Redis + + IAMPod1 -.-> Prometheus + IAMPod1 -.-> Jaeger + IAMPod1 -.-> Loki + + style Ingress fill:#ffecb3 + style IAMPod1 fill:#e1f5fe + style IAMPod2 fill:#e1f5fe + style IAMPod3 fill:#e1f5fe + style PostgreSQL fill:#f3e5f5 + style Redis fill:#fff3e0 ``` -## Hạ Tầng Chung +### Thực Tiễn Tốt Cho Production -### Traefik API Gateway (infra/traefik/) +1. **Tính Sẵn Sàng Cao**: + - Nhiều replica IAM service (3+) + - Replication PostgreSQL (primary + standby) + - Redis Sentinel cho failover -- **Vị trí**: `infra/traefik/` - Cấu hình cấp độ nền tảng -- **Static Config**: `traefik.yml` - Entry points, providers, API dashboard -- **Dynamic Config**: `dynamic/middlewares.yml`, `dynamic/routes.yml` -- **Tính năng**: Load balancing, rate limiting, SSL/TLS, CORS, security headers +2. **Bảo Mật**: + - TLS/SSL cho tất cả kết nối + - Network policies cho giao tiếp pod-to-pod + - Quản lý secrets (HashiCorp Vault, AWS Secrets Manager) + - Container không phải root -### PostgreSQL Database +3. **Giới Hạn Tài Nguyên**: + ```yaml + resources: + requests: + cpu: 500m + memory: 512Mi + limits: + cpu: 2000m + memory: 2Gi + ``` -- **Shared hoặc Isolated**: Có thể là shared database với schema isolation hoặc databases riêng biệt -- **Connection**: Qua biến môi trường `DATABASE_URL` -- **Migrations**: Quản lý per-service với Prisma +4. **Health Checks**: + ```yaml + livenessProbe: + httpGet: + path: /health/live + port: 3001 + initialDelaySeconds: 30 + periodSeconds: 10 -### Redis Cache + readinessProbe: + httpGet: + path: /health/ready + port: 3001 + initialDelaySeconds: 10 + periodSeconds: 5 + ``` -- **Shared Instance**: Redis instance chung cho tất cả services -- **Connection**: Qua `REDIS_URL` hoặc `REDIS_HOST`/`REDIS_PORT` -- **Use Cases**: Caching, rate limiting, session storage - -### Observability Stack (infra/observability/) - -- **Prometheus**: Thu thập metrics từ tất cả services -- **Grafana**: Visualization và dashboards -- **Jaeger**: Distributed tracing -- **Loki**: Log aggregation - -## Giao Tiếp Giữa Các Service - -### HTTP/REST Communication - -Services giao tiếp qua HTTP thông qua Traefik hoặc direct service-to-service calls: - -```typescript -// Ví dụ: Gọi service khác -const response = await fetch('http://iam-service:5001/api/v1/users/validate', { - headers: { - 'Authorization': `Bearer ${token}`, - 'X-Correlation-ID': correlationId - } -}); -``` - -### Authentication Flow - -1. Client xác thực với Auth Service -2. Auth Service phát hành JWT token -3. Client bao gồm JWT trong requests đến các services khác -4. Services validate JWT sử dụng `@goodgo/auth-sdk` -5. Services trích xuất user info từ validated token +5. **Horizontal Pod Autoscaling**: + ```yaml + minReplicas: 3 + maxReplicas: 10 + targetCPUUtilizationPercentage: 70 + ``` --- -# Phần 3: Bối Cảnh Triển Khai +## Bước Tiếp Theo -Phần này giải thích cách triển khai một service được xây dựng từ template này lên nền tảng. +- **Hướng Dẫn Người Dùng**: Xem [GETTING-STARTED.md](./guides/01-GETTING-STARTED.md) để biết hướng dẫn thiết lập +- **Tham Chiếu API**: Xem [API_REFERENCE.md](./API_REFERENCE.md) để biết tài liệu endpoint hoàn chỉnh +- **Mô Hình Bảo Mật**: Xem [SECURITY-MODEL.md](./concepts/SECURITY-MODEL.md) để biết chi tiết bảo mật +- **Mô Hình Dữ Liệu**: Xem [DATA-MODEL.md](./concepts/DATA-MODEL.md) để biết schema database +- **Triển Khai**: Xem [DEPLOYMENT-GUIDE.md](./deployment/DEPLOYMENT-GUIDE.md) để biết hướng dẫn triển khai -## Thêm Service Vào Nền Tảng +--- -### Bước 1: Tạo Service từ Template +## Tham Chiếu -```bash -# Sử dụng create-service script -./scripts/utils/create-service.sh my-new-service +- **Security Skill**: [.cursor/skills/security/SKILL.md](../../../.cursor/skills/security/SKILL.md) +- **IAM Proposal**: [docs/en/architecture/iam-proposal.md](../../../docs/en/architecture/iam-proposal.md) +- **Migration Guide**: [docs/en/guides/iam-migration.md](../../../docs/en/guides/iam-migration.md) +- **Prisma Schema**: [prisma/schema.prisma](../prisma/schema.prisma) +- **Routes Definition**: [src/routes/index.ts](../src/routes/index.ts) -# Hoặc copy template thủ công -cp -r services/_template services/my-new-service -``` +--- -### Bước 2: Đăng Ký trong deployments/local/docker-compose.yml - -Thêm service của bạn vào platform compose file: - -```yaml -services: - my-new-service: - build: - context: ../.. - dockerfile: services/my-new-service/Dockerfile - container_name: my-new-service-local - environment: - - NODE_ENV=development - - PORT=5003 - - DATABASE_URL=${DATABASE_URL} - - REDIS_HOST=redis - - REDIS_PORT=6379 - - JWT_SECRET=${JWT_SECRET} - - SERVICE_NAME=my-new-service - - API_VERSION=v1 - depends_on: - redis: - condition: service_healthy - networks: - - microservices-network - labels: - - "traefik.enable=true" - - "traefik.http.routers.my-new-service.rule=PathPrefix(`/api/v1/my-new-service`)" - - "traefik.http.services.my-new-service.loadbalancer.server.port=5003" -``` - -### Bước 3: Cấu Hình Traefik Routes (Tùy chọn) - -Để định tuyến nâng cao, thêm vào `infra/traefik/dynamic/routes.yml`: - -```yaml -http: - routers: - my-new-service: - rule: "PathPrefix(`/api/v1/my-new-service`)" - service: my-new-service - middlewares: - - secure-headers - - cors - - compress -``` - -### Bước 4: Khởi Động Nền Tảng - -```bash -cd deployments/local -docker-compose up -d -``` - -### Bước 5: Truy Cập Service Của Bạn - -- **API**: http://localhost/api/v1/my-new-service -- **Health**: http://localhost/api/v1/my-new-service/health -- **API Docs**: http://localhost/api/v1/my-new-service/api-docs -- **Traefik Dashboard**: http://localhost:8080 - -## Cấu Hình Môi Trường - -Services kế thừa biến môi trường từ: - -1. **Platform Level**: `deployments/local/.env.local` -2. **Service Level**: Service-specific environment trong docker-compose.yml -3. **Defaults**: `.env.example` của service cho development - -## Xuất sắc Vận hành - -### Phản hồi Sự cố - -1. **Detection**: Automated monitoring alerts -2. **Assessment**: Incident severity classification -3. **Communication**: Stakeholder notification -4. **Investigation**: Root cause analysis -5. **Resolution**: Fix deployment và verification -6. **Post-mortem**: Incident review và improvement - -### Lập kế hoạch Dung lượng - -- **Resource Monitoring**: Theo dõi CPU, memory, disk, và network usage -- **Performance Benchmarks**: Regular performance testing -- **Scaling Triggers**: Automated scaling dựa trên metrics -- **Cost Optimization**: Right-sizing resources - -### Tuân thủ & Bảo mật - -- **Security Audits**: Regular security assessments -- **Compliance Checks**: GDPR, HIPAA, SOC2 compliance -- **Data Encryption**: At-rest và in-transit encryption -- **Access Controls**: Least privilege access principles +**Cập Nhật Lần Cuối**: Tháng 1 năm 2026 +**Phiên Bản**: 1.0.0 +**Trạng Thái**: Sẵn Sàng Production diff --git a/services/iam-service/docs/FEATURES.md b/services/iam-service/docs/FEATURES.md index 4a885856..2280133c 100644 --- a/services/iam-service/docs/FEATURES.md +++ b/services/iam-service/docs/FEATURES.md @@ -62,6 +62,49 @@ - [x] Audit Logging - [x] Event Sourcing +### Identity Management +- [x] User Lifecycle Management (CRUD) +- [x] User Deactivation & Reactivation +- [x] Bulk User Import/Export +- [x] Extended User Profiles +- [x] Profile Avatar Management +- [x] Email Verification +- [x] Phone Verification +- [x] Multi-Tenant Organizations +- [x] Organization Hierarchy +- [x] Groups with Hierarchical Structure +- [x] Group Member Management + +### Access Management +- [x] Access Request Workflows +- [x] Multi-Person Approval Chains +- [x] Access Request Approval/Rejection +- [x] Access Reviews & Certification +- [x] Access Review Campaigns +- [x] Access Review Items +- [x] Access Usage Analytics +- [x] Permission Analytics +- [x] User Access Summary +- [x] Risk Analytics + +### Governance & Compliance +- [x] GDPR Compliance Reporting +- [x] SOC2 Compliance Reporting +- [x] ISO27001 Compliance Reporting +- [x] HIPAA Compliance Support +- [x] Compliance Report Generation +- [x] Compliance Report Export +- [x] Policy Templates +- [x] Policy Versioning +- [x] Policy Testing +- [x] Risk Scoring +- [x] Risk Dashboard +- [x] Access Summary Reports +- [x] User Activity Reports +- [x] Security Events Reports +- [x] Compliance Status Reports +- [x] Risk Overview Reports + ### Performance - [x] Multi-layer Caching (Memory → Redis) - [x] Token Caching @@ -70,6 +113,11 @@ ## 📋 API Endpoints Summary +### Health (3 endpoints) +- `GET /health` - Basic health check +- `GET /health/ready` - Readiness probe +- `GET /health/live` - Liveness probe + ### Authentication (6 endpoints) - `POST /api/v1/auth/register` - Register - `POST /api/v1/auth/login` - Login @@ -112,7 +160,106 @@ - `DELETE /api/v1/sessions/:sessionId` - Revoke session - `DELETE /api/v1/sessions` - Revoke all sessions -**Total: 30+ API endpoints** +### Identity Management (30 endpoints) + +#### User Management (8 endpoints) +- `GET /api/v1/identity/users` - List users +- `GET /api/v1/identity/users/:id` - Get user +- `PUT /api/v1/identity/users/:id` - Update user +- `DELETE /api/v1/identity/users/:id` - Delete user +- `POST /api/v1/identity/users/:id/deactivate` - Deactivate user +- `POST /api/v1/identity/users/:id/reactivate` - Reactivate user +- `POST /api/v1/identity/users/bulk-import` - Bulk import users +- `GET /api/v1/identity/users/bulk-export` - Bulk export users + +#### Profile Management (4 endpoints) +- `GET /api/v1/identity/users/:id/profile` - Get profile +- `PUT /api/v1/identity/users/:id/profile` - Update profile +- `POST /api/v1/identity/users/:id/profile/avatar` - Upload avatar +- `DELETE /api/v1/identity/users/:id/profile/avatar` - Delete avatar + +#### Identity Verification (5 endpoints) +- `POST /api/v1/identity/verification/email/request` - Request email verification +- `POST /api/v1/identity/verification/email/verify` - Verify email +- `POST /api/v1/identity/verification/phone/request` - Request phone verification +- `POST /api/v1/identity/verification/phone/verify` - Verify phone +- `GET /api/v1/identity/verification/:id/status` - Get verification status + +#### Organizations (5 endpoints) +- `GET /api/v1/identity/organizations` - List organizations +- `POST /api/v1/identity/organizations` - Create organization +- `GET /api/v1/identity/organizations/:id` - Get organization +- `PUT /api/v1/identity/organizations/:id` - Update organization +- `DELETE /api/v1/identity/organizations/:id` - Delete organization +- `GET /api/v1/identity/organizations/:id/users` - Get organization users + +#### Groups (8 endpoints) +- `GET /api/v1/identity/organizations/:id/groups` - List groups +- `POST /api/v1/identity/organizations/:id/groups` - Create group +- `GET /api/v1/identity/groups/:id` - Get group +- `PUT /api/v1/identity/groups/:id` - Update group +- `DELETE /api/v1/identity/groups/:id` - Delete group +- `GET /api/v1/identity/groups/:id/members` - Get group members +- `POST /api/v1/identity/groups/:id/members` - Add member to group +- `DELETE /api/v1/identity/groups/:id/members/:userId` - Remove member from group + +### Access Management (16 endpoints) + +#### Access Requests (6 endpoints) +- `GET /api/v1/access/requests` - List access requests +- `POST /api/v1/access/requests` - Create access request +- `GET /api/v1/access/requests/:id` - Get access request +- `PUT /api/v1/access/requests/:id/approve` - Approve request +- `PUT /api/v1/access/requests/:id/reject` - Reject request +- `DELETE /api/v1/access/requests/:id` - Cancel request + +#### Access Reviews (7 endpoints) +- `GET /api/v1/access/reviews` - List access reviews +- `POST /api/v1/access/reviews` - Create access review +- `GET /api/v1/access/reviews/:id` - Get access review +- `POST /api/v1/access/reviews/:id/start` - Start review +- `POST /api/v1/access/reviews/:id/complete` - Complete review +- `GET /api/v1/access/reviews/:id/items` - Get review items +- `PUT /api/v1/access/reviews/:id/items/:itemId/review` - Review item + +#### Access Analytics (4 endpoints) +- `GET /api/v1/access/analytics/usage` - Get usage analytics +- `GET /api/v1/access/analytics/permissions` - Get permission analytics +- `GET /api/v1/access/analytics/users/:id/summary` - Get user access summary +- `GET /api/v1/access/analytics/risks` - Get risk analytics + +### Governance (17 endpoints) + +#### Compliance Reports (5 endpoints) +- `GET /api/v1/governance/compliance/reports` - List compliance reports +- `POST /api/v1/governance/compliance/reports/generate` - Generate report +- `GET /api/v1/governance/compliance/reports/:id` - Get report +- `GET /api/v1/governance/compliance/reports/:id/export` - Export report +- `POST /api/v1/governance/compliance/reports/:id/publish` - Publish report + +#### Policy Governance (4 endpoints) +- `GET /api/v1/governance/policies/templates` - List policy templates +- `POST /api/v1/governance/policies/templates` - Create template +- `GET /api/v1/governance/policies/:id/versions` - Get policy versions +- `POST /api/v1/governance/policies/:id/test` - Test policy + +#### Risk Management (4 endpoints) +- `GET /api/v1/governance/risk/scores` - List risk scores +- `GET /api/v1/governance/risk/scores/:userId` - Get user risk score +- `POST /api/v1/governance/risk/calculate` - Calculate risk +- `GET /api/v1/governance/risk/dashboard` - Get risk dashboard + +#### Reporting (5 endpoints) +- `GET /api/v1/governance/reports/access-summary` - Access summary report +- `GET /api/v1/governance/reports/user-activity` - User activity report +- `GET /api/v1/governance/reports/security-events` - Security events report +- `GET /api/v1/governance/reports/compliance-status` - Compliance status report +- `GET /api/v1/governance/reports/risk-overview` - Risk overview report + +### Monitoring (1 endpoint) +- `GET /metrics` - Prometheus metrics + +**Total: 50+ API endpoints** ## 🔄 Future Enhancements diff --git a/services/iam-service/docs/IMPLEMENTATION.md b/services/iam-service/docs/IMPLEMENTATION.md index d2e66de3..d52912db 100644 --- a/services/iam-service/docs/IMPLEMENTATION.md +++ b/services/iam-service/docs/IMPLEMENTATION.md @@ -1,35 +1,71 @@ -# IAM Service Implementation Summary +# IAM Service Implementation Details > **Note**: This document consolidates implementation details, completion status, and architecture overview. > For migration guide, see [IAM Migration Guide](../../docs/en/guides/iam-migration.md) > For architecture proposal, see [IAM Proposal](../../docs/en/architecture/iam-proposal.md) -## ✅ Completed Features +## Table of Contents + +- [Overview](#overview) +- [Completed Features](#completed-features) +- [Identity Management Implementation](#identity-management-implementation) +- [Access Management Implementation](#access-management-implementation) +- [Governance & Compliance Implementation](#governance--compliance-implementation) +- [Database Schema (30+ Models)](#database-schema-30-models) +- [Module Dependencies](#module-dependencies) +- [Configuration](#configuration) +- [Next Steps](#next-steps) + +--- + +## Overview + +The IAM Service is a comprehensive Identity and Access Management platform with **50+ API endpoints** across **10 feature modules** and **30+ database models**. This document details the implementation of all major features. + +### Implementation Statistics + +| Category | Count | Status | +|----------|-------|--------| +| **API Endpoints** | 50+ | ✅ Complete | +| **Database Models** | 30+ | ✅ Complete | +| **Feature Modules** | 10 | ✅ Complete | +| **Authentication Methods** | 7 | ✅ Complete | +| **Compliance Frameworks** | 4 | ✅ Complete | + +--- + +## Completed Features ### 1. Core Infrastructure -- ✅ Multi-layer caching (Memory → Redis) -- ✅ Database schema với Prisma (RBAC, Social, Sessions, MFA) +- ✅ Multi-layer caching (Memory → Redis → PostgreSQL) +- ✅ Database schema với Prisma (30+ models) - ✅ Event sourcing cho audit logs - ✅ Zero-trust security middleware +- ✅ Connection pooling +- ✅ Repository pattern implementation ### 2. Authentication -- ✅ User registration với password hashing -- ✅ Login với JWT tokens +- ✅ User registration với password hashing (bcrypt, cost 12) +- ✅ Login với JWT tokens (15min access, 7day refresh) - ✅ Logout với session revocation -- ✅ Token refresh mechanism -- ✅ Secure cookie management +- ✅ Token refresh mechanism với rotation +- ✅ Secure cookie management (HttpOnly, SameSite) +- ✅ Password change functionality ### 3. RBAC (Role-Based Access Control) - ✅ Roles và Permissions system - ✅ User-Role assignments với expiration - ✅ Direct user permissions (override roles) -- ✅ Permission caching +- ✅ Group-based permissions +- ✅ Permission caching (5min TTL) - ✅ RBAC middleware ### 4. ABAC (Attribute-Based Access Control) - ✅ Policy engine với JSON logic -- ✅ Policy evaluation +- ✅ Policy evaluation với priority - ✅ Time-based access control +- ✅ Location-based access control +- ✅ Attribute-based conditions ### 5. Social Authentication - ✅ Google OAuth 2.0 @@ -37,10 +73,11 @@ - ✅ GitHub OAuth - ✅ Circuit breaker cho external APIs - ✅ Account linking +- ✅ State token CSRF protection ### 6. OIDC (OpenID Connect) - ✅ OIDC Provider implementation -- ✅ Discovery endpoint +- ✅ Discovery endpoint (`/.well-known/openid-configuration`) - ✅ Authorization code flow - ✅ Token endpoint - ✅ UserInfo endpoint @@ -52,31 +89,36 @@ - ✅ QR code generation - ✅ MFA device management - ✅ MFA verification +- ✅ Backup codes generation +- ✅ Multiple devices per user ### 8. Session Management - ✅ Distributed sessions - ✅ Device fingerprinting - ✅ Session expiration -- ✅ Session revocation +- ✅ Session revocation (single/all) - ✅ Multiple device support +- ✅ IP address tracking ### 9. Security Features - ✅ Zero-trust validation - ✅ CSRF protection -- ✅ Dynamic rate limiting (based on roles) +- ✅ Dynamic rate limiting (based on roles: 50-1000 req/15min) - ✅ Device fingerprinting -- ✅ Audit logging +- ✅ Audit logging (event sourcing) +- ✅ Input validation (Zod schemas) ### 10. API Endpoints -#### Authentication +#### Authentication (5 endpoints) - `POST /api/v1/auth/register` - Register new user - `POST /api/v1/auth/login` - Login user - `POST /api/v1/auth/logout` - Logout user - `POST /api/v1/auth/refresh` - Refresh access token - `GET /api/v1/auth/me` - Get current user +- `POST /api/v1/auth/change-password` - Change password -#### Social Auth +#### Social Auth (6 endpoints) - `GET /api/v1/auth/google` - Initiate Google OAuth - `GET /api/v1/auth/google/callback` - Google callback - `GET /api/v1/auth/facebook` - Initiate Facebook OAuth @@ -84,66 +126,714 @@ - `GET /api/v1/auth/github` - Initiate GitHub OAuth - `GET /api/v1/auth/github/callback` - GitHub callback -#### OIDC +#### OIDC (5 endpoints) - `GET /.well-known/openid-configuration` - Discovery - `GET /api/v1/oidc/authorize` - Authorization - `POST /api/v1/oidc/token` - Token exchange - `GET /api/v1/oidc/userinfo` - User info - `GET /api/v1/oidc/jwks` - JWKS -#### RBAC +#### RBAC (4 endpoints) - `GET /api/v1/rbac/permissions` - Get user permissions - `POST /api/v1/rbac/roles/assign` - Assign role - `POST /api/v1/rbac/roles/revoke` - Revoke role - `POST /api/v1/rbac/permissions/grant` - Grant permission - `GET /api/v1/rbac/permissions/check` - Check permission -#### MFA +#### MFA (5 endpoints) - `POST /api/v1/mfa/totp/enable` - Enable TOTP - `POST /api/v1/mfa/totp/verify` - Verify and enable TOTP - `POST /api/v1/mfa/totp/validate` - Validate TOTP token - `POST /api/v1/mfa/disable` - Disable MFA - `GET /api/v1/mfa/devices` - Get MFA devices -## 📋 Database Schema +#### Session Management (3 endpoints) +- `GET /api/v1/sessions` - Get user sessions +- `DELETE /api/v1/sessions/:sessionId` - Revoke session +- `DELETE /api/v1/sessions` - Revoke all sessions -### Models -- `User` - User accounts -- `Role` - RBAC roles -- `Permission` - Granular permissions -- `UserRole` - User-role assignments -- `RolePermission` - Role-permission mappings -- `UserPermission` - Direct user permissions -- `Session` - Active sessions -- `RefreshToken` - Refresh tokens -- `SocialAccount` - Social login accounts -- `MFADevice` - MFA devices -- `AuthEvent` - Audit events -- `Policy` - ABAC policies +--- -## 🔧 Configuration +## Identity Management Implementation + +### Overview + +The Identity Management module provides comprehensive user lifecycle management, profile management, identity verification, and organizational structure support. + +### Implementation Details + +#### 1. User Management Service + +**Location**: `src/modules/identity/user/user.service.ts` + +**Features**: +- User CRUD operations +- User listing with filters (email, organization, status) +- User deactivation/reactivation +- Bulk user import/export (CSV) +- User search and pagination +- Permission-aware access control + +**Key Methods**: +```typescript +- getUser(userId: string): Get user by ID with permissions +- listUsers(filters: UserFiltersDto): List users with pagination +- updateUser(userId: string, data: UpdateUserDto): Update user +- deleteUser(userId: string): Soft delete user +- deactivateUser(userId: string): Deactivate user account +- reactivateUser(userId: string): Reactivate user account +- bulkImportUsers(data: BulkImportUsersDto): Import users from CSV +- bulkExportUsers(filters: UserFiltersDto): Export users to CSV +``` + +**Endpoints** (8 endpoints): +- `GET /api/v1/identity/users` - List users +- `GET /api/v1/identity/users/:id` - Get user +- `PUT /api/v1/identity/users/:id` - Update user +- `DELETE /api/v1/identity/users/:id` - Delete user +- `POST /api/v1/identity/users/:id/deactivate` - Deactivate user +- `POST /api/v1/identity/users/:id/reactivate` - Reactivate user +- `POST /api/v1/identity/users/bulk-import` - Bulk import users +- `GET /api/v1/identity/users/bulk-export` - Bulk export users + +#### 2. Profile Management Service + +**Location**: `src/modules/identity/profile/profile.service.ts` + +**Features**: +- Extended user profile information +- Custom fields support (JSON) +- Avatar upload/management +- User preferences storage +- Phone number verification integration + +**Key Methods**: +```typescript +- getProfile(userId: string): Get user profile +- updateProfile(userId: string, data: UpdateUserProfileDto): Update profile +- uploadAvatar(userId: string, file: Express.Multer.File): Upload avatar +- deleteAvatar(userId: string): Delete avatar +``` + +**Endpoints** (4 endpoints): +- `GET /api/v1/identity/users/:id/profile` - Get profile +- `PUT /api/v1/identity/users/:id/profile` - Update profile +- `POST /api/v1/identity/users/:id/profile/avatar` - Upload avatar +- `DELETE /api/v1/identity/users/:id/profile/avatar` - Delete avatar + +#### 3. Identity Verification Service + +**Location**: `src/modules/identity/verification/verification.service.ts` + +**Features**: +- Email verification with OTP tokens +- Phone verification with SMS OTP +- Document verification (future) +- Verification status tracking +- Token expiration management + +**Key Methods**: +```typescript +- requestEmailVerification(userId: string): Request email verification +- verifyEmail(token: string): Verify email with token +- requestPhoneVerification(userId: string, phone: string): Request phone verification +- verifyPhone(token: string, code: string): Verify phone with OTP +- getVerificationStatus(verificationId: string): Get verification status +``` + +**Endpoints** (5 endpoints): +- `POST /api/v1/identity/verification/email/request` - Request email verification +- `POST /api/v1/identity/verification/email/verify` - Verify email +- `POST /api/v1/identity/verification/phone/request` - Request phone verification +- `POST /api/v1/identity/verification/phone/verify` - Verify phone +- `GET /api/v1/identity/verification/:id/status` - Get verification status + +#### 4. Organization Service + +**Location**: `src/modules/identity/organization/organization.service.ts` + +**Features**: +- Multi-tenant organization support +- Hierarchical organization structure (parent-child) +- Organization settings (JSON) +- Domain-based organization identification +- User-organization relationships + +**Key Methods**: +```typescript +- createOrganization(data: CreateOrganizationDto): Create organization +- getOrganization(orgId: string): Get organization +- updateOrganization(orgId: string, data: UpdateOrganizationDto): Update organization +- deleteOrganization(orgId: string): Delete organization +- getOrganizationUsers(orgId: string): Get users in organization +- listOrganizations(filters: OrganizationFiltersDto): List organizations +``` + +**Endpoints** (5 endpoints): +- `GET /api/v1/identity/organizations` - List organizations +- `POST /api/v1/identity/organizations` - Create organization +- `GET /api/v1/identity/organizations/:id` - Get organization +- `PUT /api/v1/identity/organizations/:id` - Update organization +- `DELETE /api/v1/identity/organizations/:id` - Delete organization +- `GET /api/v1/identity/organizations/:id/users` - Get organization users + +#### 5. Group Service + +**Location**: `src/modules/identity/group/group.service.ts` + +**Features**: +- Organization-scoped groups +- Group membership management +- Group permissions inheritance +- Member roles within groups +- Group expiration support + +**Key Methods**: +```typescript +- createGroup(organizationId: string, data: CreateGroupDto): Create group +- getGroup(groupId: string): Get group with members +- updateGroup(groupId: string, data: UpdateGroupDto): Update group +- deleteGroup(groupId: string): Delete group +- getGroupMembers(groupId: string): Get group members +- addGroupMember(groupId: string, userId: string, role?: string): Add member +- removeGroupMember(groupId: string, userId: string): Remove member +``` + +**Endpoints** (7 endpoints): +- `GET /api/v1/identity/organizations/:id/groups` - List groups +- `POST /api/v1/identity/organizations/:id/groups` - Create group +- `GET /api/v1/identity/groups/:id` - Get group +- `PUT /api/v1/identity/groups/:id` - Update group +- `DELETE /api/v1/identity/groups/:id` - Delete group +- `GET /api/v1/identity/groups/:id/members` - Get members +- `POST /api/v1/identity/groups/:id/members` - Add member +- `DELETE /api/v1/identity/groups/:id/members/:userId` - Remove member + +### Identity Management Models + +- **User**: Core user entity with email, password, MFA, organization +- **UserProfile**: Extended user information (name, phone, avatar, custom fields) +- **Organization**: Multi-tenant organizations with hierarchy +- **Group**: Organization-scoped user groups +- **GroupMember**: Group membership with roles +- **IdentityVerification**: Email/phone/document verification records + +--- + +## Access Management Implementation + +### Overview + +The Access Management module provides access request workflows, access reviews, certification campaigns, and access analytics. + +### Implementation Details + +#### 1. Access Request Service + +**Location**: `src/modules/access/request/request.service.ts` + +**Features**: +- Access request creation and management +- Multi-person approval workflows +- Request status tracking (PENDING, APPROVED, REJECTED, EXPIRED, CANCELLED) +- Automatic expiration handling +- Integration with RBAC for permission granting + +**Key Methods**: +```typescript +- createRequest(userId: string, data: CreateAccessRequestDto): Create access request +- getRequest(requestId: string): Get request details +- getUserRequests(userId: string): Get user's requests +- approveRequest(requestId: string, approverId: string, comments?: string): Approve request +- rejectRequest(requestId: string, approverId: string, comments?: string): Reject request +- cancelRequest(requestId: string, userId: string): Cancel request +``` + +**Endpoints** (6 endpoints): +- `GET /api/v1/access/requests` - List access requests +- `POST /api/v1/access/requests` - Create access request +- `GET /api/v1/access/requests/:id` - Get request +- `PUT /api/v1/access/requests/:id/approve` - Approve request +- `PUT /api/v1/access/requests/:id/reject` - Reject request +- `DELETE /api/v1/access/requests/:id` - Cancel request + +**Workflow**: +1. User creates access request with resource, action, and reason +2. System identifies required approvers based on policy +3. Approvers review and approve/reject +4. On approval, permissions are granted via RBAC service +5. Request status updated and audit logged + +#### 2. Access Review Service + +**Location**: `src/modules/access/review/review.service.ts` + +**Features**: +- Access certification campaigns +- Periodic and ad-hoc reviews +- Review item management +- Reviewer assignment +- Review completion tracking + +**Key Methods**: +```typescript +- createReview(data: CreateAccessReviewDto, createdBy: string): Create review +- getReview(reviewId: string): Get review details +- startReview(reviewId: string): Start review campaign +- completeReview(reviewId: string): Complete review +- getReviewItems(reviewId: string): Get review items +- reviewItem(itemId: string, reviewerId: string, status: ReviewItemStatus, comments?: string): Review item +``` + +**Endpoints** (7 endpoints): +- `GET /api/v1/access/reviews` - List reviews +- `POST /api/v1/access/reviews` - Create review +- `GET /api/v1/access/reviews/:id` - Get review +- `POST /api/v1/access/reviews/:id/start` - Start review +- `POST /api/v1/access/reviews/:id/complete` - Complete review +- `GET /api/v1/access/reviews/:id/items` - Get review items +- `PUT /api/v1/access/reviews/:id/items/:itemId/review` - Review item + +**Review Types**: +- **Periodic**: Scheduled reviews (quarterly, annual) +- **Ad-hoc**: On-demand reviews +- **Certification**: Compliance certification campaigns + +#### 3. Access Analytics Service + +**Location**: `src/modules/access/analytics/analytics.service.ts` + +**Features**: +- Access usage analytics +- Permission usage tracking +- User access summaries +- Risk analysis and anomaly detection +- Access pattern reporting + +**Key Methods**: +```typescript +- getUsageAnalytics(filters: AnalyticsFiltersDto): Get usage analytics +- getPermissionAnalytics(filters: AnalyticsFiltersDto): Get permission usage +- getUserAccessSummary(userId: string): Get user access summary +- getRiskAnalytics(filters: AnalyticsFiltersDto): Get risk analytics +``` + +**Endpoints** (4 endpoints): +- `GET /api/v1/access/analytics/usage` - Get usage analytics +- `GET /api/v1/access/analytics/permissions` - Get permission analytics +- `GET /api/v1/access/analytics/users/:id/summary` - Get user summary +- `GET /api/v1/access/analytics/risks` - Get risk analytics + +### Access Management Models + +- **AccessRequest**: Access request records with status and metadata +- **AccessRequestApprover**: Multi-person approval tracking +- **AccessReview**: Review campaign records +- **AccessReviewItem**: Individual items within reviews + +--- + +## Governance & Compliance Implementation + +### Overview + +The Governance module provides compliance reporting (GDPR, SOC2, ISO27001, HIPAA), policy governance, risk management, and comprehensive reporting. + +### Implementation Details + +#### 1. Compliance Service + +**Location**: `src/modules/governance/compliance/compliance.service.ts` + +**Features**: +- GDPR compliance reporting +- SOC2 compliance reporting +- ISO27001 compliance reporting +- HIPAA compliance support +- Custom compliance frameworks +- Report generation and export +- Report publishing workflow + +**Key Methods**: +```typescript +- generateReport(type: ComplianceType, periodStart: Date, periodEnd: Date, generatedBy: string): Generate report +- getReports(filters: ReportFiltersDto): List reports +- getReport(reportId: string): Get report details +- exportReport(reportId: string, format: 'json' | 'csv' | 'pdf'): Export report +- publishReport(reportId: string): Publish report +- generateGDPRReport(periodStart: Date, periodEnd: Date): Generate GDPR report +- generateSOC2Report(periodStart: Date, periodEnd: Date): Generate SOC2 report +- generateISO27001Report(periodStart: Date, periodEnd: Date): Generate ISO27001 report +``` + +**Endpoints** (5 endpoints): +- `GET /api/v1/governance/compliance/reports` - List reports +- `POST /api/v1/governance/compliance/reports/generate` - Generate report +- `GET /api/v1/governance/compliance/reports/:id` - Get report +- `GET /api/v1/governance/compliance/reports/:id/export` - Export report +- `POST /api/v1/governance/compliance/reports/:id/publish` - Publish report + +**Compliance Frameworks**: +- **GDPR**: Data protection, right to access, right to deletion, consent tracking +- **SOC2**: Access controls, monitoring, incident response, change management +- **ISO27001**: Information security management, risk assessment, controls +- **HIPAA**: Healthcare data protection, access controls, audit trails + +#### 2. Policy Governance Service + +**Location**: `src/modules/governance/policy/policy-governance.service.ts` + +**Features**: +- Policy template management +- Policy versioning +- Policy testing and validation +- Policy categories +- Template-based policy creation + +**Key Methods**: +```typescript +- createTemplate(data: CreatePolicyTemplateDto): Create policy template +- getTemplates(category?: string): List templates +- getTemplateVersions(templateId: string): Get template versions +- testPolicy(data: TestPolicyDto): Test policy evaluation +``` + +**Endpoints** (4 endpoints): +- `GET /api/v1/governance/policies/templates` - List templates +- `POST /api/v1/governance/policies/templates` - Create template +- `GET /api/v1/governance/policies/:id/versions` - Get versions +- `POST /api/v1/governance/policies/:id/test` - Test policy + +#### 3. Risk Management Service + +**Location**: `src/modules/governance/risk/risk.service.ts` + +**Features**: +- User risk scoring (0-100) +- Risk level calculation (LOW, MEDIUM, HIGH, CRITICAL) +- Risk factor analysis +- Risk dashboard +- Risk score history + +**Key Methods**: +```typescript +- calculateRiskScore(userId: string): Calculate user risk score +- getRiskScore(userId: string): Get current risk score +- getRiskScores(filters: RiskFiltersDto): List risk scores +- getRiskDashboard(): Get risk dashboard data +``` + +**Endpoints** (4 endpoints): +- `GET /api/v1/governance/risk/scores` - List risk scores +- `GET /api/v1/governance/risk/scores/:userId` - Get user risk score +- `POST /api/v1/governance/risk/calculate` - Calculate risk +- `GET /api/v1/governance/risk/dashboard` - Get risk dashboard + +**Risk Factors**: +- Failed login attempts +- Unusual location access +- New device detection +- High privilege access patterns +- Inactivity periods +- Open access requests +- Permission changes + +#### 4. Reporting Service + +**Location**: `src/modules/governance/reporting/reporting.service.ts` + +**Features**: +- Access summary reports +- User activity reports +- Security event reports +- Compliance status reports +- Risk overview reports + +**Key Methods**: +```typescript +- getAccessSummary(filters: ReportFiltersDto): Get access summary +- getUserActivity(filters: ReportFiltersDto): Get user activity +- getSecurityEvents(filters: ReportFiltersDto): Get security events +- getComplianceStatus(): Get compliance status +- getRiskOverview(): Get risk overview +``` + +**Endpoints** (5 endpoints): +- `GET /api/v1/governance/reports/access-summary` - Access summary +- `GET /api/v1/governance/reports/user-activity` - User activity +- `GET /api/v1/governance/reports/security-events` - Security events +- `GET /api/v1/governance/reports/compliance-status` - Compliance status +- `GET /api/v1/governance/reports/risk-overview` - Risk overview + +### Governance Models + +- **ComplianceReport**: Compliance report records with type, period, status, and data +- **PolicyTemplate**: Reusable policy templates with versioning +- **RiskScore**: User risk scores with factors and levels + +--- + +## Database Schema (30+ Models) + +### Model Categories + +#### 1. Core Authentication (7 models) + +| Model | Purpose | Key Fields | +|-------|---------|------------| +| **User** | Core user entity | id, email, username, passwordHash, isActive, mfaEnabled, organizationId | +| **Session** | Active user sessions | id, userId, deviceId, deviceName, ipAddress, fingerprint, expiresAt | +| **RefreshToken** | Long-lived refresh tokens | id, userId, token, family, deviceId, expiresAt, revokedAt | +| **AuthEvent** | Audit log events | id, userId, eventType, eventData, ipAddress, success, timestamp | +| **SocialAccount** | OAuth provider accounts | id, userId, provider, providerId, email, accessToken, refreshToken | +| **MFADevice** | MFA devices | id, userId, type, name, secret, credentialId, isActive | +| **Policy** | ABAC policies | id, name, resource, condition, effect, priority, organizationId | + +#### 2. Authorization (6 models) + +| Model | Purpose | Key Fields | +|-------|---------|------------| +| **Role** | RBAC roles | id, name, displayName, description, isSystem | +| **Permission** | Granular permissions | id, resource, action, scope, description | +| **UserRole** | User-role assignments | id, userId, roleId, grantedBy, expiresAt | +| **RolePermission** | Role-permission mappings | id, roleId, permissionId | +| **UserPermission** | Direct user permissions | id, userId, permissionId, granted, grantedBy, expiresAt | +| **GroupPermission** | Group permissions | id, groupId, permissionId | + +#### 3. Identity Management (6 models) + +| Model | Purpose | Key Fields | +|-------|---------|------------| +| **Organization** | Multi-tenant organizations | id, name, domain, parentId, settings, isActive | +| **Group** | User groups | id, name, organizationId, description, isActive | +| **GroupMember** | Group membership | id, userId, groupId, role, joinedAt, expiresAt | +| **UserProfile** | Extended user info | id, userId, firstName, lastName, phone, avatarUrl, customFields | +| **IdentityVerification** | Verification records | id, userId, type, status, method, token, verifiedAt | + +#### 4. Access Management (4 models) + +| Model | Purpose | Key Fields | +|-------|---------|------------| +| **AccessRequest** | Access requests | id, userId, resource, action, reason, status, requestedAt, reviewedAt | +| **AccessRequestApprover** | Approval tracking | id, requestId, approverId, status, comments, reviewedAt | +| **AccessReview** | Review campaigns | id, name, type, status, startDate, endDate, createdBy | +| **AccessReviewItem** | Review items | id, reviewId, userId, resource, access, status, reviewedBy | + +#### 5. Governance (3 models) + +| Model | Purpose | Key Fields | +|-------|---------|------------| +| **ComplianceReport** | Compliance reports | id, type, name, periodStart, periodEnd, status, data, generatedAt | +| **PolicyTemplate** | Policy templates | id, name, category, description, content, version, isActive | +| **RiskScore** | Risk scores | id, userId, score, level, factors, calculatedAt | + +#### 6. Additional Models (4+ models) + +Additional models may include: +- Audit trail models +- Configuration models +- Feature flag models +- Integration models + +### Total: 30+ Models + +**Key Relationships**: +- User (1) → (*) UserRole → (*) Role → (*) RolePermission → (*) Permission +- User (1) → (*) UserPermission → (*) Permission +- User (1) → (1) UserProfile +- User (1) → (*) Session +- User (1) → (*) AccessRequest +- Organization (1) → (*) User +- Organization (1) → (*) Group → (*) GroupMember → (*) User +- Group (1) → (*) GroupPermission → (*) Permission + +--- + +## Module Dependencies + +### Architecture Layers + +``` +┌─────────────────────────────────────────┐ +│ Presentation Layer (Routes) │ +│ 50+ API Endpoints │ +└─────────────────────────────────────────┘ + ↓ +┌─────────────────────────────────────────┐ +│ Business Logic Layer (Modules) │ +│ │ +│ ┌──────────────┐ ┌──────────────┐ │ +│ │ Auth │ │ Identity │ │ +│ │ Token │ │ Profile │ │ +│ │ Session │ │ Org │ │ +│ │ RBAC │ │ Group │ │ +│ │ Social │ │ Verify │ │ +│ │ OIDC │ │ │ │ +│ │ MFA │ │ │ │ +│ └──────────────┘ └──────────────┘ │ +│ │ +│ ┌──────────────┐ ┌──────────────┐ │ +│ │ Access │ │ Governance │ │ +│ │ Request │ │ Compliance │ │ +│ │ Review │ │ Policy │ │ +│ │ Analytics │ │ Risk │ │ +│ │ │ │ Reporting │ │ +│ └──────────────┘ └──────────────┘ │ +└─────────────────────────────────────────┘ + ↓ +┌─────────────────────────────────────────┐ +│ Core Services Layer │ +│ Cache │ Audit │ Security │ Feature │ +└─────────────────────────────────────────┘ + ↓ +┌─────────────────────────────────────────┐ +│ Data Access Layer (Repositories) │ +│ Prisma ORM │ +└─────────────────────────────────────────┘ + ↓ +┌─────────────────────────────────────────┐ +│ Infrastructure Layer │ +│ PostgreSQL │ Redis │ +└─────────────────────────────────────────┘ +``` + +### Module Dependencies + +**Identity Module** depends on: +- RBAC Module (for permission checks) +- Cache Service (for user data caching) +- Audit Service (for audit logging) +- Organization Module (for organization context) +- Group Module (for group membership) + +**Access Module** depends on: +- RBAC Module (for permission granting/revoking) +- Identity Module (for user information) +- Audit Service (for request/review logging) +- Analytics Module (for usage tracking) + +**Governance Module** depends on: +- RBAC Module (for access data) +- Identity Module (for user data) +- Access Module (for access history) +- Audit Service (for compliance data) + +**All Modules** depend on: +- Cache Service (multi-layer caching) +- Audit Service (event sourcing) +- Security Service (encryption, hashing) +- Repository Layer (data access) + +--- + +## Configuration ### Environment Variables + See `env.local.example` for all required environment variables. ### Key Configurations -- JWT secrets (access, refresh, ID tokens) -- OAuth client IDs and secrets -- Database connection -- Redis connection -- OIDC issuer URL -## 🚀 Next Steps (Future Enhancements) +#### Database +- `DATABASE_URL`: PostgreSQL connection string +- `DATABASE_POOL_SIZE`: Connection pool size (default: 10) +- `DATABASE_TIMEOUT`: Query timeout in ms (default: 30000) -1. **Database Sharding** - For 100M+ users -2. **Multi-region Deployment** - High availability -3. **WebAuthn** - Advanced MFA -4. **OIDC Multi-tenancy** - Enterprise customers -5. **Load Testing** - K6 tests for 50k req/s -6. **Advanced Monitoring** - Datadog, ELK stack -7. **Rate Limiting Refinement** - ML-based behavior analysis +#### Redis +- `REDIS_HOST`: Redis host +- `REDIS_PORT`: Redis port (default: 6379) +- `REDIS_PASSWORD`: Redis password (optional) +- `REDIS_TTL_DEFAULT`: Default TTL in seconds (default: 300) -## 📝 Notes +#### JWT +- `JWT_ACCESS_SECRET`: Access token secret +- `JWT_REFRESH_SECRET`: Refresh token secret +- `JWT_ID_SECRET`: ID token secret (OIDC) +- `JWT_ACCESS_EXPIRY`: Access token expiry (default: 15m) +- `JWT_REFRESH_EXPIRY`: Refresh token expiry (default: 7d) + +#### OAuth +- `GOOGLE_CLIENT_ID`: Google OAuth client ID +- `GOOGLE_CLIENT_SECRET`: Google OAuth client secret +- `FACEBOOK_APP_ID`: Facebook OAuth app ID +- `FACEBOOK_APP_SECRET`: Facebook OAuth app secret +- `GITHUB_CLIENT_ID`: GitHub OAuth client ID +- `GITHUB_CLIENT_SECRET`: GitHub OAuth client secret + +#### OIDC +- `OIDC_ISSUER_URL`: OIDC issuer URL +- `OIDC_AUTHORIZATION_ENDPOINT`: Authorization endpoint +- `OIDC_TOKEN_ENDPOINT`: Token endpoint + +#### Security +- `BCRYPT_COST`: Bcrypt cost factor (default: 12) +- `RATE_LIMIT_ENABLED`: Enable rate limiting (default: true) +- `ZERO_TRUST_ENABLED`: Enable zero-trust validation (default: true) + +#### Application +- `PORT`: Server port (default: 3001) +- `NODE_ENV`: Environment (development, staging, production) +- `API_VERSION`: API version (default: v1) +- `LOG_LEVEL`: Logging level (error, warn, info, debug) + +### Cache Configuration + +| Data Type | L1 TTL | L2 TTL | Invalidation Strategy | +|-----------|--------|--------|----------------------| +| User Data | 60s | 15min | On user update/delete | +| Permissions | 60s | 5min | On role/permission change | +| User Roles | 60s | 5min | On role assignment/revocation | +| Token Validation | N/A | Token lifetime | On logout/revocation | +| Sessions | N/A | Session lifetime | On logout | +| Rate Limit Counters | N/A | 15min window | Time-based expiry | + +--- + +## Next Steps + +### Short-term Enhancements (1-3 months) + +1. **WebAuthn Support**: Implement FIDO2/WebAuthn for passwordless authentication +2. **Advanced Analytics**: Enhanced access analytics with ML-based anomaly detection +3. **Email/SMS Integration**: Integrate with email and SMS services for verification +4. **File Storage**: Integrate S3/GCS for avatar and document storage +5. **API Rate Limiting Refinement**: ML-based behavior analysis for dynamic limits + +### Medium-term Enhancements (3-6 months) + +1. **Multi-region Deployment**: High availability across regions +2. **Database Sharding**: Support for 100M+ users with sharding +3. **Advanced Compliance**: Additional compliance frameworks (PCI-DSS, FedRAMP) +4. **GraphQL API**: GraphQL endpoint for flexible queries +5. **Real-time Notifications**: WebSocket support for real-time updates + +### Long-term Enhancements (6-12 months) + +1. **Machine Learning**: ML-based risk scoring and anomaly detection +2. **Advanced Reporting**: Custom report builder with drag-and-drop +3. **Workflow Engine**: Custom workflow engine for access requests +4. **Integration Marketplace**: Pre-built integrations with common services +5. **Mobile SDKs**: Native iOS and Android SDKs + +### Performance Optimizations + +1. **Query Optimization**: Database query optimization and indexing +2. **Caching Strategy**: Enhanced caching with predictive pre-loading +3. **Connection Pooling**: Advanced connection pool management +4. **Load Testing**: K6 tests for 50k req/s throughput +5. **CDN Integration**: CDN for static assets and API responses + +### Monitoring & Observability + +1. **Advanced Monitoring**: Datadog, New Relic integration +2. **ELK Stack**: Centralized logging with ELK +3. **Distributed Tracing**: Enhanced Jaeger integration +4. **Custom Dashboards**: Grafana dashboards for all metrics +5. **Alerting**: Advanced alerting with PagerDuty integration + +--- + +## Notes - All code includes bilingual comments (EN/VI) - Follows GoodGo project standards @@ -151,3 +841,24 @@ See `env.local.example` for all required environment variables. - Implements repository pattern - Event sourcing for audit compliance - Zero-trust security by default +- Comprehensive error handling +- Input validation with Zod schemas +- Rate limiting with Redis +- Multi-layer caching strategy + +--- + +## Reference Files + +- **Architecture**: [ARCHITECTURE.en.md](./ARCHITECTURE.en.md) +- **Data Model**: [DATA-MODEL.md](./concepts/DATA-MODEL.md) +- **Core Concepts**: [CORE-CONCEPTS.md](./concepts/CORE-CONCEPTS.md) +- **API Reference**: [API_REFERENCE.md](./API_REFERENCE.md) +- **Prisma Schema**: [prisma/schema.prisma](../prisma/schema.prisma) +- **Routes**: [src/routes/index.ts](../src/routes/index.ts) + +--- + +**Last Updated**: January 2026 +**Version**: 1.0.0 +**Status**: Production Ready diff --git a/services/iam-service/docs/QUICK_START.md b/services/iam-service/docs/QUICK_START.md index 8911bb1a..1c88c176 100644 --- a/services/iam-service/docs/QUICK_START.md +++ b/services/iam-service/docs/QUICK_START.md @@ -30,7 +30,7 @@ pnpm prisma:seed pnpm dev ``` -Service will start on `http://localhost:4000` +Service will start on `http://localhost:3001` ## 📝 Default Credentials @@ -40,20 +40,21 @@ After seeding: ## 🔑 API Testing -### Register User +The IAM Service provides 50+ endpoints across 10 modules. Here are quick examples for the main modules: + +### Authentication Module ```bash -curl -X POST http://localhost:4000/api/v1/auth/register \ +curl -X POST http://localhost:3001/api/v1/auth/register \ -H "Content-Type: application/json" \ -d '{ "email": "user@example.com", - "password": "password123", - "username": "testuser" + "password": "SecurePass123!" }' ``` ### Login ```bash -curl -X POST http://localhost:4000/api/v1/auth/login \ +curl -X POST http://localhost:3001/api/v1/auth/login \ -H "Content-Type: application/json" \ -d '{ "email": "admin@goodgo.com", @@ -63,16 +64,64 @@ curl -X POST http://localhost:4000/api/v1/auth/login \ ### Get Current User ```bash -curl -X GET http://localhost:4000/api/v1/auth/me \ +curl -X GET http://localhost:3001/api/v1/auth/me \ -H "Authorization: Bearer YOUR_ACCESS_TOKEN" ``` ### Check Permissions ```bash -curl -X GET "http://localhost:4000/api/v1/rbac/permissions/check?resource=users&action=read&scope=all" \ +curl -X GET "http://localhost:3001/api/v1/rbac/permissions/check?resource=users&action=read&scope=all" \ -H "Authorization: Bearer YOUR_ACCESS_TOKEN" ``` +### Identity Management Module +Manage users, profiles, organizations, and groups: + +```bash +# List users +curl -X GET http://localhost:3001/api/v1/identity/users \ + -H "Authorization: Bearer YOUR_ACCESS_TOKEN" + +# Get user profile +curl -X GET http://localhost:3001/api/v1/identity/users/{userId}/profile \ + -H "Authorization: Bearer YOUR_ACCESS_TOKEN" +``` + +### Access Management Module +Handle access requests, reviews, and analytics: + +```bash +# Create access request +curl -X POST http://localhost:3001/api/v1/access/requests \ + -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \ + -H "Content-Type: application/json" \ + -d '{ + "resource": "users", + "action": "write", + "scope": "all", + "reason": "Need access to manage users" + }' + +# List access requests +curl -X GET http://localhost:3001/api/v1/access/requests \ + -H "Authorization: Bearer YOUR_ACCESS_TOKEN" +``` + +### Governance & Compliance Module +Compliance reporting, risk management, and policy templates: + +```bash +# Get risk scores +curl -X GET http://localhost:3001/api/v1/governance/risk/scores \ + -H "Authorization: Bearer YOUR_ACCESS_TOKEN" + +# List compliance reports +curl -X GET http://localhost:3001/api/v1/governance/compliance/reports \ + -H "Authorization: Bearer YOUR_ACCESS_TOKEN" +``` + +**For complete API documentation, see [API Reference](API_REFERENCE.md).** + ## 🔐 Social Login Setup ### Google OAuth @@ -82,7 +131,7 @@ curl -X GET "http://localhost:4000/api/v1/rbac/permissions/check?resource=users& ``` GOOGLE_CLIENT_ID=your-client-id GOOGLE_CLIENT_SECRET=your-client-secret - GOOGLE_REDIRECT_URI=http://localhost:4000/api/v1/auth/google/callback + GOOGLE_REDIRECT_URI=http://localhost:3001/api/v1/auth/google/callback ``` ### Facebook OAuth @@ -92,7 +141,7 @@ curl -X GET "http://localhost:4000/api/v1/rbac/permissions/check?resource=users& ``` FACEBOOK_APP_ID=your-app-id FACEBOOK_APP_SECRET=your-app-secret - FACEBOOK_REDIRECT_URI=http://localhost:4000/api/v1/auth/facebook/callback + FACEBOOK_REDIRECT_URI=http://localhost:3001/api/v1/auth/facebook/callback ``` ### GitHub OAuth @@ -102,7 +151,7 @@ curl -X GET "http://localhost:4000/api/v1/rbac/permissions/check?resource=users& ``` GITHUB_CLIENT_ID=your-client-id GITHUB_CLIENT_SECRET=your-client-secret - GITHUB_REDIRECT_URI=http://localhost:4000/api/v1/auth/github/callback + GITHUB_REDIRECT_URI=http://localhost:3001/api/v1/auth/github/callback ``` ## 🔒 MFA Setup