- 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.
5.9 KiB
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:
-
OAuth2 Bearer Token
- Validates JWT tokens from
Authorization: Bearer <token>header - Extracts client ID, scopes, and roles
- Supports token expiration checking
- Validates JWT tokens from
-
mTLS (Mutual TLS)
- Validates client certificates for adapter endpoints
- Certificate fingerprint matching
- Expiration checking
-
API Key
- Validates API keys from
X-API-Keyheader - SHA-256 hashed key storage
- Expiration support
- Validates API keys from
Configuration:
JWT_SECRET- Secret for JWT validationOAUTH2_CLIENT_SECRET- OAuth2 client secretAPI_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 tokensPOLICY_OPERATOR- Can manage policiesISSUER- Can mint/burn tokensENFORCEMENT- Can clawback/force-transferCOMPLIANCE- Can manage complianceDEBT_AUTHORITY- Can manage liensBRIDGE_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:
- Client sends request with
Idempotency-Keyheader - Middleware checks Redis for existing response
- If found, returns cached response with
Idempotency-Replayed: trueheader - If not found, processes request and stores response in Redis
- 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 requestIdempotency-Replayed- Set totrueif 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
-
Client Registry: Replace in-memory registry with database
- Store client credentials securely (hashed secrets)
- Support client rotation
- Track client metadata
-
JWT Validation:
- Use JWKS endpoint for token validation
- Support multiple issuers
- Implement token refresh
-
mTLS Certificate Management:
- Certificate rotation support
- CRL (Certificate Revocation List) checking
- Certificate pinning
-
API Key Management:
- Use hashed keys in database
- Support key rotation
- Track key usage and limits
RBAC
-
Role Management:
- Database-backed role storage
- Dynamic role assignment
- Role hierarchy configuration
-
Audit Logging:
- Log all authorization decisions
- Track role changes
- Monitor access patterns
Idempotency
-
Redis High Availability:
- Use Redis cluster for production
- Implement failover
- Monitor Redis health
-
Key Management:
- Implement key expiration policies
- Monitor key usage
- Cleanup old keys
-
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 validationredis- Redis client for idempotency@types/jsonwebtoken- TypeScript types
Next Steps
- Database Integration: Replace in-memory registries with database
- JWKS Support: Implement JWKS endpoint for token validation
- Certificate Management: Add certificate rotation and CRL checking
- Monitoring: Add metrics for auth failures, role checks, idempotency hits
- Rate Limiting: Add rate limiting per client/role
- Audit Logging: Log all authentication and authorization events