# Đề Xuất Kiến Trúc IAM Service

Tài liệu này mô tả đề xuất kiến trúc cho IAM Service (Identity and Access Management Service), mở rộng từ auth-service hiện tại.

## Tổng Quan: Auth Service → IAM Service

**Auth Service hiện tại** tập trung vào:
- Authentication (xác thực)
- Authorization (phân quyền)  
- Session & Token management
- RBAC/ABAC

**IAM Service** mở rộng thêm:
- **Identity Management** (quản lý danh tính toàn diện)
- **Access Governance** (quản trị truy cập)
- **Compliance & Reporting** (tuân thủ và báo cáo)
- **Lifecycle Management** (quản lý vòng đời tài khoản)

---

## 1. Phạm Vi IAM Service

### 1.1 Identity Management (Quản Lý Danh Tính)

#### A. User Lifecycle Management
- User CRUD operations
- User provisioning/deprovisioning workflows
- Bulk user operations (import/export)
- User deactivation/reactivation với approval workflow
- Account merging/deduplication
- User archival (soft delete với retention policy)

#### B. Profile Management
- Extended attributes (custom fields)
- Profile picture upload & management
- Contact information (phone, address)
- Preferences & settings
- Profile versioning/audit trail

#### C. Identity Verification
- Email verification
- Phone/SMS verification
- Identity document verification (KYC)
- Multi-level verification (verified, pending, rejected)

#### D. Organizations & Groups
- Organization management (multi-tenant)
- Group/Team management
- Organization hierarchy
- Group-based access control
- Organization-level policies

### 1.2 Access Management (Quản Lý Truy Cập)

#### A. Advanced Access Control
- Just-In-Time (JIT) access provisioning
- Privileged Access Management (PAM)
- Temporary access grants
- Access request/approval workflows
- Delegation & impersonation (admin view)
- Conditional access policies (location, time, device)

#### B. Access Reviews & Certifications
- Periodic access reviews
- Access certification campaigns
- Access analytics & reporting
- Risk scoring for access decisions
- Anomaly detection (unusual access patterns)

### 1.3 Governance & Compliance (Quản Trị & Tuân Thủ)

#### A. Audit & Logging
- Compliance reporting (GDPR, SOC2, ISO 27001)
- Data retention policies
- Audit log search & analytics
- Export audit logs

#### B. Policy Governance
- Policy versioning & rollback
- Policy templates library
- Policy testing & validation
- Policy compliance checks

#### C. Risk Management
- Risk scoring engine
- Risk-based authentication
- Threat detection
- Incident response workflows
- Security posture dashboard

---

## 2. Kiến Trúc Module Structure

```
services/iam-service/
├── src/
│   ├── config/              # Configuration files
│   ├── core/
│   │   ├── cache/           # Multi-layer cache
│   │   ├── security/        # Zero-trust, encryption
│   │   ├── events/          # Event sourcing
│   │   └── workflows/       # Workflow engine (NEW)
│   ├── 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
│   │   │   ├── user/        # User lifecycle
│   │   │   ├── profile/     # Profile management
│   │   │   ├── verification/ # Identity verification
│   │   │   └── organization/ # Organizations & groups
│   │   │
│   │   ├── access/          # 🆕 Access Management
│   │   │   ├── request/     # Access requests
│   │   │   ├── review/      # Access reviews
│   │   │   ├── pam/         # Privileged access
│   │   │   └── analytics/   # Access analytics
│   │   │
│   │   ├── governance/      # 🆕 Governance & Compliance
│   │   │   ├── compliance/  # Compliance reporting
│   │   │   ├── policy/      # Policy governance
│   │   │   ├── risk/        # Risk management
│   │   │   └── reporting/   # Reporting & dashboards
│   │   │
│   │   └── workflow/        # 🆕 Workflow Engine
│   │       ├── engine/      # Workflow engine
│   │       ├── approval/    # Approval workflows
│   │       └── automation/  # Automated workflows
│   │
│   ├── middlewares/         # Express middlewares
│   ├── repositories/        # Data access layer
│   └── routes/              # Route definitions
└── prisma/
    └── schema.prisma        # Database schema (mở rộng)
```

---

## 3. Database Schema Mở Rộng

### 3.1 Identity Management Models

- **Organization**: Quản lý tổ chức với hierarchy
- **Group**: Quản lý nhóm trong organization
- **GroupMember**: Thành viên của group
- **GroupPermission**: Permissions cho group
- **UserProfile**: Thông tin profile mở rộng của user
- **IdentityVerification**: Xác thực danh tính (email, phone, document)

### 3.2 Access Management Models

- **AccessRequest**: Yêu cầu truy cập
- **AccessRequestApprover**: Người phê duyệt request
- **AccessReview**: Đánh giá truy cập định kỳ
- **AccessReviewItem**: Item trong review

### 3.3 Governance Models

- **ComplianceReport**: Báo cáo tuân thủ (GDPR, SOC2, ISO27001)
- **PolicyTemplate**: Template cho policies
- **RiskScore**: Điểm rủi ro của user

---

## 4. API Endpoints Mở Rộng

### 4.1 Identity Management APIs

```
# User Management
GET    /api/v1/identity/users
POST   /api/v1/identity/users
GET    /api/v1/identity/users/:id
PUT    /api/v1/identity/users/:id
DELETE /api/v1/identity/users/:id
POST   /api/v1/identity/users/bulk-import
GET    /api/v1/identity/users/bulk-export

# Profile Management
GET    /api/v1/identity/users/:id/profile
PUT    /api/v1/identity/users/:id/profile
POST   /api/v1/identity/users/:id/profile/avatar

# Identity Verification
POST   /api/v1/identity/verification/email/request
POST   /api/v1/identity/verification/email/verify
POST   /api/v1/identity/verification/phone/request
POST   /api/v1/identity/verification/phone/verify

# Organizations & Groups
GET    /api/v1/identity/organizations
POST   /api/v1/identity/organizations
GET    /api/v1/identity/organizations/:id/groups
POST   /api/v1/identity/organizations/:id/groups
GET    /api/v1/identity/groups/:id/members
POST   /api/v1/identity/groups/:id/members
```

### 4.2 Access Management APIs

```
# Access Requests
GET    /api/v1/access/requests
POST   /api/v1/access/requests
PUT    /api/v1/access/requests/:id/approve
PUT    /api/v1/access/requests/:id/reject

# Access Reviews
GET    /api/v1/access/reviews
POST   /api/v1/access/reviews
POST   /api/v1/access/reviews/:id/start
POST   /api/v1/access/reviews/:id/complete
GET    /api/v1/access/reviews/:id/items

# Access Analytics
GET    /api/v1/access/analytics/usage
GET    /api/v1/access/analytics/permissions
GET    /api/v1/access/analytics/risks
```

### 4.3 Governance APIs

```
# Compliance Reports
GET    /api/v1/governance/compliance/reports
POST   /api/v1/governance/compliance/reports/generate
GET    /api/v1/governance/compliance/reports/:id/export

# Policy Governance
GET    /api/v1/governance/policies/templates
POST   /api/v1/governance/policies/templates
GET    /api/v1/governance/policies/:id/versions
POST   /api/v1/governance/policies/:id/test

# Risk Management
GET    /api/v1/governance/risk/scores
GET    /api/v1/governance/risk/scores/:userId
POST   /api/v1/governance/risk/calculate

# Reporting
GET    /api/v1/governance/reports/access-summary
GET    /api/v1/governance/reports/user-activity
GET    /api/v1/governance/reports/security-events
```

---

## 5. Implementation Roadmap

### Phase 1: Foundation (Weeks 1-4)
- ✅ Migrate từ auth-service sang iam-service
- 🔄 Tổ chức lại modules theo IAM structure
- 🔄 Mở rộng database schema với identity models
- 🔄 Implement User Profile module

### Phase 2: Identity Management (Weeks 5-8)
- 🔄 User lifecycle management
- 🔄 Identity verification (email, phone, document)
- 🔄 Organization & Group management
- 🔄 Profile management with extended attributes

### Phase 3: Access Management (Weeks 9-12)
- 🔄 Access request/approval workflows
- 🔄 Access review & certification system
- 🔄 Access analytics
- 🔄 Privileged Access Management (PAM)

### Phase 4: Governance (Weeks 13-16)
- 🔄 Compliance reporting engine
- 🔄 Policy governance & versioning
- 🔄 Risk scoring & management
- 🔄 Reporting dashboards

### Phase 5: Advanced Features (Weeks 17-20)
- 🔄 Workflow engine
- 🔄 Advanced analytics & ML-based insights
- 🔄 Integration APIs (SCIM, LDAP sync)
- 🔄 Performance optimization & scaling

---

## 6. Lợi Ích Của IAM Service

### 6.1 Cho Doanh Nghiệp
- ✅ Tuân thủ (GDPR, SOC2, ISO 27001)
- ✅ Quản lý rủi ro bảo mật tốt hơn
- ✅ Tự động hóa quy trình quản lý truy cập
- ✅ Báo cáo và audit trail đầy đủ
- ✅ Hỗ trợ multi-tenant/organization

### 6.2 Cho Developers
- ✅ API thống nhất cho identity & access
- ✅ Workflow engine linh hoạt
- ✅ Extensible architecture
- ✅ Comprehensive documentation
- ✅ SDK support

### 6.3 Cho End Users
- ✅ Self-service profile management
- ✅ Transparent access requests
- ✅ Better user experience
- ✅ Enhanced security với MFA & verification

---

## 7. Migration Strategy

### Từ Auth Service → IAM Service

1. **Rename Service**: `services/auth-service` → `services/iam-service`
2. **Update Package Name**: `@goodgo/auth-service` → `@goodgo/iam-service`
3. **Update Routes**: 
   - Giữ backward compatibility với `/api/v1/auth/*`
   - Thêm routes mới cho `/api/v1/identity/*`, `/api/v1/access/*`, `/api/v1/governance/*`
4. **Database Migration**: 
   - Thêm schema mới cho identity, access, governance
   - Giữ nguyên các tables hiện có (backward compatible)
5. **Gradual Rollout**:
   - Phase 1: Deploy cùng auth-service (dual deployment)
   - Phase 2: Migrate clients dần dần
   - Phase 3: Deprecate auth-service khi migration hoàn tất

---

## Kết Luận

Đề xuất này mở rộng `auth-service` thành `IAM Service` với đầy đủ các tính năng:
- **Identity Management** đầy đủ
- **Access Management** nâng cao
- **Governance & Compliance** toàn diện
- **Workflow automation** linh hoạt

Điều này biến service từ authentication/authorization cơ bản thành một IAM platform toàn diện, phù hợp cho enterprise.
