Implement JWT Secret Rotation #8

Closed
opened 2026-04-06 23:38:16 +02:00 by arcodange · 1 comment
Owner

Implement JWT Secret Rotation

Currently, the JWT secret is hardcoded and cannot be rotated without invalidating all user sessions. We need to implement a secret rotation mechanism with the following requirements:

Requirements

  1. Secret Persistence: Store multiple valid secrets in database with timestamps
  2. Limited Expiration: Set reasonable JWT expiration (e.g., 30 minutes)
  3. Retention Policy: Keep old secrets for 24-48 hours to allow graceful rotation
  4. Rotation Mechanism: Admin endpoint to add new secrets and mark old ones for deletion
  5. Validation Logic: Check tokens against all valid secrets, not just the current one

Implementation Plan

  1. Database Schema:

    CREATE TABLE jwt_secrets (
        id SERIAL PRIMARY KEY,
        secret_hash VARCHAR(255) NOT NULL,
        created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
        expires_at TIMESTAMP WITH TIME ZONE,
        is_active BOOLEAN DEFAULT TRUE
    );
    
  2. Secret Management Service:

    • AddSecret(secret string, expiration time.Duration)
    • RotateSecret() (string, error) // Returns new secret
    • GetValidSecrets() ([]string, error)
    • CleanupExpiredSecrets()
  3. JWT Validation Update:

    • Try all valid secrets when validating tokens
    • Log which secret was used for validation
    • Return specific error for expired tokens
  4. Admin Endpoints:

    • POST /api/v1/admin/auth/secrets/rotate - Rotate current secret
    • GET /api/v1/admin/auth/secrets - List all valid secrets
    • DELETE /api/v1/admin/auth/secrets/{id} - Remove specific secret
  5. Automatic Cleanup:

    • Background job to remove expired secrets
    • Log cleanup operations for audit trail

Security Considerations

  1. Secret Storage: Hash secrets in database (bcrypt or similar)
  2. Access Control: Only admins can rotate secrets
  3. Audit Logging: Log all secret rotation operations
  4. Rate Limiting: Prevent brute force attacks on rotation endpoint

Migration Path

  1. Add new jwt_secrets table
  2. Insert current secret as first entry
  3. Update JWT validation to use secret service
  4. Add admin endpoints
  5. Implement cleanup job
  6. Update documentation

Testing

  • Unit tests for secret service
  • Integration tests for JWT validation with multiple secrets
  • BDD scenarios for admin rotation workflow
  • Performance tests for validation with multiple secrets

References

  • ADR-0018: User Management and Authentication System
  • RFC 7519: JSON Web Token (JWT)
  • OWASP Authentication Cheat Sheet
Implement JWT Secret Rotation Currently, the JWT secret is hardcoded and cannot be rotated without invalidating all user sessions. We need to implement a secret rotation mechanism with the following requirements: ## Requirements 1. **Secret Persistence**: Store multiple valid secrets in database with timestamps 2. **Limited Expiration**: Set reasonable JWT expiration (e.g., 30 minutes) 3. **Retention Policy**: Keep old secrets for 24-48 hours to allow graceful rotation 4. **Rotation Mechanism**: Admin endpoint to add new secrets and mark old ones for deletion 5. **Validation Logic**: Check tokens against all valid secrets, not just the current one ## Implementation Plan 1. **Database Schema**: ```sql CREATE TABLE jwt_secrets ( id SERIAL PRIMARY KEY, secret_hash VARCHAR(255) NOT NULL, created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), expires_at TIMESTAMP WITH TIME ZONE, is_active BOOLEAN DEFAULT TRUE ); ``` 2. **Secret Management Service**: - AddSecret(secret string, expiration time.Duration) - RotateSecret() (string, error) // Returns new secret - GetValidSecrets() ([]string, error) - CleanupExpiredSecrets() 3. **JWT Validation Update**: - Try all valid secrets when validating tokens - Log which secret was used for validation - Return specific error for expired tokens 4. **Admin Endpoints**: - POST /api/v1/admin/auth/secrets/rotate - Rotate current secret - GET /api/v1/admin/auth/secrets - List all valid secrets - DELETE /api/v1/admin/auth/secrets/{id} - Remove specific secret 5. **Automatic Cleanup**: - Background job to remove expired secrets - Log cleanup operations for audit trail ## Security Considerations 1. **Secret Storage**: Hash secrets in database (bcrypt or similar) 2. **Access Control**: Only admins can rotate secrets 3. **Audit Logging**: Log all secret rotation operations 4. **Rate Limiting**: Prevent brute force attacks on rotation endpoint ## Migration Path 1. Add new jwt_secrets table 2. Insert current secret as first entry 3. Update JWT validation to use secret service 4. Add admin endpoints 5. Implement cleanup job 6. Update documentation ## Testing - Unit tests for secret service - Integration tests for JWT validation with multiple secrets - BDD scenarios for admin rotation workflow - Performance tests for validation with multiple secrets ## References - ADR-0018: User Management and Authentication System - RFC 7519: JSON Web Token (JWT) - OWASP Authentication Cheat Sheet
Author
Owner

📊 SOLID Analysis Complete

I've completed a comprehensive SOLID principles and best practices review of the codebase. Here are the key findings:

Critical Issues Found

  1. SRP Violations: manages authentication, users, AND password reset
  2. ISP Violations: Fat interface with 5 methods
  3. DIP Violations: Direct instantiation in handlers
  4. Security Issues: JWT validation needs issuer/audience claims
  5. Password Security: Should use bcrypt cost 12 instead of default

Major Issues Found

  1. KISS Violations: Monolithic 50+ line route setup method
  2. DRY Violations: Repeated error handling code
  3. YAGNI Violations: Over-engineered telemetry with 6 sampler types
  4. Circular Dependencies: Between greet and user packages
  5. Law of Demeter: Complex middleware chain creation

Recommendations

High Priority Refactoring

  • Split into separate handlers
  • Break into focused interfaces
  • Inject dependencies instead of creating them
  • Add proper JWT claims validation (iss, aud, jti)

Medium Priority Improvements

  • Simplify route setup with smaller methods
  • Extract error handling to reusable functions
  • Move context management to separate package
  • Add comprehensive table-driven tests

Low Priority Cleanup

  • Remove unused sampler types
  • Fix circular dependency between packages
  • Add missing test files

Cognitive Complexity Analysis

The current implementation shows:

  • High: AuthHandler (3 responsibilities)
  • Medium: Server route setup (mixed concerns)
  • Low: Individual service methods (well-focused)

After refactoring, we should see:

  • Better separation of concerns
  • Reduced method complexity
  • Improved testability
  • Easier maintenance

Next Steps

I recommend we:

  1. Start with AuthHandler refactoring (highest impact)
  2. Then improve JWT security
  3. Finally address the circular dependencies

This will significantly reduce cognitive load while maintaining all functionality.

📊 SOLID Analysis Complete I've completed a comprehensive SOLID principles and best practices review of the codebase. Here are the key findings: ## Critical Issues Found 1. **SRP Violations**: manages authentication, users, AND password reset 2. **ISP Violations**: Fat interface with 5 methods 3. **DIP Violations**: Direct instantiation in handlers 4. **Security Issues**: JWT validation needs issuer/audience claims 5. **Password Security**: Should use bcrypt cost 12 instead of default ## Major Issues Found 1. **KISS Violations**: Monolithic 50+ line route setup method 2. **DRY Violations**: Repeated error handling code 3. **YAGNI Violations**: Over-engineered telemetry with 6 sampler types 4. **Circular Dependencies**: Between greet and user packages 5. **Law of Demeter**: Complex middleware chain creation ## Recommendations ### High Priority Refactoring - Split into separate handlers - Break into focused interfaces - Inject dependencies instead of creating them - Add proper JWT claims validation (iss, aud, jti) ### Medium Priority Improvements - Simplify route setup with smaller methods - Extract error handling to reusable functions - Move context management to separate package - Add comprehensive table-driven tests ### Low Priority Cleanup - Remove unused sampler types - Fix circular dependency between packages - Add missing test files ## Cognitive Complexity Analysis The current implementation shows: - **High**: AuthHandler (3 responsibilities) - **Medium**: Server route setup (mixed concerns) - **Low**: Individual service methods (well-focused) After refactoring, we should see: - Better separation of concerns - Reduced method complexity - Improved testability - Easier maintenance ## Next Steps I recommend we: 1. Start with AuthHandler refactoring (highest impact) 2. Then improve JWT security 3. Finally address the circular dependencies This will significantly reduce cognitive load while maintaining all functionality.
Sign in to join this conversation.
No Label
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: arcodange/dance-lessons-coach#8