# IAM Service
> **Enterprise-Grade Identity & Access Management Platform**
>
> Comprehensive authentication, authorization, identity management, access governance, and compliance reporting for microservices architecture.





[Quick Start](#quick-start) •
[Documentation](#documentation) •
[Features](#features-showcase) •
[Architecture](docs/ARCHITECTURE.en.md) •
[API Reference](docs/API_REFERENCE.md)
---
## At a Glance
| Metric | Value |
|--------|-------|
| **API Endpoints** | 50+ across 10 modules |
| **Database Models** | 30+ with comprehensive relationships |
| **Authentication Methods** | 7 (Password, Google, Facebook, GitHub, OIDC, MFA x2) |
| **Authorization Models** | RBAC + ABAC (Hybrid) |
| **Compliance Frameworks** | GDPR, SOC2, ISO27001, HIPAA |
| **Caching Layers** | 3 (Memory → Redis → Database) |
| **Security Features** | Zero-Trust, Device Fingerprinting, Dynamic Rate Limiting |
| **Production Status** | ✅ Ready (95% implementation) |
---
## Features Showcase
🔐 Authentication
- ✅ Email/Password with bcrypt (cost 12)
- ✅ Social Login (Google, Facebook, GitHub)
- ✅ OpenID Connect (Provider + Client)
- ✅ Multi-Factor Authentication (TOTP)
- ✅ JWT + Refresh Tokens (15min/7days)
- ✅ Session Management with Device Tracking
- ✅ CSRF Protection & Secure Cookies
|
🛡️ Authorization
- ✅ RBAC (Role-Based Access Control)
- ✅ ABAC (Attribute-Based Access Control)
- ✅ Permission Model (resource:action:scope)
- ✅ Direct User Permissions (override roles)
- ✅ Group-Based Permissions
- ✅ Temporary Role Assignments
- ✅ Policy Engine with JSON Logic
|
👤 Identity Management
- ✅ User Lifecycle Management (CRUD)
- ✅ Extended User Profiles
- ✅ Email/Phone/Document Verification
- ✅ Multi-Tenant Organizations
- ✅ Groups with Hierarchical Structure
- ✅ Bulk User Import/Export
- ✅ User Deactivation & Reactivation
|
🔍 Access Governance
- ✅ Access Request Workflows
- ✅ Multi-Person Approval Chains
- ✅ Access Reviews & Certification
- ✅ Access Analytics & Reporting
- ✅ Just-In-Time (JIT) Access
- ✅ Temporary Access Grants
- ✅ Anomaly Detection
|
📊 Compliance & Governance
- ✅ GDPR Compliance Reporting
- ✅ SOC2 Compliance Reporting
- ✅ ISO27001 Compliance Reporting
- ✅ HIPAA Compliance Support
- ✅ Policy Templates & Versioning
- ✅ Risk Scoring & Management
- ✅ Comprehensive Audit Logs
|
⚡ Performance & Security
- ✅ Multi-Layer Caching (L1/L2/L3)
- ✅ Zero-Trust Architecture
- ✅ Device Fingerprinting
- ✅ Dynamic Rate Limiting (by role)
- ✅ Event Sourcing for Audit
- ✅ Connection Pooling
- ✅ Prometheus Metrics & Jaeger Tracing
|
---
## Quick Start
Get up and running in **less than 5 minutes**:
### Prerequisites
- Node.js 18+ and pnpm
- PostgreSQL 14+
- Redis 6+
- Docker (optional, for infra)
### Installation
```bash
# 1. Install dependencies
pnpm install
# 2. Configure environment
cp env.local.example .env.local
# Edit .env.local with your database and Redis URLs
# 3. Setup database
pnpm prisma:generate
pnpm prisma:migrate
pnpm prisma:seed
# 4. Start development server
pnpm dev
```
### Verify Installation
```bash
# Health check
curl http://localhost:3001/health
# Expected response:
# {"status":"ok","timestamp":"2024-01-01T00:00:00.000Z"}
```
### First API Call
```bash
# Register a new user
curl -X POST http://localhost:3001/api/v1/auth/register \
-H "Content-Type: application/json" \
-d '{
"email": "user@example.com",
"password": "SecurePass123!"
}'
```
**For detailed setup instructions**, see [Quick Start Guide](docs/QUICK_START.md).
---
## Documentation
Documentation is organized by audience and use case:
### 📚 For Developers
Start here if you're integrating with or extending the IAM Service:
| Document | Description |
|----------|-------------|
| [**Getting Started**](docs/guides/01-GETTING-STARTED.md) | Your first authentication flow |
| [**API Reference**](docs/API_REFERENCE.md) | Complete API documentation (50+ endpoints) |
| [**Authentication Guide**](docs/guides/02-AUTHENTICATION-GUIDE.md) | Password, Social, OIDC, MFA |
| [**Authorization Guide**](docs/guides/03-AUTHORIZATION-GUIDE.md) | RBAC, ABAC, Permission Model |
| [**Code Examples**](docs/examples/CODE-SAMPLES.md) | TypeScript, React, Vue, Python, cURL |
### 🏗️ For Architects
Understand the system design and data architecture:
| Document | Description |
|----------|-------------|
| [**Architecture Overview**](docs/ARCHITECTURE.en.md) | System architecture with diagrams ⭐ |
| [**Core Concepts**](docs/concepts/CORE-CONCEPTS.md) | IAM fundamentals explained |
| [**Data Model**](docs/concepts/DATA-MODEL.md) | 30+ models with complete ERD |
| [**Security Model**](docs/concepts/SECURITY-MODEL.md) | Security architecture & threat model |
| [**IAM Proposal**](../../docs/en/architecture/iam-proposal.md) | Architectural proposal & roadmap |
### 🚀 For Operators
Deploy and manage the IAM Service in production:
| Document | Description |
|----------|-------------|
| [**Deployment Guide**](docs/deployment/DEPLOYMENT-GUIDE.md) | Kubernetes, Docker, Cloud deployment |
| [**Configuration**](docs/deployment/CONFIGURATION.md) | Environment variables & settings |
| [**Monitoring**](docs/deployment/MONITORING.md) | Metrics, logs, traces, alerts |
| [**Troubleshooting**](docs/guides/07-TROUBLESHOOTING.md) | Common issues & solutions |
### 🔒 For Security Teams
Audit, compliance, and security features:
| Document | Description |
|----------|-------------|
| [**Security Model**](docs/concepts/SECURITY-MODEL.md) | Defense-in-depth security |
| [**Compliance**](docs/guides/05-ACCESS-GOVERNANCE.md#compliance--reporting) | GDPR, SOC2, ISO27001, HIPAA |
| [**Audit Logging**](docs/ARCHITECTURE.en.md#observability) | Event sourcing & audit trail |
| [**Security Skill**](../../.cursor/skills/security/SKILL.md) | Security patterns reference |
### 📖 Complete Documentation Index
View all documentation
**Core Documentation**:
- [Quick Start Guide](docs/QUICK_START.md)
- [API Reference](docs/API_REFERENCE.md)
- [Architecture (EN)](docs/ARCHITECTURE.en.md) | [Architecture (VI)](docs/ARCHITECTURE.vi.md)
- [Features Overview](docs/FEATURES.md)
- [Implementation Details](docs/IMPLEMENTATION.md)
**Concepts**:
- [Core Concepts](docs/concepts/CORE-CONCEPTS.md) - IAM fundamentals
- [Data Model](docs/concepts/DATA-MODEL.md) - Database schema & ERD
- [Security Model](docs/concepts/SECURITY-MODEL.md) - Security architecture
**User Guides**:
- [01 - Getting Started](docs/guides/01-GETTING-STARTED.md)
- [02 - Authentication Guide](docs/guides/02-AUTHENTICATION-GUIDE.md)
- [03 - Authorization Guide](docs/guides/03-AUTHORIZATION-GUIDE.md)
- [04 - Identity Management](docs/guides/04-IDENTITY-MANAGEMENT.md)
- [05 - Access Governance](docs/guides/05-ACCESS-GOVERNANCE.md)
- [06 - Integration Guide](docs/guides/06-INTEGRATION-GUIDE.md)
- [07 - Troubleshooting](docs/guides/07-TROUBLESHOOTING.md)
**Examples**:
- [Basic Usage](docs/examples/BASIC-USAGE.md)
- [Advanced Scenarios](docs/examples/ADVANCED-SCENARIOS.md)
- [Code Samples](docs/examples/CODE-SAMPLES.md)
**Deployment**:
- [Deployment Guide](docs/deployment/DEPLOYMENT-GUIDE.md)
- [Configuration](docs/deployment/CONFIGURATION.md)
- [Monitoring](docs/deployment/MONITORING.md)
**Reference**:
- [Security Patterns](../../.cursor/skills/security/SKILL.md)
- [IAM Proposal](../../docs/en/architecture/iam-proposal.md)
- [Migration Guide](../../docs/en/guides/iam-migration.md)
---
## Architecture Overview
The IAM Service follows a **layered architecture** with clear separation of concerns:
```
┌─────────────────────────────────────────────────────────────┐
│ Client Layer │
│ Web Apps │ Mobile Apps │ Services │
└─────────────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────────┐
│ Traefik API Gateway │
│ Load Balancing │ TLS │ Routing │
└─────────────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────────┐
│ Middleware Stack │
│ Correlation ID → Logger → Zero-Trust → Rate Limit → │
│ Authentication → Authorization │
└─────────────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────────┐
│ Feature Modules (10) │
│ │
│ ┌─────────────┐ ┌────────────┐ ┌──────────────┐ │
│ │ Auth │ │ Identity │ │ Access │ │
│ │ Token │ │ Profile │ │ Request │ │
│ │ Session │ │ Org │ │ Review │ │
│ │ RBAC │ │ Group │ │ Analytics │ │
│ │ Social │ │ Verify │ │ │ │
│ │ OIDC │ │ │ │ Governance │ │
│ │ MFA │ │ │ │ Compliance │ │
│ └─────────────┘ └────────────┘ └──────────────┘ │
└─────────────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────────┐
│ Core Services │
│ Cache Service │ Audit Service │ Security Service │
└─────────────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────────┐
│ Data Layer │
│ PostgreSQL (30+ Models) │ Redis (Cache) │
└─────────────────────────────────────────────────────────────┘
```
**See [ARCHITECTURE.en.md](docs/ARCHITECTURE.en.md) for detailed diagrams and flows.**
---
## Key API Endpoints
### Authentication (`/api/v1/auth`)
```
POST /register Register new user
POST /login Login with email/password
POST /logout Logout user
POST /refresh Refresh access token
POST /change-password Change password
GET /me Get current user
```
### Social Authentication (`/api/v1/auth/social`)
```
GET /google Initiate Google OAuth
GET /facebook Initiate Facebook OAuth
GET /github Initiate GitHub OAuth
GET /google/callback Google OAuth callback
GET /facebook/callback Facebook OAuth callback
GET /github/callback GitHub OAuth callback
```
### RBAC (`/api/v1/rbac`)
```
GET /roles List all roles
POST /roles Create role
GET /permissions List all permissions
POST /users/:id/roles Assign role to user
DELETE /users/:id/roles/:id Revoke role from user
POST /users/:id/permissions Grant permission to user
```
### MFA (`/api/v1/mfa`)
```
POST /totp/enable Enable TOTP MFA
POST /totp/verify Verify TOTP code
POST /totp/validate Validate TOTP during login
POST /totp/disable Disable TOTP MFA
GET /devices List MFA devices
```
### Identity Management (`/api/v1/identity`)
```
GET /users List users
POST /users Create user
GET /users/:id Get user
PUT /users/:id Update user
POST /users/:id/deactivate Deactivate user
POST /users/:id/reactivate Reactivate user
GET /users/:id/profile Get user profile
PUT /users/:id/profile Update user profile
POST /users/:id/avatar Upload avatar
```
### Access Management (`/api/v1/access`)
```
POST /requests Create access request
GET /requests List access requests
POST /requests/:id/approve Approve request
POST /requests/:id/reject Reject request
POST /reviews Create access review
GET /reviews List access reviews
POST /reviews/:id/items/:id/review Review access item
GET /analytics/usage Get usage analytics
```
### Governance (`/api/v1/governance`)
```
POST /compliance/reports Create compliance report
GET /compliance/reports List compliance reports
POST /compliance/reports/:id/generate Generate report
GET /risk/scores Get risk scores
POST /risk/calculate Calculate user risk
GET /policies/templates List policy templates
```
**For complete API documentation, see [API Reference](docs/API_REFERENCE.md).**
---
## Database Schema
The IAM Service uses **PostgreSQL 14+** with **Prisma ORM**. Key models:
### Core Authentication
- **User** - User accounts with email/password/MFA
- **Session** - Active user sessions with device tracking
- **RefreshToken** - Long-lived refresh tokens with rotation
- **AuthEvent** - Audit log for all authentication events
- **SocialAccount** - Linked OAuth provider accounts
- **MFADevice** - TOTP and WebAuthn devices
### Authorization
- **Role** - Named collections of permissions (ADMIN, MANAGER, USER)
- **Permission** - Granular permissions (resource:action:scope)
- **UserRole** - User-role assignments with expiration
- **RolePermission** - Role-permission mappings
- **UserPermission** - Direct user permissions (override roles)
- **Policy** - ABAC policies with JSON Logic conditions
### Identity Management
- **Organization** - Multi-tenant organizations with hierarchy
- **Group** - User groups within organizations
- **GroupMember** - Group membership with roles
- **UserProfile** - Extended user information
- **IdentityVerification** - Email/phone/document verification
### Access Management
- **AccessRequest** - Access request workflows
- **AccessRequestApprover** - Multi-person approval
- **AccessReview** - Access certification campaigns
- **AccessReviewItem** - Individual review items
### Governance
- **ComplianceReport** - GDPR, SOC2, ISO27001 reports
- **PolicyTemplate** - Reusable policy templates
- **RiskScore** - User risk scoring
**For complete ERD and schema details, see [Data Model](docs/concepts/DATA-MODEL.md).**
---
## Security Features
The IAM Service implements **defense-in-depth security** with multiple layers:
### 1. Zero-Trust Architecture
- Every request validated (no implicit trust)
- Device fingerprinting for session binding
- Location analysis (IP address validation)
- Behavioral analysis (unusual patterns)
- Risk-based authentication decisions
### 2. Authentication Security
- Bcrypt password hashing (cost factor 12)
- JWT tokens with short lifetime (15 minutes)
- Refresh token rotation with family tracking
- Secure HTTP-only cookies
- CSRF protection
### 3. Authorization Security
- Principle of least privilege
- Permission caching (5 minutes TTL)
- Direct permission overrides
- Temporary role assignments
- Group-based inheritance
### 4. Rate Limiting
- **Dynamic by role**:
- Anonymous: 50 req/15min
- Regular User: 100 req/15min
- Moderator: 300 req/15min
- Admin: 500 req/15min
- Super Admin: 1000 req/15min
- Redis-backed distributed limiting
- Login-specific limits (5 attempts/15min)
### 5. Audit Logging
- All authentication events logged
- All authorization decisions logged
- Event sourcing for compliance
- 7-year retention for compliance
- Correlation IDs for request tracking
### 6. Input Validation
- Zod schemas for all inputs
- SQL injection prevention (Prisma ORM)
- XSS prevention (Content Security Policy)
- File upload validation
**For complete security details, see [Security Model](docs/concepts/SECURITY-MODEL.md).**
---
## Performance
### Multi-Layer Caching Strategy
```
Request → L1 (Memory, 60s) → L2 (Redis, 5-15min) → L3 (PostgreSQL)
```
- **L1 Cache**: In-memory (node-cache), 60s TTL, hot data only
- **L2 Cache**: Redis, 5-15min TTL, distributed across instances
- **L3 Cache**: PostgreSQL with connection pooling
### Cached Data Types
| Data Type | L1 TTL | L2 TTL | Invalidation |
|-----------|--------|--------|--------------|
| User Data | 60s | 15min | On user update |
| Permissions | 60s | 5min | On permission change |
| User Roles | 60s | 5min | On role assignment |
| Token Validation | N/A | Token lifetime | On logout |
| Rate Limit Counters | N/A | 15min | Time-based |
### Performance Metrics
- **Token Validation**: < 1ms (L1 cache hit)
- **Permission Check**: < 5ms (L2 cache hit)
- **Login**: ~100ms (bcrypt + database + cache)
- **API Response Time**: P95 < 100ms
---
## Development
### Available Scripts
```bash
# Development
pnpm dev # Start dev server with hot reload
# Building
pnpm build # Build for production
pnpm start # Start production server
# Database
pnpm prisma:generate # Generate Prisma client
pnpm prisma:migrate # Run migrations
pnpm prisma:seed # Seed database
pnpm prisma:studio # Open Prisma Studio
# Testing
pnpm test # Run tests
pnpm test:watch # Run tests in watch mode
pnpm test:coverage # Generate coverage report
# Code Quality
pnpm lint # Run ESLint
pnpm format # Format with Prettier
pnpm typecheck # TypeScript type checking
```
### Project Structure
```
services/iam-service/
├── src/
│ ├── config/ # Configuration files
│ │ ├── app.config.ts
│ │ ├── database.config.ts
│ │ ├── jwt.config.ts
│ │ └── redis.config.ts
│ ├── core/ # Core utilities
│ │ ├── cache/ # Multi-layer caching
│ │ ├── events/ # Audit logging & event sourcing
│ │ └── security/ # Zero-trust validator
│ ├── modules/ # Feature modules
│ │ ├── auth/ # Core authentication
│ │ ├── rbac/ # RBAC system
│ │ ├── token/ # JWT & Cookie management
│ │ ├── session/ # Session management
│ │ ├── mfa/ # Multi-factor auth
│ │ ├── social/ # Social OAuth
│ │ ├── oidc/ # OpenID Connect
│ │ ├── identity/ # Identity management
│ │ ├── access/ # Access management
│ │ ├── governance/ # Governance & compliance
│ │ ├── feature/ # Feature flags
│ │ ├── health/ # Health checks
│ │ └── metrics/ # Prometheus metrics
│ ├── middlewares/ # Express middlewares
│ ├── repositories/ # Data access layer (Prisma)
│ ├── routes/ # Route definitions
│ ├── types/ # TypeScript types
│ ├── errors/ # Error handling
│ ├── utils/ # Utilities
│ └── docs/ # Swagger documentation
├── prisma/ # Prisma schema & migrations
│ ├── schema.prisma
│ ├── seed.ts
│ └── migrations/
├── docs/ # Documentation
├── tests/ # Tests
└── package.json
```
---
## Migration from Auth Service
This service was migrated from `auth-service` to `iam-service` to reflect its expanded scope as a comprehensive Identity and Access Management platform.
### Backward Compatibility ✅
**No Breaking Changes**: All existing endpoints remain unchanged and fully functional:
- `/api/v1/auth/*` - Authentication endpoints
- `/api/v1/rbac/*` - RBAC endpoints
- `/api/v1/mfa/*` - MFA endpoints
- `/api/v1/sessions/*` - Session management endpoints
### New Capabilities
The IAM service extends the original auth-service with:
1. **Identity Management**:
- User lifecycle management (CRUD, bulk operations)
- Extended user profiles with custom fields
- Email/phone/document verification
- Multi-tenant organizations with hierarchy
- Groups with member management
2. **Access Management**:
- Access request workflows with approval chains
- Access reviews & certification campaigns
- Access analytics and anomaly detection
- Just-In-Time (JIT) access
- Temporary access grants
3. **Governance & Compliance**:
- GDPR compliance reporting
- SOC2 compliance reporting
- ISO27001 compliance reporting
- HIPAA compliance support
- Policy templates & versioning
- Risk scoring & management
**For detailed migration instructions, see [Migration Guide](../../docs/en/guides/iam-migration.md).**
---
## Production Deployment
### Docker
```bash
# Build Docker image
docker build -t goodgo/iam-service:latest .
# Run container
docker run -d \
--name iam-service \
-p 3001:3001 \
-e DATABASE_URL="postgresql://..." \
-e REDIS_HOST="redis" \
goodgo/iam-service:latest
```
### Kubernetes
```yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: iam-service
spec:
replicas: 3
selector:
matchLabels:
app: iam-service
template:
metadata:
labels:
app: iam-service
spec:
containers:
- name: iam-service
image: goodgo/iam-service:latest
ports:
- containerPort: 3001
env:
- name: DATABASE_URL
valueFrom:
secretKeyRef:
name: iam-secrets
key: database-url
resources:
requests:
cpu: 500m
memory: 512Mi
limits:
cpu: 2000m
memory: 2Gi
livenessProbe:
httpGet:
path: /health/live
port: 3001
initialDelaySeconds: 30
periodSeconds: 10
readinessProbe:
httpGet:
path: /health/ready
port: 3001
initialDelaySeconds: 10
periodSeconds: 5
```
**For complete deployment guides, see [Deployment Documentation](docs/deployment/DEPLOYMENT-GUIDE.md).**
---
## Observability
### Metrics (Prometheus)
- HTTP request duration (histogram)
- HTTP request count by status code (counter)
- Active sessions (gauge)
- Cache hit/miss ratio (counter)
- Database query duration (histogram)
- Authentication success/failure rate (counter)
**Endpoint**: `GET /metrics`
### Logging (Winston)
Structured JSON logs with correlation IDs:
```json
{
"level": "info",
"message": "User logged in",
"timestamp": "2024-01-01T00:00:00.000Z",
"correlationId": "req-123-456",
"userId": "user-789",
"email": "user@example.com",
"service": "iam-service"
}
```
### Tracing (Jaeger)
Distributed tracing with spans for:
- HTTP request handling
- Database queries
- Cache operations
- External API calls (OAuth)
- Authentication flows
- Authorization checks
### Health Checks
```bash
# Liveness probe (is the app running?)
curl http://localhost:3001/health/live
# Readiness probe (is the app ready to serve traffic?)
curl http://localhost:3001/health/ready
# Full health check (with dependencies)
curl http://localhost:3001/health
```
---
## Contributing
This is a proprietary service for the GoodGo platform. For internal development:
1. Create a feature branch
2. Make your changes
3. Write tests
4. Submit a pull request
5. Wait for code review
---
## Support
- **Documentation**: Start with [Quick Start Guide](docs/QUICK_START.md)
- **API Reference**: See [API Documentation](docs/API_REFERENCE.md)
- **Troubleshooting**: Check [Troubleshooting Guide](docs/guides/07-TROUBLESHOOTING.md)
- **Issues**: Internal issue tracker
- **Security**: Report security issues to security@goodgo.com
---
## License
Proprietary - GoodGo Platform
© 2024-2026 GoodGo. All rights reserved.
---
## Related Documentation
- **[Security Patterns](../../.cursor/skills/security/SKILL.md)** - Security best practices reference
- **[IAM Proposal](../../docs/en/architecture/iam-proposal.md)** - Original IAM architectural proposal
- **[Migration Guide](../../docs/en/guides/iam-migration.md)** - Migrating from auth-service
---
**Last Updated**: January 2026
**Version**: 1.0.0
**Status**: Production Ready