---
name: IAM Service Audit Plan
overview: "Kế hoạch kiểm tra toàn diện cho IAM Service bao gồm: logic nghiệp vụ, quy trình build, bảo mật, và triển khai môi trường dev/staging/production. Plan được chia thành 6 phases: Pre-deployment Audit, Security Fixes, Local Environment, Staging Deployment, Production Deployment, và Post-deployment."
todos:
  - id: audit-auth-1
    content: "Review Authentication Module - Registration Flow: Check email validation, password hashing with bcrypt cost 12, user profile creation in services/iam-service/src/modules/auth/auth.service.ts"
    status: completed
  - id: audit-auth-2
    content: "Review Authentication Module - Login Flow: Check password verification, JWT generation (access + refresh), session creation, MFA integration in services/iam-service/src/modules/auth/auth.service.ts"
    status: completed
  - id: audit-auth-3
    content: "Review Authentication Module - Token Refresh: Check token family tracking, refresh token rotation, replay attack detection in services/iam-service/src/modules/token/jwt.service.ts"
    status: completed
  - id: audit-auth-4
    content: "Review Authentication Module - Password Change: Check refresh token revocation, audit logging in services/iam-service/src/modules/auth/change-password.service.ts"
    status: completed
  - id: audit-rbac-1
    content: "Review RBAC Module - Permission Resolution: Check hierarchy (Direct user → Role → Group → Policy) in services/iam-service/src/modules/rbac/rbac.service.ts"
    status: completed
  - id: audit-rbac-2
    content: "Review RBAC Module - Role Assignment: Check expiration handling in services/iam-service/src/modules/rbac/rbac.service.ts"
    status: completed
  - id: audit-rbac-3
    content: "Review RBAC Module - Policy Engine: Check JSON Logic implementation in services/iam-service/src/modules/rbac/policy.engine.ts"
    status: completed
  - id: audit-rbac-4
    content: "Review RBAC Module - Permission Caching: Verify 5 min TTL and cache invalidation in services/iam-service/src/core/cache/cache.service.ts"
    status: completed
  - id: audit-identity-1
    content: "Review Identity Module - User Management: Check CRUD operations, bulk import/export in services/iam-service/src/modules/identity/user/user.service.ts"
    status: completed
  - id: audit-identity-2
    content: "Review Identity Module - Profile Management: Check custom fields, avatar upload/delete in services/iam-service/src/modules/identity/profile/profile.service.ts"
    status: completed
  - id: audit-identity-3
    content: "Review Identity Module - Verification: Check email/phone/document verification flows in services/iam-service/src/modules/identity/verification/verification.service.ts"
    status: completed
  - id: audit-identity-4
    content: "Review Identity Module - Organizations: Check multi-tenant support, hierarchical structure in services/iam-service/src/modules/identity/organization/organization.service.ts"
    status: completed
  - id: audit-identity-5
    content: "Review Identity Module - Groups: Check member management, group-based permissions in services/iam-service/src/modules/identity/group/group.service.ts"
    status: completed
  - id: audit-access-1
    content: "Review Access Module - Access Requests: Check workflow, approval chains, JIT access in services/iam-service/src/modules/access/request/request.service.ts"
    status: completed
  - id: audit-access-2
    content: "Review Access Module - Access Reviews: Check certification campaigns, automated cleanup in services/iam-service/src/modules/access/review/review.service.ts"
    status: completed
  - id: audit-access-3
    content: "Review Access Module - Access Analytics: Check usage tracking, risk identification in services/iam-service/src/modules/access/analytics/analytics.service.ts"
    status: completed
  - id: audit-mfa-1
    content: "Review MFA Module - TOTP: Check TOTP implementation using speakeasy library in services/iam-service/src/modules/mfa/mfa.service.ts"
    status: completed
  - id: audit-mfa-2
    content: "Review MFA Module - QR Code: Check QR code generation in services/iam-service/src/modules/mfa/mfa.service.ts"
    status: completed
  - id: audit-mfa-3
    content: "Review MFA Module - WebAuthn: Check WebAuthn support in services/iam-service/src/modules/mfa/mfa.service.ts"
    status: completed
  - id: audit-mfa-4
    content: "Review MFA Module - Multiple Devices: Check multiple devices per user support in services/iam-service/src/modules/mfa/mfa.service.ts"
    status: completed
  - id: audit-mfa-5
    content: "Review MFA Module - Recovery Flow: Verify MFA recovery flow exists (NOTE: Currently missing, needs review)"
    status: completed
  - id: audit-social-1
    content: "Review Social Authentication Module: Check Google/Facebook/GitHub OAuth flows, account linking, token refresh in services/iam-service/src/modules/social/social.service.ts"
    status: completed
  - id: audit-oidc-1
    content: "Review OIDC Provider Module: Check discovery endpoint, authorization code flow, token exchange, JWKS endpoint in services/iam-service/src/modules/oidc/oidc-provider.service.ts"
    status: completed
  - id: audit-session-1
    content: "Review Session Management Module: Check device fingerprinting, session expiration, revocation, activity tracking in services/iam-service/src/modules/session/session.service.ts"
    status: completed
  - id: audit-governance-1
    content: "Review Governance Module: Check compliance reporting (GDPR, SOC2, ISO27001), policy management, risk scoring in services/iam-service/src/modules/governance/"
    status: completed
  - id: audit-cache-1
    content: "Review Cache Service: Check multi-layer caching (L1: Memory, L2: Redis, L3: DB), cache warming, invalidation in services/iam-service/src/core/cache/cache.service.ts"
    status: completed
  - id: audit-events-1
    content: "Review Event Sourcing: Check audit logging for all security events, 7-year retention in services/iam-service/src/core/events/"
    status: completed
  - id: audit-build-1
    content: "Run TypeScript typecheck: cd services/iam-service && pnpm typecheck - Verify no TypeScript errors"
    status: completed
  - id: audit-build-2
    content: "Run TypeScript build: cd services/iam-service && pnpm build - Verify build succeeds, check for unused variables/imports"
    status: completed
  - id: audit-build-3
    content: "Verify Type Safety: Check type safety for Prisma models, verify path aliases (@/*) working correctly"
    status: completed
  - id: audit-lint-1
    content: "Run ESLint: cd services/iam-service && pnpm lint - Verify coding standards compliance"
    status: completed
  - id: audit-lint-2
    content: "Check Code Quality: Verify no console.log in production code, proper error handling, no security anti-patterns"
    status: completed
  - id: audit-prisma-1
    content: "Generate Prisma Client: cd services/iam-service && pnpm prisma:generate - Verify generation succeeds"
    status: completed
  - id: audit-prisma-2
    content: "Validate Prisma Schema: Verify schema syntax valid, all relations properly defined, indexes optimized, migration files consistent"
    status: completed
  - id: audit-test-1
    content: "Run Unit Tests: cd services/iam-service && pnpm test:unit - Verify all unit tests pass"
    status: completed
  - id: audit-test-2
    content: "Run E2E Tests: cd services/iam-service && pnpm test:e2e - Verify all E2E tests pass"
    status: completed
  - id: audit-test-3
    content: "Generate Test Coverage: cd services/iam-service && pnpm test:coverage - Verify coverage >= 70% (branches, functions, lines, statements)"
    status: completed
  - id: audit-docker-1
    content: "Build Docker Image: docker build -t iam-service:test -f services/iam-service/Dockerfile . - Verify multi-stage build succeeds"
    status: completed
  - id: audit-docker-2
    content: "Verify Docker Image: Check image size <500MB, non-root user configured, health check functional"
    status: completed
  - id: security-mfa-1
    content: "CRITICAL: Create Encryption Service - Create services/iam-service/src/core/security/encryption.service.ts with encrypt/decrypt functions using crypto module"
    status: completed
  - id: security-mfa-2
    content: "CRITICAL: Update Schema for MFA Encryption - Update prisma/schema.prisma to support encrypted MFA secret fields (add encrypted field or use existing secret field with encryption layer)"
    status: completed
  - id: security-mfa-3
    content: "CRITICAL: Update MFA Service - Update services/iam-service/src/modules/mfa/mfa.service.ts to encrypt MFA secrets before saving and decrypt when reading"
    status: completed
  - id: security-refresh-1
    content: "CRITICAL: Hash Refresh Tokens - Update services/iam-service/src/modules/token/jwt.service.ts to hash refresh tokens (SHA-256) before storing in database"
    status: completed
  - id: security-refresh-2
    content: "CRITICAL: Update Refresh Token Validation - Update refresh token validation logic in jwt.service.ts to compare hashes instead of plaintext tokens"
    status: completed
  - id: security-jwt-1
    content: "CRITICAL: Block Default JWT Secrets - Update services/iam-service/src/config/jwt.config.ts to throw error if default secrets are used when NODE_ENV === 'production'"
    status: completed
  - id: security-input-1
    content: "MEDIUM: Install DOMPurify: cd services/iam-service && pnpm add dompurify @types/dompurify"
    status: completed
  - id: security-input-2
    content: "MEDIUM: Update Input Sanitization - Update services/iam-service/src/utils/helpers.ts sanitizeInput function to use DOMPurify instead of simple < > removal"
    status: completed
  - id: security-password-1
    content: "MEDIUM: Add Password Complexity Schema - Update services/iam-service/src/modules/auth/auth.dto.ts RegisterDto to enforce: uppercase, lowercase, numbers, symbols (minimum 8 characters)"
    status: completed
  - id: security-password-2
    content: "MEDIUM: Update Change Password Schema - Update services/iam-service/src/modules/auth/auth.dto.ts ChangePasswordDto to enforce same password complexity rules"
    status: completed
  - id: security-fingerprint-1
    content: "MEDIUM: Install FingerprintJS: cd services/iam-service && pnpm add @fingerprintjs/fingerprintjs"
    status: completed
  - id: security-fingerprint-2
    content: "MEDIUM: Update Device Fingerprinting - Update services/iam-service/src/modules/token/cookie.service.ts to use @fingerprintjs/fingerprintjs library instead of basic User-Agent + IP hash"
    status: skipped
  - id: security-lockout-1
    content: "MEDIUM: Add Lockout Fields to Schema - Update prisma/schema.prisma User model to add failedLoginAttempts (Int, default 0) and lockedUntil (DateTime?) fields"
    status: completed
  - id: security-lockout-2
    content: "MEDIUM: Create Account Lockout Service - Create services/iam-service/src/modules/auth/account-lockout.service.ts with lockout logic and exponential backoff"
    status: completed
  - id: security-lockout-3
    content: "MEDIUM: Update Auth Service for Lockout - Update services/iam-service/src/modules/auth/auth.service.ts to track failed attempts and check lockout status before login"
    status: completed
  - id: security-lockout-4
    content: "MEDIUM: Create Lockout Migration - Create Prisma migration for failedLoginAttempts and lockedUntil fields"
    status: completed
  - id: security-audit-1
    content: "LOW: Run npm audit: cd services/iam-service && npm audit - Review vulnerabilities"
    status: completed
  - id: security-audit-2
    content: "LOW: Fix npm vulnerabilities: cd services/iam-service && npm audit fix - Apply fixes for vulnerabilities"
    status: completed
  - id: security-cors-1
    content: "LOW: Review CORS Configuration - Check services/iam-service/src/main.ts CORS settings, verify necessity of credentials enabled"
    status: pending
  - id: security-social-1
    content: "LOW: Review Social Token Storage - Check services/iam-service/prisma/schema.prisma SocialAccount model, consider encryption for accessToken and refreshToken fields"
    status: pending
  - id: security-backup-1
    content: "LOW: Design MFA Backup Codes - Design backup codes generation and storage strategy for MFA recovery scenarios"
    status: pending
  - id: local-env-1
    content: "Copy Environment File: cp deployments/local/env.local.example deployments/local/.env.local"
    status: completed
  - id: local-env-2
    content: "Update DATABASE_URL: Set DATABASE_URL in deployments/local/.env.local to Neon PostgreSQL connection string"
    status: completed
  - id: local-env-3
    content: "Update REDIS_URL: Set REDIS_URL in deployments/local/.env.local to redis://localhost:6379"
    status: completed
  - id: local-env-4
    content: "Generate JWT Secrets: Generate new JWT_SECRET, JWT_REFRESH_SECRET, JWT_ID_SECRET (NOT defaults) and update deployments/local/.env.local"
    status: completed
  - id: local-env-5
    content: "Update Social Auth Credentials: Set Google/Facebook/GitHub OAuth credentials in deployments/local/.env.local"
    status: skipped
  - id: local-docker-1
    content: "Start Docker Compose: cd deployments/local && docker-compose up -d"
    status: completed
  - id: local-docker-2
    content: "Verify Docker Services: Check Traefik, IAM Service, Redis, PostgreSQL containers are running successfully"
    status: completed
  - id: local-migrate-1
    content: "Run Prisma Migrate: cd services/iam-service && pnpm prisma:migrate - Verify migrations apply successfully"
    status: completed
  - id: local-migrate-2
    content: "Run Prisma Seed: cd services/iam-service && pnpm prisma:seed - Verify seed data is created"
    status: completed
  - id: local-verify-1
    content: "Test Traefik Dashboard: Open http://localhost:8080 and verify Traefik dashboard loads"
    status: completed
  - id: local-verify-2
    content: "Test IAM Service: Open http://localhost:5001 and verify service is accessible"
    status: completed
  - id: local-verify-3
    content: "Test API Gateway: Test http://localhost/api/v1/auth endpoint"
    status: completed
  - id: local-verify-4
    content: "Test Redis: Verify Redis connection on localhost:6379"
    status: completed
  - id: local-health-1
    content: "Test Liveness Endpoint: curl http://localhost:5001/health/live - Verify returns 200 OK"
    status: completed
  - id: local-health-2
    content: "Test Readiness Endpoint: curl http://localhost:5001/health/ready - Verify returns 200 OK (includes DB check)"
    status: completed
  - id: local-health-3
    content: "Test Metrics Endpoint: curl http://localhost:5001/metrics - Verify Prometheus metrics are returned"
    status: completed
  - id: local-test-1
    content: "Test Registration Flow: Register new user via API, verify email validation, password hashing, profile creation"
    status: completed
  - id: local-test-2
    content: "Test Login Flow: Login with registered user, verify JWT tokens, session creation"
    status: completed
  - id: local-test-3
    content: "Test Logout Flow: Logout user, verify session revocation"
    status: skipped
  - id: local-test-4
    content: "Test Authorization: Test RBAC/ABAC permissions with different user roles"
    status: skipped
  - id: local-test-5
    content: "Test MFA: Test TOTP setup, QR code generation, WebAuthn if implemented"
    status: skipped
  - id: local-test-6
    content: "Test Social Login: Test Google/Facebook/GitHub OAuth flows"
    status: skipped
  - id: local-test-7
    content: "Review Logs and Metrics: Check application logs and Prometheus metrics for errors"
    status: completed
  - id: staging-k8s-1
    content: "Create Staging Namespace: kubectl create namespace staging"
    status: skipped
  - id: staging-k8s-2
    content: "Create Staging Secrets: kubectl create secret generic iam-service-secrets --from-literal=database-url='...' --from-literal=jwt-secret='...' --from-literal=jwt-refresh-secret='...' -n staging"
    status: skipped
  - id: staging-k8s-3
    content: "Apply Staging ConfigMap: kubectl apply -f deployments/staging/kubernetes/iam-service-configmap.yaml"
    status: skipped
  - id: staging-k8s-4
    content: "Deploy Staging Service: kubectl apply -f deployments/staging/kubernetes/iam-service.yaml"
    status: skipped
  - id: staging-k8s-5
    content: "Apply Staging Ingress: kubectl apply -f deployments/staging/kubernetes/ingress.yaml"
    status: skipped
  - id: staging-migrate-1
    content: "Run Staging Migrations: DATABASE_URL='postgresql://...' pnpm prisma:deploy - Verify migrations apply successfully"
    status: skipped
  - id: staging-verify-1
    content: "Check Staging Pods: kubectl get pods -n staging - Verify pods are running"
    status: skipped
  - id: staging-verify-2
    content: "Check Staging Logs: kubectl logs -f deployment/iam-service -n staging - Review logs for errors"
    status: skipped
  - id: staging-verify-3
    content: "Describe Staging Pod: kubectl describe pod <pod-name> -n staging - Verify pod status and events"
    status: skipped
  - id: staging-test-1
    content: "Run Staging Smoke Tests: Execute basic API endpoint tests (health, auth endpoints)"
    status: skipped
  - id: staging-test-2
    content: "Run Performance Tests: Execute performance tests on staging environment"
    status: skipped
  - id: staging-test-3
    content: "Run Load Tests: Execute load tests on staging environment"
    status: skipped
  - id: staging-test-4
    content: "Monitor Staging Logs: Monitor logs for errors during testing period"
    status: skipped
  - id: staging-test-5
    content: "Verify Staging Health Endpoints: Test /health/live and /health/ready endpoints on staging"
    status: skipped
  - id: prod-check-1
    content: "Pre-production: Verify security audit passed - Review all security fixes are implemented"
    status: skipped
  - id: prod-check-2
    content: "Pre-production: Verify staging tests passed - Confirm all staging tests are successful"
    status: skipped
  - id: prod-check-3
    content: "Pre-production: Backup Database - Create database backup before production deployment"
    status: skipped
  - id: prod-check-4
    content: "Pre-production: Generate Production Secrets - Generate STRONG NON-DEFAULT JWT secrets for production"
    status: skipped
  - id: prod-check-5
    content: "Pre-production: Verify Critical Security Fixes - Confirm all CRITICAL security fixes are implemented and tested"
    status: skipped
  - id: prod-k8s-1
    content: "Create Production Namespace: kubectl create namespace production"
    status: skipped
  - id: prod-k8s-2
    content: "Create Production Secrets: kubectl create secret generic iam-service-secrets --from-literal=database-url='...' --from-literal=jwt-secret='STRONG_SECRET' --from-literal=jwt-refresh-secret='STRONG_SECRET' --from-literal=jwt-id-secret='STRONG_SECRET' -n production"
    status: skipped
  - id: prod-k8s-3
    content: "Apply Production ConfigMap: kubectl apply -f deployments/production/kubernetes/iam-service-configmap.yaml"
    status: skipped
  - id: prod-k8s-4
    content: "Deploy Production Service: kubectl apply -f deployments/production/kubernetes/iam-service.yaml"
    status: skipped
  - id: prod-k8s-5
    content: "Deploy Production HPA: kubectl apply -f deployments/production/kubernetes/hpa.yaml"
    status: skipped
  - id: prod-k8s-6
    content: "Apply Production Ingress: kubectl apply -f deployments/production/kubernetes/ingress.yaml"
    status: skipped
  - id: prod-migrate-1
    content: "Run Production Migrations: DATABASE_URL='postgresql://...' pnpm prisma:deploy (safe deployment mode) - Verify migrations apply successfully"
    status: skipped
  - id: prod-monitor-1
    content: "Monitor Production Rollout: kubectl rollout status deployment/iam-service -n production - Verify deployment succeeds"
    status: skipped
  - id: prod-monitor-2
    content: "Check Production HPA: kubectl get hpa -n production - Verify HPA is configured correctly"
    status: skipped
  - id: prod-security-1
    content: "Production Security: Verify secrets NOT using defaults - Check all JWT secrets are strong and non-default"
    status: skipped
  - id: prod-security-2
    content: "Production Security: Verify TLS/SSL certificates configured - Check certificates are valid and configured"
    status: skipped
  - id: prod-security-3
    content: "Production Security: Verify network policies applied - Check Kubernetes network policies are in place"
    status: skipped
  - id: prod-security-4
    content: "Production Security: Verify pod security policies enabled - Check pod security policies are configured"
    status: skipped
  - id: prod-security-5
    content: "Production Security: Verify resource quotas set - Check resource quotas are configured for namespace"
    status: skipped
  - id: prod-security-6
    content: "Production Security: Verify RBAC configured - Check Kubernetes RBAC is properly configured"
    status: skipped
  - id: prod-security-7
    content: "Production Security: Verify monitoring alerts configured - Check Prometheus alerts are set up"
    status: skipped
  - id: prod-security-8
    content: "Production Security: Verify backup strategy in place - Confirm database backup strategy is implemented"
    status: skipped
  - id: post-monitor-1
    content: "Monitor Error Rates: Check error rates in monitoring dashboard, verify errors are within acceptable range"
    status: skipped
  - id: post-monitor-2
    content: "Monitor Response Times: Check API response times, verify performance metrics are acceptable"
    status: skipped
  - id: post-monitor-3
    content: "Check Security Events: Review audit logs for security events, verify no suspicious activities"
    status: skipped
  - id: post-monitor-4
    content: "Review Audit Logs: Review comprehensive audit logs for any anomalies"
    status: skipped
  - id: post-monitor-5
    content: "Verify Autoscaling: Monitor HPA scaling based on CPU/memory metrics, verify autoscaling works correctly"
    status: skipped
  - id: post-test-1
    content: "Test Failover Scenarios: Test pod failures, verify service remains available"
    status: skipped
  - id: post-test-2
    content: "Run Comprehensive Smoke Tests: Execute full smoke test suite on production"
    status: skipped
  - id: post-test-3
    content: "Verify Health Endpoints: Test /health/live and /health/ready endpoints on production"
    status: skipped
  - id: post-test-4
    content: "Test Authentication Flows: Test register, login, logout flows on production"
    status: skipped
  - id: post-test-5
    content: "Test Authorization Flows: Test RBAC/ABAC authorization on production"
    status: skipped
  - id: post-doc-1
    content: "Document Known Issues: Create document listing any known issues or limitations"
    status: skipped
  - id: post-doc-2
    content: "Create Operations Runbook: Create runbook with operational procedures, troubleshooting guides"
    status: skipped
  - id: post-doc-3
    content: "Update Deployment Procedures: Update deployment documentation with lessons learned"
    status: skipped
  - id: post-doc-4
    content: "Document Rollback Procedures: Document step-by-step rollback procedures for production"
    status: skipped
---

# IAM Service Audit Plan

## Tổng Quan (Overview)

Kế hoạch kiểm tra toàn diện cho IAM Service với 6 phases chính:

1. **Pre-deployment Audit**: Review logic nghiệp vụ, build, linting, testing
2. **Security Fixes (CRITICAL)**: Fix các lỗ hổng bảo mật nghiêm trọng
3. **Local Environment**: Setup và test môi trường local
4. **Staging Deployment**: Deploy và verify trên staging
5. **Production Deployment**: Deploy production với zero-downtime
6. **Post-deployment**: Monitor và validate sau deploy

---

## Phase 1: Pre-deployment Audit

### 1.1 Business Logic Review (10 Modules)

**Authentication Module** (`services/iam-service/src/modules/auth/`)

- Review registration flow: email validation, password hashing (bcrypt cost 12), user profile creation
- Review login flow: password verification, JWT generation (access + refresh), session creation, MFA integration
- Review token refresh: token family tracking, refresh token rotation, replay attack detection
- Review password change: refresh token revocation, audit logging

**Authorization/RBAC Module** (`services/iam-service/src/modules/rbac/`)

- Review permission resolution hierarchy: Direct user → Role → Group → Policy (ABAC)
- Review role assignment with expiration
- Review policy engine (JSON Logic)
- Validate permission caching (5 min TTL) và cache invalidation

**Identity Management** (`services/iam-service/src/modules/identity/`)

- User Management: CRUD operations, bulk import/export
- Profile Management: Custom fields, avatar upload/delete
- Verification: Email/phone/document verification flows
- Organizations: Multi-tenant support, hierarchical structure
- Groups: Member management, group-based permissions

**Access Management** (`services/iam-service/src/modules/access/`)

- Access Requests: Workflow, approval chains, JIT access
- Access Reviews: Certification campaigns, automated cleanup
- Access Analytics: Usage tracking, risk identification

**Multi-Factor Authentication** (`services/iam-service/src/modules/mfa/`)

- TOTP implementation (speakeasy library)
- QR code generation
- WebAuthn support
- Multiple devices per user
- MFA recovery flow (REVIEW REQUIRED - currently missing)

**Social Authentication** (`services/iam-service/src/modules/social/`)

- Google/Facebook/GitHub OAuth flows
- Account linking logic
- Token refresh for social providers
- Email verification bypass for verified social accounts

**OIDC Provider** (`services/iam-service/src/modules/oidc/`)

- Discovery endpoint
- Authorization code flow
- Token exchange
- JWKS endpoint

**Session Management** (`services/iam-service/src/modules/session/`)

- Device fingerprinting
- Session expiration
- Session revocation (single/all)
- Activity tracking

**Governance & Compliance** (`services/iam-service/src/modules/governance/`)

- Compliance reporting (GDPR, SOC2, ISO27001)
- Policy management và versioning
- Risk scoring (0-100)
- Audit reporting

**Cache và Event Sourcing** (`services/iam-service/src/core/cache/`, `services/iam-service/src/core/events/`)

- Multi-layer caching (L1: Memory, L2: Redis, L3: DB)
- Cache warming và invalidation
- Audit logging tất cả security events
- Event sourcing với 7-year retention

### 1.2 Build & Error Checking

**TypeScript Compilation**

```bash
cd services/iam-service
pnpm typecheck  # Type checking
pnpm build      # Full build
```

- Verify: No TypeScript errors, no unused variables/imports, type safety for Prisma models, path aliases (@/*) working

**Linting & Code Quality**

```bash
pnpm lint
```

- Verify: Coding standards compliance, no console.log in production code, proper error handling, no security anti-patterns

**Database Schema**

```bash
pnpm prisma:generate   # Generate Prisma client
pnpm prisma:validate   # Validate schema (if available)
```

- Verify: Schema syntax valid, all relations properly defined, indexes optimized, migration files consistent

**Testing**

```bash
pnpm test:unit         # Unit tests
pnpm test:e2e          # E2E tests
pnpm test:coverage     # Coverage report
```

- Target: Coverage >= 70% (branches, functions, lines, statements), all critical paths tested

**Docker Build**

```bash
docker build -t iam-service:test -f services/iam-service/Dockerfile .
```

- Verify: Multi-stage build successful, image size <500MB, non-root user configured, health check functional

---

## Phase 2: Security Fixes (CRITICAL - Must Complete Before Production)

### 2.1 CRITICAL Vulnerabilities (HIGH PRIORITY)

**🔴 CRITICAL: MFA Secrets in Plaintext**

- **Location**: `services/iam-service/prisma/schema.prisma` (lines 23, 234)
- **Issue**: `MFADevice.secret` và `User.mfaSecret` stored unencrypted
- **Fix**: Implement field-level encryption using crypto module (encrypt before save, decrypt on read)
- **Files to modify**:
  - `prisma/schema.prisma` - Add encrypted field support
  - Create `services/iam-service/src/core/security/encryption.service.ts` for encryption/decryption
  - Update `services/iam-service/src/modules/mfa/mfa.service.ts` to use encryption

**🔴 CRITICAL: Refresh Tokens in Plaintext**

- **Location**: `services/iam-service/prisma/schema.prisma` (line 177)
- **Issue**: `RefreshToken.token` stored as plaintext
- **Fix**: Store hashed tokens (SHA-256), compare hash during validation
- **Files to modify**:
  - Update `services/iam-service/src/modules/token/jwt.service.ts` to hash refresh tokens before storing
  - Update refresh token validation logic

**🔴 CRITICAL: Default JWT Secrets**

- **Location**: `services/iam-service/src/config/jwt.config.ts` (lines 7, 11, 15)
- **Issue**: Default secrets not blocked in production
- **Fix**: Add production check that throws error if defaults are used
- **Files to modify**:
  - `services/iam-service/src/config/jwt.config.ts` - Add production validation

### 2.2 Medium Severity Issues

**🟡 Weak Input Sanitization**

- **Location**: `services/iam-service/src/utils/helpers.ts` (line 39)
- **Current**: Only removes `<` and `>`
- **Fix**: Use DOMPurify or proper HTML entity encoding

**🟡 No Password Complexity Rules**

- **Location**: `services/iam-service/src/modules/auth/auth.dto.ts` (line 9)
- **Current**: Only minimum 8 characters
- **Fix**: Enforce uppercase, lowercase, numbers, symbols

**🟡 Simple Device Fingerprinting**

- **Location**: `services/iam-service/src/modules/token/cookie.service.ts` (lines 117-126)
- **Current**: Basic User-Agent + IP hash
- **Fix**: Use @fingerprintjs/fingerprintjs library

**🟡 Missing Account Lockout**

- **Issue**: No protection after N failed login attempts
- **Fix**: Implement exponential backoff + account lockout
- **Files to create/modify**:
  - Create `services/iam-service/src/modules/auth/account-lockout.service.ts`
  - Update `services/iam-service/src/modules/auth/auth.service.ts` to track failed attempts
  - Add `failedLoginAttempts` và `lockedUntil` fields to User model

### 2.3 Low Severity Issues

- No password history tracking
- CORS credentials enabled (review necessity)
- Social tokens in plaintext (consider encryption)
- No MFA backup codes
- Missing password breach checking (HaveIBeenPwned integration)

### 2.4 OWASP Top 10 Review

- A01: Broken Access Control - ✅ Well implemented via RBAC/ABAC
- A02: Cryptographic Failures - ❌ See vulnerabilities above
- A03: Injection - ✅ Protected by Prisma parameterized queries
- A04: Insecure Design - Review zero-trust implementation
- A05: Security Misconfiguration - Review Helmet.js settings
- A06: Vulnerable Components - Run `npm audit`
- A07: Auth Failures - ❌ Missing account lockout
- A08: Data Integrity Failures - Review JWT signature validation
- A09: Logging Failures - ✅ Comprehensive audit logging
- A10: SSRF - Review external API calls

---

## Phase 3: Local Environment Setup

### 3.1 Docker Compose Setup

**Environment Configuration**

- Copy `deployments/local/env.local.example` to `deployments/local/.env.local`
- Update environment variables:
  - `DATABASE_URL` (Neon PostgreSQL)
  - `REDIS_URL`
  - `JWT_SECRET` (generate new, NOT default)
  - `JWT_REFRESH_SECRET` (generate new)
  - `JWT_ID_SECRET` (generate new)
  - Social auth credentials

**Start Services**

```bash
cd deployments/local
docker-compose up -d
```

**Database Migrations**

```bash
cd services/iam-service
pnpm prisma:migrate
pnpm prisma:seed
```

**Verify Services**

- Traefik Dashboard: http://localhost:8080
- IAM Service: http://localhost:5001
- API Gateway: http://localhost/api/v1/auth
- Redis: localhost:6379

**Health Checks**

```bash
curl http://localhost:5001/health/live      # Liveness
curl http://localhost:5001/health/ready     # Readiness (includes DB)
curl http://localhost:5001/metrics          # Prometheus metrics
```

### 3.2 Functional Testing

- Test authentication flows (register, login, logout)
- Test authorization (RBAC/ABAC)
- Test MFA (TOTP, WebAuthn)
- Test social login (Google, Facebook, GitHub)
- Review logs and metrics

---

## Phase 4: Staging Deployment

### 4.1 Kubernetes Setup

**Prerequisites**

- Kubernetes cluster configured
- kubectl installed và configured
- Docker images pushed to registry

**Create Namespace**

```bash
kubectl create namespace staging
```

**Create Secrets**

```bash
kubectl create secret generic iam-service-secrets \
  --from-literal=database-url="postgresql://..." \
  --from-literal=jwt-secret="..." \
  --from-literal=jwt-refresh-secret="..." \
  -n staging
```

**Apply ConfigMap**

```bash
kubectl apply -f deployments/staging/kubernetes/iam-service-configmap.yaml
```

**Deploy Service**

```bash
kubectl apply -f deployments/staging/kubernetes/iam-service.yaml
```

**Apply Ingress**

```bash
kubectl apply -f deployments/staging/kubernetes/ingress.yaml
```

**Run Migrations**

```bash
DATABASE_URL="postgresql://..." pnpm prisma:deploy
```

**Verify Deployment**

```bash
kubectl get pods -n staging
kubectl logs -f deployment/iam-service -n staging
kubectl describe pod <pod-name> -n staging
```

### 4.2 Configuration

- Replicas: 2
- Resources: Requests (256Mi memory, 250m CPU), Limits (512Mi memory, 500m CPU)
- Probes: Liveness (/health/live, 30s delay), Readiness (/health/ready, 10s delay)

### 4.3 Testing

- Smoke tests
- Performance testing
- Load testing
- Monitor logs for errors

---

## Phase 5: Production Deployment

### 5.1 Pre-deployment Checklist

- Security audit passed
- Staging tests passed
- Backup database
- Configure production secrets (NON-DEFAULT VALUES)

### 5.2 Kubernetes Setup

**Create Namespace**

```bash
kubectl create namespace production
```

**Create Secrets**

```bash
kubectl create secret generic iam-service-secrets \
  --from-literal=database-url="postgresql://..." \
  --from-literal=jwt-secret="STRONG_PRODUCTION_SECRET" \
  --from-literal=jwt-refresh-secret="STRONG_PRODUCTION_REFRESH_SECRET" \
  --from-literal=jwt-id-secret="STRONG_PRODUCTION_ID_SECRET" \
  -n production
```

**Apply Production ConfigMap**

```bash
kubectl apply -f deployments/production/kubernetes/iam-service-configmap.yaml
```

**Deploy with HPA**

```bash
kubectl apply -f deployments/production/kubernetes/iam-service.yaml
kubectl apply -f deployments/production/kubernetes/hpa.yaml
```

**Apply Production Ingress**

```bash
kubectl apply -f deployments/production/kubernetes/ingress.yaml
```

**Run Migrations (Safe Deployment)**

```bash
DATABASE_URL="postgresql://..." pnpm prisma:deploy
```

**Monitor Rollout**

```bash
kubectl rollout status deployment/iam-service -n production
kubectl get hpa -n production
```

### 5.3 Production Configuration

- Replicas: 3 (min) → 10 (max) via HPA
- Resources: Requests (512Mi memory, 500m CPU), Limits (1Gi memory, 1000m CPU)
- Autoscaling: CPU target 70%, Memory target 80%
- Environment: `NODE_ENV=production`, `LOG_LEVEL=warn`, `TRACING_ENABLED=true`

### 5.4 Security Checklist

- ✅ Secrets NOT using defaults
- ✅ TLS/SSL certificates configured
- ✅ Network policies applied
- ✅ Pod security policies enabled
- ✅ Resource quotas set
- ✅ RBAC configured
- ✅ Monitoring alerts configured
- ✅ Backup strategy in place

---

## Phase 6: Post-deployment

### 6.1 Monitoring

- Monitor error rates
- Monitor response times
- Check for security events
- Review audit logs
- Verify autoscaling works

### 6.2 Testing

- Test failover scenarios
- Run comprehensive smoke tests
- Verify health endpoints

### 6.3 Documentation

- Document known issues
- Create runbook for operations
- Update deployment procedures

---

## Critical Files to Review/Modify

### Security Fixes Required

- `services/iam-service/prisma/schema.prisma` - Add encryption for sensitive fields
- `services/iam-service/src/config/jwt.config.ts` - Block defaults in production
- `services/iam-service/src/modules/auth/auth.dto.ts` - Password complexity
- `services/iam-service/src/modules/auth/auth.service.ts` - Account lockout
- `services/iam-service/src/utils/helpers.ts` - Input sanitization
- `services/iam-service/src/modules/token/cookie.service.ts` - Device fingerprinting

### Deployment Configs

- `deployments/local/docker-compose.yml`
- `deployments/staging/kubernetes/iam-service.yaml`
- `deployments/production/kubernetes/iam-service.yaml`
- `deployments/production/kubernetes/hpa.yaml`

---

## Conclusion

### Strengths

- ✅ Clean architecture với separation of concerns
- ✅ Comprehensive business logic (10 modules)
- ✅ Multi-layered security (RBAC + ABAC + Zero-Trust)
- ✅ Excellent audit logging
- ✅ Production-ready deployment configs
- ✅ CI/CD automation
- ✅ Horizontal scaling support

### Critical Issues to Address

- ❌ Encrypt sensitive data at rest (MFA secrets, refresh tokens)
- ❌ Block default JWT secrets in production
- ❌ Implement account lockout
- ❌ Improve password policies
- ❌ Enhanced input sanitization

### Recommendations

- **Immediate**: Fix all HIGH severity security issues before production
- **Short-term**: Implement MEDIUM severity fixes within 2 weeks
- **Long-term**: Enhance with ML-based risk analysis, passwordless auth
- **Continuous**: Regular security audits, penetration testing, dependency updates