11 KiB
Security Hardening Implementation Summary
Overview
This document summarizes the security hardening improvements added to the authentication service. All changes are marked with clear comments in the code for easy identification.
1. OTP Logging Safety ✅
Implementation: src/utils/otpLogger.js
- Safe OTP logging helper that only logs in development mode
- Never logs OTPs to production or centralized logging systems
- Uses
logOtpForDebug()function that:- Only logs when
NODE_ENV === 'development' - Masks phone numbers (shows only last 4 digits)
- Clearly marked as
[DEV-ONLY]
- Only logs when
Updated Files:
src/services/smsService.js- Now uses safe logging instead of directconsole.log
Configuration:
- No configuration needed - automatically detects environment
2. IP/Device Risk Controls ✅
Implementation: src/services/riskScoring.js
- IP blocking: Blocks logins from configured CIDR ranges (private IPs, test ranges)
- Risk scoring: Calculates risk score based on:
- IP address changes
- Device changes
- User agent changes
- Suspicious refresh detection: Detects when refresh tokens are used from different environments
Features:
- Configurable blocked IP ranges via
BLOCKED_IP_RANGESenvironment variable - Optional OTP re-verification requirement for suspicious refreshes
- Risk scores logged to audit trail
Updated Files:
src/routes/authRoutes.js- Integrated IP blocking and risk scoring
Configuration:
BLOCKED_IP_RANGES=10.0.0.0/8,172.16.0.0/12 # Comma-separated CIDR blocks
REQUIRE_OTP_ON_SUSPICIOUS_REFRESH=true # Require OTP on suspicious refresh
3. Access Token Replay Mitigation ✅
Implementation: src/middleware/stepUpAuth.js
- Step-up authentication middleware for sensitive operations
- Requires either:
- Recent OTP verification (within configurable window)
- High assurance flag in token (set after OTP verification)
- Access tokens now include
high_assuranceclaim after OTP verification
Usage:
router.post('/users/me/change-phone',
authMiddleware,
requireRecentOtpOrReauth,
async (req, res) => { ... }
);
Updated Files:
src/services/tokenService.js- AddedhighAssuranceoption tosignAccessToken()src/middleware/authMiddleware.js- Extractshigh_assuranceclaim from tokensrc/routes/authRoutes.js- Issues tokens withhighAssurance: trueafter OTP verification
Configuration:
STEP_UP_OTP_WINDOW_MINUTES=5 # Time window for "recent" OTP (default: 5)
4. Refresh Token Theft Mitigation ✅
Implementation: Enhanced in src/routes/authRoutes.js and src/services/riskScoring.js
- Environment fingerprinting: Tracks IP, user-agent, device ID
- Suspicious refresh detection: Compares current refresh with previous environment
- Optional OTP requirement: Can require OTP re-verification for suspicious refreshes
- Enhanced logging: All suspicious refreshes logged with risk scores
Features:
- Detects IP changes, device changes, user-agent changes
- Calculates risk score (0-100)
- Logs suspicious events to audit trail
- Optionally blocks suspicious refreshes until OTP verification
Configuration:
REQUIRE_OTP_ON_SUSPICIOUS_REFRESH=true # Require OTP on suspicious refresh
5. JWT Key Rotation & Secrets Management ✅
Implementation: src/services/jwtKeys.js
- Multiple signing keys with key IDs (kid) in JWT header
- Active key for signing: Configurable via
JWT_ACTIVE_KEY_ID - Multiple verification keys: Supports key rotation without breaking existing tokens
- Strict claims validation: Validates
iss,aud,exp,iat,nbf
Key Features:
- Tokens include
kidin header for key identification - Supports multiple keys for graceful rotation
- Validates issuer and audience claims
- Backward compatible with legacy single-key setup
Updated Files:
src/services/tokenService.js- Uses new key management systemsrc/middleware/authMiddleware.js- Validates tokens with key rotation support
Configuration:
JWT_ACTIVE_KEY_ID=1 # Key ID for signing new tokens
JWT_KEYS_JSON='{"1":"secret1","2":"secret2"}' # Multiple keys for rotation
JWT_ISSUER=farm-auth-service # Issuer claim
JWT_AUDIENCE=mobile-app # Audience claim
JWT_REFRESH_KEY_ID=1 # Key ID for refresh tokens (optional)
TODO for Production:
- Load keys from secrets manager (AWS Secrets Manager, HashiCorp Vault, etc.)
- See comments in
src/services/jwtKeys.jsfor implementation example
6. Stricter JWT Claims Validation ✅
Implementation: src/services/jwtKeys.js - validateTokenClaims()
- Issuer (iss) validation: Ensures tokens are from correct service
- Audience (aud) validation: Ensures tokens are for correct application
- Expiration (exp) validation: Already handled, but now with clock skew tolerance
- Issued at (iat) validation: Prevents tokens issued in the future
- Not before (nbf) validation: Validates if present
Features:
- Configurable clock skew (default: 60 seconds)
- Centralized validation function
- Used in all token verification paths
Configuration:
- Claims values set via
JWT_ISSUERandJWT_AUDIENCEenvironment variables
7. CORS Hardening ✅
Implementation: src/index.js
- Strict origin whitelisting: Only allows explicitly configured origins
- No wildcard support: Never uses
*when credentials are involved - Clear warnings: Logs when allowing all origins (development only)
- Production requirement: CORS origins must be configured in production
Features:
- Development mode: Allows all origins only if none configured (with warning)
- Production mode: Requires explicit origin whitelist
- Validates origin on every request
- Blocks unauthorized origins with 403
Configuration:
CORS_ALLOWED_ORIGINS=https://app.example.com,https://api.example.com
WARNING: Never use * as an allowed origin when credentials or tokens are involved.
8. CSRF Future-Proofing ✅
Implementation: CSRF_NOTES.md
- Documentation: Comprehensive notes on CSRF protection
- Current status: No CSRF protection needed (using Bearer tokens)
- Future guidance: Implementation strategy if moving to cookies
Key Points:
- Current implementation (Bearer tokens) is CSRF-safe
- If moving to HTTP-only cookies, CSRF protection becomes mandatory
- Recommended: SameSite cookies + CSRF token validation
9. Enhanced Audit Logging ✅
Implementation: src/services/auditLogger.js
- Risk levels: INFO, SUSPICIOUS, HIGH_RISK
- Enhanced logging: All events include risk level
- Anomaly detection: Helper functions for pattern detection
- Suspicious event logging:
- Multiple failed OTP attempts
- Suspicious refresh events
- Blocked IP logins
Features:
- Automatic
risk_levelcolumn creation inauth_audittable - Structured logging with metadata
- Easy integration with external alerting systems
Updated Files:
src/routes/authRoutes.js- Uses enhanced audit logging throughout
Logging Functions:
logAuthEvent()- General auth event logginglogSuspiciousOtpAttempt()- Failed OTP attemptslogBlockedIpLogin()- Blocked IP loginslogSuspiciousRefresh()- Suspicious refresh eventscheckAnomalies()- Pattern detection (for future alerting)
TODO for Production:
- Integrate with external alerting (PagerDuty, Slack, email)
- See comments in
src/services/auditLogger.jsfor implementation example
10. Input Validation ✅
Implementation: src/middleware/validation.js
- Centralized validation: Reusable middleware for all endpoints
- Type checking: Validates field types
- Length limits: Prevents DoS via large payloads
- Format validation: Validates phone numbers, OTP codes, etc.
Validation Middleware:
validateRequestOtpBody()- OTP request validationvalidateVerifyOtpBody()- OTP verification validationvalidateRefreshTokenBody()- Refresh token validationvalidateLogoutBody()- Logout validation
Features:
- Validates required fields
- Validates field types
- Validates string lengths
- Validates formats (phone, OTP code)
- Prevents oversized payloads
Updated Files:
src/routes/authRoutes.js- All endpoints use validation middleware
Environment Variables Summary
Required
DATABASE_URL=postgresql://...
JWT_ACCESS_SECRET=... # Or use JWT_KEYS_JSON
JWT_REFRESH_SECRET=... # Or use JWT_KEYS_JSON
Optional (with defaults)
# JWT Configuration
JWT_ACTIVE_KEY_ID=1
JWT_KEYS_JSON='{"1":"secret1","2":"secret2"}'
JWT_ISSUER=farm-auth-service
JWT_AUDIENCE=mobile-app
JWT_REFRESH_KEY_ID=1
# Security Hardening
BLOCKED_IP_RANGES=10.0.0.0/8,172.16.0.0/12
REQUIRE_OTP_ON_SUSPICIOUS_REFRESH=false
STEP_UP_OTP_WINDOW_MINUTES=5
# CORS
CORS_ALLOWED_ORIGINS=https://app.example.com
# Rate Limiting (from previous implementation)
OTP_REQ_PHONE_10MIN_LIMIT=3
OTP_REQ_PHONE_DAY_LIMIT=10
OTP_REQ_IP_10MIN_LIMIT=20
OTP_REQ_IP_DAY_LIMIT=100
OTP_VERIFY_MAX_ATTEMPTS=5
OTP_VERIFY_FAILED_PER_HOUR_LIMIT=10
OTP_TTL_SECONDS=120
Code Markers
All security hardening code is marked with comments:
// === SECURITY HARDENING: OTP LOGGING ===// === SECURITY HARDENING: IP/DEVICE RISK ===// === SECURITY HARDENING: JWT KEY ROTATION ===// === SECURITY HARDENING: ACCESS TOKEN REPLAY MITIGATION ===// === SECURITY HARDENING: REFRESH TOKEN THEFT MITIGATION ===// === SECURITY HARDENING: AUDIT LOGS & ANOMALY FLAGS ===// === SECURITY HARDENING: INPUT VALIDATION ===// === SECURITY HARDENING: CORS ===// === SECURITY HARDENING: CSRF (FUTURE-PROOFING) ===
Testing Recommendations
- OTP Logging: Verify OTPs are not logged in production
- IP Blocking: Test with blocked IP ranges
- Risk Scoring: Test with different IPs/devices
- JWT Key Rotation: Test token verification with multiple keys
- CORS: Test with allowed and blocked origins
- Input Validation: Test with invalid payloads
- Audit Logging: Verify risk levels are logged correctly
Next Steps
- Secrets Management: Integrate with AWS Secrets Manager or HashiCorp Vault
- Alerting: Set up alerts for HIGH_RISK events
- Monitoring: Monitor audit logs for suspicious patterns
- Key Rotation: Implement automated key rotation process
- CSRF: If moving to cookies, implement CSRF protection
Files Created
src/utils/otpLogger.js- Safe OTP loggingsrc/services/riskScoring.js- IP/device risk scoringsrc/services/jwtKeys.js- JWT key managementsrc/middleware/validation.js- Input validationsrc/services/auditLogger.js- Enhanced audit loggingsrc/middleware/stepUpAuth.js- Step-up authenticationCSRF_NOTES.md- CSRF protection documentationSECURITY_HARDENING_SUMMARY.md- This file
Files Modified
src/services/smsService.js- Safe OTP loggingsrc/services/tokenService.js- JWT key rotation, claims validationsrc/middleware/authMiddleware.js- JWT key rotation supportsrc/routes/authRoutes.js- All security features integratedsrc/index.js- CORS hardeningsrc/config.js- New environment variables documented