Files
gru_emoney_token-factory/api/services/rest-api/AUTH_IMPLEMENTATION.md
defiQUG c32fcf48e8 Add authentication and idempotency middleware, implement graceful shutdown, and update dependencies
- Introduced `authMiddleware` for request authentication and `optionalAuthMiddleware` for optional authentication.
- Added `idempotencyMiddleware` to ensure idempotent requests are processed correctly, including Redis caching.
- Implemented graceful shutdown for the REST API server to close Redis connections on termination signals.
- Updated `package.json` to include `jsonwebtoken` and its type definitions.
2025-12-12 11:17:59 -08:00

5.9 KiB

Authentication, RBAC, and Idempotency Implementation

Completed Implementation

All three middleware components have been fully implemented:

1. Authentication Middleware

Location: src/middleware/auth.ts
Service: src/services/auth-service.ts

Features:

  • OAuth2 Bearer token validation (JWT)
  • mTLS certificate validation
  • API key validation
  • Request context attachment (req.auth)
  • Optional authentication support

Authentication Methods:

  1. OAuth2 Bearer Token

    • Validates JWT tokens from Authorization: Bearer <token> header
    • Extracts client ID, scopes, and roles
    • Supports token expiration checking
  2. mTLS (Mutual TLS)

    • Validates client certificates for adapter endpoints
    • Certificate fingerprint matching
    • Expiration checking
  3. API Key

    • Validates API keys from X-API-Key header
    • SHA-256 hashed key storage
    • Expiration support

Configuration:

  • JWT_SECRET - Secret for JWT validation
  • OAUTH2_CLIENT_SECRET - OAuth2 client secret
  • API_KEY - API key for internal services

2. RBAC Middleware

Location: src/middleware/rbac.ts

Features:

  • Role-based access control
  • Role hierarchy support (GOVERNANCE_ADMIN inherits all roles)
  • Multiple role requirements (requireAnyRole, requireAllRoles)
  • Scope-based access control
  • Detailed error responses

Available Roles:

  • GOVERNANCE_ADMIN - Full access (inherits all roles)
  • TOKEN_DEPLOYER - Can deploy tokens
  • POLICY_OPERATOR - Can manage policies
  • ISSUER - Can mint/burn tokens
  • ENFORCEMENT - Can clawback/force-transfer
  • COMPLIANCE - Can manage compliance
  • DEBT_AUTHORITY - Can manage liens
  • BRIDGE_OPERATOR - Can operate bridge

Usage Examples:

// Require single role
router.post('/', requireRole('ISSUER'), handler);

// Require any of multiple roles
router.post('/', requireAnyRole('ISSUER', 'ENFORCEMENT'), handler);

// Require all roles
router.post('/', requireAllRoles('ISSUER', 'COMPLIANCE'), handler);

// Require scope
router.get('/', requireScope('read'), handler);

3. Idempotency Middleware

Location: src/middleware/idempotency.ts
Service: src/services/redis.ts

Features:

  • Redis-based idempotency storage
  • Response caching and replay
  • Idempotency key validation
  • TTL-based expiration (24 hours)
  • Automatic response header injection
  • Fail-open on Redis errors

How It Works:

  1. Client sends request with Idempotency-Key header
  2. Middleware checks Redis for existing response
  3. If found, returns cached response with Idempotency-Replayed: true header
  4. If not found, processes request and stores response in Redis
  5. Subsequent requests with same key get cached response

Idempotency Key Format:

  • 1-255 characters
  • Alphanumeric, hyphens, and underscores only
  • Example: req-123e4567-e89b-12d3-a456-426614174000

Response Headers:

  • Idempotency-Key - Echoed from request
  • Idempotency-Replayed - Set to true if response was replayed

Configuration:

  • REDIS_URL - Redis connection URL (default: redis://localhost:6379)

Request Flow

Request
  ↓
Auth Middleware (OAuth2/mTLS/API Key)
  ↓
RBAC Middleware (Role/Scope Check)
  ↓
Idempotency Middleware (Check/Store)
  ↓
Route Handler
  ↓
Response (Cached if idempotent)

Error Responses

401 Unauthorized

{
  "code": "UNAUTHORIZED",
  "message": "Authentication required",
  "reasonCode": "AUTH_REQUIRED"
}

403 Forbidden

{
  "code": "FORBIDDEN",
  "message": "Required role: ISSUER",
  "reasonCode": "INSUFFICIENT_PERMISSIONS",
  "requiredRole": "ISSUER",
  "userRoles": ["COMPLIANCE"]
}

400 Bad Request (Idempotency)

{
  "code": "INVALID_IDEMPOTENCY_KEY",
  "message": "Idempotency key must be 1-255 characters...",
  "reasonCode": "INVALID_IDEMPOTENCY_KEY"
}

Production Considerations

Authentication Service

  1. Client Registry: Replace in-memory registry with database

    • Store client credentials securely (hashed secrets)
    • Support client rotation
    • Track client metadata
  2. JWT Validation:

    • Use JWKS endpoint for token validation
    • Support multiple issuers
    • Implement token refresh
  3. mTLS Certificate Management:

    • Certificate rotation support
    • CRL (Certificate Revocation List) checking
    • Certificate pinning
  4. API Key Management:

    • Use hashed keys in database
    • Support key rotation
    • Track key usage and limits

RBAC

  1. Role Management:

    • Database-backed role storage
    • Dynamic role assignment
    • Role hierarchy configuration
  2. Audit Logging:

    • Log all authorization decisions
    • Track role changes
    • Monitor access patterns

Idempotency

  1. Redis High Availability:

    • Use Redis cluster for production
    • Implement failover
    • Monitor Redis health
  2. Key Management:

    • Implement key expiration policies
    • Monitor key usage
    • Cleanup old keys
  3. Performance:

    • Consider Redis pipelining for bulk operations
    • Monitor cache hit rates
    • Optimize TTL values

Testing

Example test file created: src/services/auth-service.test.ts

To test:

# Run tests
pnpm test

# Test with curl
curl -H "Authorization: Bearer <token>" http://localhost:3000/v1/tokens
curl -H "X-API-Key: <key>" http://localhost:3000/v1/tokens

Dependencies Added

  • jsonwebtoken - JWT token validation
  • redis - Redis client for idempotency
  • @types/jsonwebtoken - TypeScript types

Next Steps

  1. Database Integration: Replace in-memory registries with database
  2. JWKS Support: Implement JWKS endpoint for token validation
  3. Certificate Management: Add certificate rotation and CRL checking
  4. Monitoring: Add metrics for auth failures, role checks, idempotency hits
  5. Rate Limiting: Add rate limiting per client/role
  6. Audit Logging: Log all authentication and authorization events