# 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)

## 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 → 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 (bcrypt, cost 12)
- ✅ Login với JWT tokens (15min access, 7day refresh)
- ✅ Logout với session revocation
- ✅ 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)
- ✅ Group-based permissions
- ✅ Permission caching (5min TTL)
- ✅ RBAC middleware

### 4. ABAC (Attribute-Based Access Control)
- ✅ Policy engine với JSON logic
- ✅ Policy evaluation với priority
- ✅ Time-based access control
- ✅ Location-based access control
- ✅ Attribute-based conditions

### 5. Social Authentication
- ✅ Google OAuth 2.0
- ✅ Facebook OAuth
- ✅ GitHub OAuth
- ✅ Circuit breaker cho external APIs
- ✅ Account linking
- ✅ State token CSRF protection

### 6. OIDC (OpenID Connect)
- ✅ OIDC Provider implementation
- ✅ Discovery endpoint (`/.well-known/openid-configuration`)
- ✅ Authorization code flow
- ✅ Token endpoint
- ✅ UserInfo endpoint
- ✅ JWKS endpoint
- ✅ OIDC Client support

### 7. MFA (Multi-Factor Authentication)
- ✅ TOTP (Time-based One-Time Password)
- ✅ 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 (single/all)
- ✅ Multiple device support
- ✅ IP address tracking

### 9. Security Features
- ✅ Zero-trust validation
- ✅ CSRF protection
- ✅ Dynamic rate limiting (based on roles: 50-1000 req/15min)
- ✅ Device fingerprinting
- ✅ Audit logging (event sourcing)
- ✅ Input validation (Zod schemas)

### 10. API Endpoints

#### 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 (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
- `GET /api/v1/auth/facebook/callback` - Facebook callback
- `GET /api/v1/auth/github` - Initiate GitHub OAuth
- `GET /api/v1/auth/github/callback` - GitHub callback

#### 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 (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 (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

#### 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

---

## 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

#### Database
- `DATABASE_URL`: PostgreSQL connection string
- `DATABASE_POOL_SIZE`: Connection pool size (default: 10)
- `DATABASE_TIMEOUT`: Query timeout in ms (default: 30000)

#### 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)

#### 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
- Uses Prisma for type-safe database access
- 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
