Files
pos-system/services/iam-service/docs/ARCHITECTURE.vi.md
Ho Ngoc Hai af303eaf7b Enhance IAM Service documentation with comprehensive updates
- Expanded the IAM Service README to include a detailed overview, features showcase, and quick start guide.
- Updated API reference with new endpoints for health checks and identity management.
- Improved implementation details, including completed features and module dependencies.
- Enhanced architecture documentation with clear diagrams and structured sections for better understanding.
- Added quick reference tables for API endpoints across various modules, improving accessibility for developers.

These changes aim to provide a clearer, more comprehensive understanding of the IAM Service's capabilities and usage.
2026-01-02 00:39:14 +07:00

38 KiB

Kiến Trúc IAM Service

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.

Mục Lục


Tổng Quan

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:

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:

graph TB
    subgraph "Client Layer"
        WebApp[Web Application<br/>React/Vue/Angular]
        MobileApp[Mobile App<br/>iOS/Android/React Native]
        Service[Other Microservices<br/>Product/Order/Payment]
    end

    subgraph "API Gateway"
        Traefik[Traefik Gateway<br/>Load Balancer + Routing<br/>Port 80/443]
    end

    subgraph "IAM Service - Port 3001"
        subgraph "Middleware Stack"
            Correlation[Correlation ID<br/>Request Tracking]
            Logger[Request Logger<br/>Winston]
            ZeroTrust[Zero-Trust Validator<br/>Device + Location + Behavior]
            RateLimit[Dynamic Rate Limiter<br/>Redis-backed<br/>50-1000 req/15min]
            Auth[Authentication<br/>JWT Verification]
            RBAC[Authorization<br/>RBAC + ABAC]
        end

        subgraph "Core Authentication Modules"
            AuthModule[Auth Module<br/>Login/Register/Logout]
            TokenModule[Token Module<br/>JWT + Cookie Management]
            SessionModule[Session Module<br/>Device Fingerprinting]
            SocialModule[Social Auth<br/>Google/FB/GitHub]
            OIDCModule[OIDC Provider<br/>OpenID Connect]
            MFAModule[MFA Module<br/>TOTP/WebAuthn]
            RBACModule[RBAC Module<br/>Roles + Permissions]
        end

        subgraph "Identity Management Modules"
            UserModule[User Lifecycle<br/>CRUD + Bulk Ops]
            ProfileModule[Profile Management<br/>Avatar + Custom Fields]
            VerificationModule[Identity Verification<br/>Email/Phone/Document]
            OrgModule[Organizations<br/>Multi-tenant Hierarchy]
            GroupModule[Groups<br/>Group-based Access]
        end

        subgraph "Access Management Modules"
            RequestModule[Access Requests<br/>Approval Workflows]
            ReviewModule[Access Reviews<br/>Certification Campaigns]
            AnalyticsModule[Access Analytics<br/>Usage + Risk Analysis]
        end

        subgraph "Governance Modules"
            ComplianceModule[Compliance<br/>GDPR/SOC2/ISO27001]
            PolicyModule[Policy Governance<br/>Templates + Versioning]
            RiskModule[Risk Management<br/>Scoring + Detection]
            ReportingModule[Reporting<br/>Dashboards + Exports]
        end

        subgraph "Core Services"
            CacheService[Multi-layer Cache<br/>Memory → Redis<br/>TTL: 60s-15min]
            AuditService[Audit Logging<br/>Event Sourcing<br/>AuthEvent Model]
            SecurityService[Security Services<br/>Encryption + Hashing]
        end
    end

    subgraph "Data Layer"
        PostgreSQL[(PostgreSQL 14+<br/>Primary Database<br/>Connection Pool<br/>30+ Models)]
        Redis[(Redis 6+<br/>Cache + Sessions<br/>Rate Limits + Locks)]
    end

    subgraph "External Services (Future)"
        EmailService[Email Service<br/>Verification + Notifications]
        SMSService[SMS Service<br/>OTP + Phone Verification]
        FileStorage[File Storage<br/>S3/GCS for Avatars]
    end

    subgraph "Observability Stack"
        Prometheus[Prometheus<br/>Metrics Collection]
        Jaeger[Jaeger<br/>Distributed Tracing]
        Logs[Structured Logs<br/>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:

sequenceDiagram
    participant Client
    participant Middleware
    participant AuthService
    participant RBACService
    participant Database
    participant Redis
    participant AuditService

    Client->>Middleware: POST /api/v1/auth/login<br/>{email, password}

    Middleware->>Middleware: 1. Correlation ID
    Middleware->>Middleware: 2. Zero-Trust Validation<br/>(Device + IP + Behavior)
    Middleware->>Middleware: 3. Rate Limit Check<br/>(5 login/15min)

    Middleware->>AuthService: login(email, password)

    AuthService->>Database: Find user by email
    Database-->>AuthService: User record

    AuthService->>AuthService: Verify password<br/>(bcrypt compare, cost=12)

    alt Password Invalid
        AuthService->>AuditService: Log LOGIN_FAILED event
        AuditService->>Database: Save AuthEvent
        AuthService-->>Client: 401 Unauthorized<br/>"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<br/>Access: 15min<br/>Refresh: 7 days

        AuthService->>Database: Save refresh token
        AuthService->>Redis: Cache user data<br/>TTL: 15min
        AuthService->>Redis: Cache permissions<br/>TTL: 5min
        AuthService->>Database: Create session<br/>(device fingerprint)

        AuthService->>Database: Update lastLoginAt, loginCount
        AuthService->>AuditService: Log LOGIN_SUCCESS event

        AuthService-->>Client: 200 OK<br/>{user, tokens}<br/>Set-Cookie: refresh_token
    else Password Valid & MFA Enabled
        AuthService-->>Client: 200 OK<br/>{mfaRequired: true}
        Note over Client: Prompt for MFA code
        Client->>Middleware: POST /api/v1/mfa/verify<br/>{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:

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<br/>(CSRF protection)
    IAM->>Redis: Store state token<br/>TTL: 10min
    IAM-->>Client: 302 Redirect to Google<br/>with state param

    Client->>Google: OAuth consent screen
    Google-->>Client: Authorization code + state

    Client->>IAM: GET /api/v1/auth/social/google/callback<br/>?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<br/>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<br/>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:

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<br/>(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<br/>{token: "123456"}

    IAM->>IAM: Verify TOTP token<br/>(30s window, ±1 interval)

    alt Token Valid
        IAM->>Database: Create MFADevice record<br/>(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<br/>{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<br/>{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

flowchart TD
    Start[Request to Protected Resource] --> Auth{Authenticated?}

    Auth -->|No| Deny401[401 Unauthorized<br/>Authentication required]
    Auth -->|Yes| Cache{Permission<br/>in Cache?}

    Cache -->|Hit| CacheValue{Cache<br/>Value?}
    CacheValue -->|Allow| Allow[Access Granted]
    CacheValue -->|Deny| Deny403Cache[403 Forbidden<br/>Cached denial]

    Cache -->|Miss| LoadPerms[Load Permissions<br/>from Database]

    LoadPerms --> DirectPerms{Has Direct<br/>User Permission?}

    DirectPerms -->|Explicit Deny| Deny403A[403 Forbidden<br/>Explicit permission denial]
    DirectPerms -->|Explicit Allow| Allow
    DirectPerms -->|None| RolePerms{Has Role<br/>Permission?}

    RolePerms -->|Yes| CheckExpiry{Role<br/>Expired?}
    RolePerms -->|No| GroupPerms{Has Group<br/>Permission?}

    CheckExpiry -->|Yes| GroupPerms
    CheckExpiry -->|No| Allow

    GroupPerms -->|Yes| Allow
    GroupPerms -->|No| ABACCheck{ABAC Policy<br/>Exists?}

    ABACCheck -->|No Policies| DefaultDeny[403 Forbidden<br/>Default deny - No permissions]
    ABACCheck -->|Has Policies| EvaluatePolicies[Evaluate Policies<br/>by Priority]

    EvaluatePolicies --> EvalConditions{Policy<br/>Conditions?}

    EvalConditions -->|Time-based| CheckTime{Current time<br/>in range?}
    EvalConditions -->|Location-based| CheckLocation{IP in<br/>allowed range?}
    EvalConditions -->|Attribute-based| CheckAttrs{Attributes<br/>match?}

    CheckTime -->|Yes| PolicyEffect{Policy<br/>Effect?}
    CheckTime -->|No| NextPolicy{More<br/>Policies?}

    CheckLocation -->|Yes| PolicyEffect
    CheckLocation -->|No| NextPolicy

    CheckAttrs -->|Yes| PolicyEffect
    CheckAttrs -->|No| NextPolicy

    PolicyEffect -->|ALLOW| Allow
    PolicyEffect -->|DENY| Deny403Policy[403 Forbidden<br/>Policy denial]

    NextPolicy -->|Yes| EvaluatePolicies
    NextPolicy -->|No| DefaultDeny

    Allow --> CacheResult[Cache Result<br/>TTL: 5min]
    CacheResult --> AuditLog[Log Access Event<br/>to AuthEvent]
    AuditLog --> Success[200 OK<br/>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)

graph LR
    User[User] --> UserRole1[UserRole]
    User --> UserRole2[UserRole]
    User --> UserPerm[UserPermission<br/>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)

graph TD
    Request[Access Request] --> PolicyEngine[Policy Engine]

    PolicyEngine --> LoadPolicies[Load Policies<br/>for Resource]
    LoadPolicies --> SortPolicies[Sort by Priority<br/>Descending]

    SortPolicies --> EvaluatePolicy[Evaluate Policy<br/>Conditions]

    EvaluatePolicy --> TimeCondition{Time-based<br/>Condition?}
    EvaluatePolicy --> LocationCondition{Location-based<br/>Condition?}
    EvaluatePolicy --> AttributeCondition{Attribute-based<br/>Condition?}

    TimeCondition --> CheckTime[Check current time<br/>vs allowed hours]
    LocationCondition --> CheckIP[Check IP address<br/>vs allowed ranges]
    AttributeCondition --> CheckAttrs[Check user attributes<br/>vs required values]

    CheckTime --> ConditionMet{All Conditions<br/>Met?}
    CheckIP --> ConditionMet
    CheckAttrs --> ConditionMet

    ConditionMet -->|Yes| ApplyEffect{Policy<br/>Effect?}
    ConditionMet -->|No| NextPolicy{More<br/>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

Ví Dụ Chính Sách (JSON Logic):

{
  "name": "Business Hours Only",
  "resource": "sensitive_data",
  "condition": {
    "and": [
      {
        ">=": [{"var": "hour"}, 9]
      },
      {
        "<=": [{"var": "hour"}, 17]
      },
      {
        "in": [{"var": "day"}, [1, 2, 3, 4, 5]]
      }
    ]
  },
  "effect": "ALLOW",
  "priority": 100
}

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:

graph TB
    Request[Incoming Request] --> CheckL1{L1 Cache<br/>Node.js Memory}

    CheckL1 -->|Cache Hit| L1Hit[Fast Response<br/>< 1ms latency]
    CheckL1 -->|Cache Miss| CheckL2{L2 Cache<br/>Redis}

    CheckL2 -->|Cache Hit| L2Hit[Medium Response<br/>< 10ms latency]
    CheckL2 -->|Cache Miss| Database[(PostgreSQL<br/>Source of Truth)]

    Database --> UpdateL2[Update L2 Cache<br/>Write to Redis]
    UpdateL2 --> UpdateL1[Update L1 Cache<br/>Write to Memory]

    UpdateL1 --> Response[Return Response]
    L2Hit --> UpdateL1
    L1Hit --> Response

    subgraph "Cache Layers"
        L1Cache[L1: In-Memory Cache<br/>node-cache<br/>TTL: 60 seconds<br/>Hot data only]
        L2Cache[L2: Redis Cache<br/>ioredis<br/>TTL: 5-15 minutes<br/>Distributed]
        DBLayer[L3: PostgreSQL<br/>Prisma ORM<br/>Source of truth<br/>Persistent]
    end

    subgraph "Cached Data Types"
        UserData[User Data<br/>TTL: 15min]
        Permissions[Permissions<br/>TTL: 5min]
        Tokens[Token Validation<br/>TTL: Token lifetime]
        Sessions[Sessions<br/>TTL: Session lifetime]
        Roles[User Roles<br/>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

// 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:

graph TD
    subgraph "Presentation Layer"
        Routes[Routes/Controllers<br/>50+ Endpoints]
    end

    subgraph "Business Logic Layer"
        subgraph "Core Auth"
            AuthModule[Auth Module<br/>Login/Register/Logout]
            TokenModule[Token Module<br/>JWT + Cookies]
            SessionModule[Session Module<br/>Device Tracking]
        end

        subgraph "Extended Auth"
            RBACModule[RBAC Module<br/>Roles + Permissions]
            SocialModule[Social Auth<br/>Google/FB/GitHub]
            OIDCModule[OIDC Module<br/>Provider + Client]
            MFAModule[MFA Module<br/>TOTP/WebAuthn]
        end

        subgraph "Identity"
            IdentityModule[Identity Module<br/>Users + Profiles]
            OrgModule[Organization Module<br/>Multi-tenancy]
            GroupModule[Group Module<br/>Group Permissions]
        end

        subgraph "Access Governance"
            AccessModule[Access Module<br/>Requests + Reviews]
            AnalyticsModule[Analytics Module<br/>Usage Analysis]
        end

        subgraph "Compliance"
            GovernanceModule[Governance Module<br/>Compliance + Risk]
        end
    end

    subgraph "Core Services Layer"
        CacheService[Cache Service<br/>Multi-layer]
        AuditService[Audit Service<br/>Event Sourcing]
        SecurityService[Security Service<br/>Encryption]
        FeatureService[Feature Flags<br/>Runtime Config]
    end

    subgraph "Data Access Layer"
        Repositories[Repositories<br/>Data Access<br/>Prisma ORM]
    end

    subgraph "Infrastructure"
        Database[(PostgreSQL<br/>30+ Models)]
        Redis[(Redis<br/>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 để 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

graph TB
    Request[Incoming Request] --> Layer1[Layer 1: Network Security<br/>Traefik Gateway + TLS]

    Layer1 --> Layer2[Layer 2: Zero-Trust Validation<br/>Device + Location + Behavior]

    Layer2 --> Layer3[Layer 3: Rate Limiting<br/>Dynamic by Role<br/>50-1000 req/15min]

    Layer3 --> Layer4[Layer 4: Authentication<br/>JWT Validation<br/>Token Expiry: 15min]

    Layer4 --> Layer5[Layer 5: Authorization<br/>RBAC + ABAC<br/>Permission Checking]

    Layer5 --> Layer6[Layer 6: Input Validation<br/>Zod Schemas<br/>Sanitization]

    Layer6 --> Layer7[Layer 7: Audit Logging<br/>Event Sourcing<br/>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

graph TB
    subgraph "IAM Service"
        Application[Application Code]

        Application --> MetricsCollector[Metrics Collector<br/>Prometheus Format]
        Application --> Logger[Structured Logger<br/>Winston]
        Application --> Tracer[Distributed Tracer<br/>Jaeger Client]
    end

    subgraph "Collection Layer"
        Prometheus[Prometheus<br/>Metrics Storage]
        Loki[Loki<br/>Log Aggregation]
        Jaeger[Jaeger<br/>Trace Storage]
    end

    subgraph "Visualization Layer"
        Grafana[Grafana<br/>Dashboards + Alerts]
    end

    MetricsCollector --> Prometheus
    Logger --> Loki
    Tracer --> Jaeger

    Prometheus --> Grafana
    Loki --> Grafana
    Jaeger --> Grafana

    Grafana --> Alerts[Alert Manager<br/>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:

{
  "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ộ

graph LR
    Developer[Developer<br/>Localhost] --> LocalIAM[IAM Service<br/>pnpm dev<br/>Port 3001]

    LocalIAM --> LocalDB[(PostgreSQL<br/>Docker<br/>Port 5432)]
    LocalIAM --> LocalRedis[(Redis<br/>Docker<br/>Port 6379)]

    style LocalIAM fill:#e1f5fe
    style LocalDB fill:#f3e5f5
    style LocalRedis fill:#fff3e0

Docker Compose (Multi-Service)

graph TB
    subgraph "Docker Compose Network"
        Traefik[Traefik Gateway<br/>Port 80/443]

        Traefik --> IAMService[IAM Service<br/>Port 3001]
        Traefik --> ProductService[Product Service<br/>Port 3002]
        Traefik --> OrderService[Order Service<br/>Port 3003]

        IAMService --> SharedDB[(PostgreSQL<br/>Port 5432)]
        IAMService --> SharedRedis[(Redis<br/>Port 6379)]

        ProductService --> SharedDB
        ProductService --> SharedRedis

        OrderService --> SharedDB
        OrderService --> SharedRedis
    end

    style Traefik fill:#ffecb3
    style IAMService fill:#e1f5fe
    style SharedDB fill:#f3e5f5
    style SharedRedis fill:#fff3e0

Kubernetes (Production)

graph TB
    subgraph "Ingress Layer"
        Ingress[Ingress Controller<br/>NGINX/Traefik<br/>TLS Termination]
    end

    subgraph "Application Layer"
        IAMPod1[IAM Pod 1<br/>Replica 1]
        IAMPod2[IAM Pod 2<br/>Replica 2]
        IAMPod3[IAM Pod 3<br/>Replica 3]

        IAMService[IAM Service<br/>ClusterIP]
    end

    subgraph "Data Layer"
        PostgreSQL[(PostgreSQL<br/>StatefulSet<br/>Persistent Volume)]
        Redis[(Redis<br/>StatefulSet<br/>Sentinel HA)]
    end

    subgraph "Observability"
        Prometheus[Prometheus<br/>Metrics]
        Jaeger[Jaeger<br/>Tracing]
        Loki[Loki<br/>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

Thực Tiễn Tốt Cho Production

  1. Tính Sẵn Sàng Cao:

    • Nhiều replica IAM service (3+)
    • Replication PostgreSQL (primary + standby)
    • Redis Sentinel cho failover
  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
  3. Giới Hạn Tài Nguyên:

    resources:
      requests:
        cpu: 500m
        memory: 512Mi
      limits:
        cpu: 2000m
        memory: 2Gi
    
  4. Health Checks:

    livenessProbe:
      httpGet:
        path: /health/live
        port: 3001
      initialDelaySeconds: 30
      periodSeconds: 10
    
    readinessProbe:
      httpGet:
        path: /health/ready
        port: 3001
      initialDelaySeconds: 10
      periodSeconds: 5
    
  5. Horizontal Pod Autoscaling:

    minReplicas: 3
    maxReplicas: 10
    targetCPUUtilizationPercentage: 70
    

Bước Tiếp Theo


Tham Chiếu


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