2FA Implementation Task List
Overview
This document contains a comprehensive task list for implementing Two-Factor Authentication (2FA) in the kulcare Rails API backend. Tasks are organized by component and follow a Test-Driven Development (TDD) approach.
Task Status Legend
- Not Started
- [🔄] In Progress
- [✅] Completed
- [🚫] Blocked
- [⚠️] Needs Review
Phase 1: Foundation & Test Setup
1.1 Project Setup
- Create feature branch
feature/2fa-implementation - Add required gems to Gemfile:
-
gem 'rotp', '~> 6.3'for TOTP generation -
gem 'rqrcode', '~> 2.2'for QR code generation
-
- Run
bundle install - Create
parts/two_factordirectory structureparts/two_factor/ ├── controllers/ ├── interactors/ ├── models/ ├── policies/ ├── serializers/ ├── services/ ├── migrate/ ├── routes.rb └── spec/
1.2 Database Schema Design
- Create migration for
two_factor_settingstable- Add user_id with foreign key and unique index
- Add method enum field (totp, sms)
- Add enabled boolean with default false
- Add encrypted totp_secret field
- Add backup_phone field
- Add last_used_at timestamp
- Add timestamps
- Create migration for
two_factor_recovery_codestable- Add user_id with foreign key and index
- Add code_hash field with unique index
- Add used_at timestamp
- Add created_at timestamp
- Create migration for
two_factor_audit_logstable- Add user_id with foreign key and index
- Add action enum field
- Add method field
- Add ip_address field
- Add user_agent field
- Add metadata jsonb field
- Add created_at timestamp with index
1.3 RSpec Test Suite Setup
- Extend existing spec directory structure for 2FA
domains/identity/spec/ ├── models/ │ ├── two_factor_setting_spec.rb # NEW │ ├── two_factor_recovery_code_spec.rb # NEW │ └── two_factor_audit_log_spec.rb # NEW ├── interactors/ │ └── two_factor/ # NEW subdirectory ├── controllers/ │ └── two_factor_controller_spec.rb # NEW ├── requests/ │ └── two_factor_spec.rb # NEW ├── services/ │ └── two_factor_service_spec.rb # NEW └── factories/ ├── two_factor_settings.rb # NEW ├── two_factor_recovery_codes.rb # NEW └── two_factor_audit_logs.rb # NEW - Create factory files for test data
-
factories/two_factor_settings.rb -
factories/two_factor_recovery_codes.rb -
factories/two_factor_audit_logs.rb
-
Phase 2: Model Layer Implementation
2.1 Model Tests (Write First - TDD)
- Write specs for
TwoFactorSettingmodel- Validation tests
- Association tests
- Encryption tests
- Scope tests
- Instance method tests
- Write specs for
TwoFactorRecoveryCodemodel- Code generation tests
- Hash verification tests
- Usage tracking tests
- Uniqueness tests
- Write specs for
TwoFactorAuditLogmodel- Validation tests
- Scope tests
- Query method tests
2.2 Model Implementation
- Implement
TwoFactorSettingmodel- Set up associations with User
- Add validations
- Configure encrypted attributes
- Add scopes (enabled, by_method)
- Add instance methods
- Implement
TwoFactorRecoveryCodemodel- Set up associations
- Add code generation logic
- Add hash verification
- Add usage tracking
- Implement
TwoFactorAuditLogmodel- Set up associations
- Add validations
- Add query scopes
2.3 User Model Updates
- Write tests for User model 2FA methods
- Update User model
- Add
has_one :two_factor_settingassociation - Add
has_many :two_factor_recovery_codesassociation - Add
has_many :two_factor_audit_logsassociation - Add 2FA helper methods
-
two_factor_enabled? -
two_factor_method -
generate_recovery_codes!
-
- Add
Phase 3: Business Logic Layer (Interactors)
3.1 Interactor Tests (Write First - TDD)
- Write specs for TOTP setup interactors
-
TwoFactor::Setup::InitiateTotpspec -
TwoFactor::Setup::VerifyTotpspec -
TwoFactor::Setup::ConfirmTotpspec
-
- Write specs for SMS setup interactors
-
TwoFactor::Setup::InitiateSmsspec -
TwoFactor::Setup::VerifySmsspec
-
- Write specs for verification interactors
-
TwoFactor::Verify::VerifyCodespec -
TwoFactor::Verify::VerifyRecoveryCodespec
-
- Write specs for management interactors
-
TwoFactor::Management::Disablespec -
TwoFactor::Management::GenerateRecoveryCodesspec -
TwoFactor::Management::GetStatusspec
-
3.2 Core Interactor Implementation
- Create base interactor
TwoFactor::BaseInteractor- Common validation methods
- Audit logging helper
- Rate limiting helper
- Implement TOTP setup interactors
-
TwoFactor::Setup::InitiateTotp- Generate TOTP secret
- Create QR code
- Store temporary secret
-
TwoFactor::Setup::VerifyTotp- Verify TOTP code
- Return success/failure
-
TwoFactor::Setup::ConfirmTotp- Enable 2FA
- Generate recovery codes
- Log audit event
-
- Implement SMS setup interactors
-
TwoFactor::Setup::InitiateSms- Validate phone number
- Send verification SMS
-
TwoFactor::Setup::VerifySms- Verify SMS code
- Enable SMS 2FA
- Generate recovery codes
-
3.3 Verification Interactors
- Implement
TwoFactor::Verify::VerifyCode- Check 2FA method
- Verify TOTP or SMS code
- Rate limiting logic
- Audit logging
- Implement
TwoFactor::Verify::VerifyRecoveryCode- Verify recovery code hash
- Mark code as used
- Log recovery usage
- Alert user about low codes
3.4 Management Interactors
- Implement
TwoFactor::Management::Disable- Require current 2FA verification
- Disable 2FA setting
- Clear recovery codes
- Log audit event
- Implement
TwoFactor::Management::GenerateRecoveryCodes- Clear existing unused codes
- Generate new codes
- Return codes for display
- Log generation event
- Implement
TwoFactor::Management::GetStatus- Return 2FA enabled status
- Return configured method
- Return recovery codes count
Phase 4: Service Layer Implementation
4.1 Service Tests (Write First - TDD)
- Write specs for
TwoFactor::TotpService - Write specs for
TwoFactor::QrCodeService - Write specs for
TwoFactor::RecoveryCodeService - Write specs for
TwoFactor::RateLimiter - Write specs for
TwoFactor::AuditLogger
4.2 Service Implementation
- Implement
TwoFactor::TotpService- Secret generation
- Code verification
- URI generation for QR codes
- Implement
TwoFactor::QrCodeService- QR code generation from URI
- Multiple format support (PNG, SVG)
- Size configuration
- Implement
TwoFactor::RecoveryCodeService- Secure code generation
- Code hashing
- Batch generation (10 codes)
- Implement
TwoFactor::RateLimiter- Redis-based rate limiting
- Configurable limits per action
- Lockout mechanism
- Implement
TwoFactor::AuditLogger- Standardized audit logging
- IP and user agent capture
- Metadata storage
Phase 5: Authentication Integration
5.1 Authentication Flow Tests
- Write integration tests for login with 2FA
- Write tests for partial authentication state
- Write tests for JWT token modifications
- Write tests for session management
5.2 Modify Existing Authentication
- Update
Session::SignIninteractor- Check for 2FA after password verification
- Return partial auth state if 2FA enabled
- Issue temporary token for 2FA flow
- Update
Session::ProcessUserinteractor- Add 2FA verification step
- Update token claims with 2FA status
- Update
TokenIssuerservice- Add
two_factor_verifiedclaim - Add
partial_authflag - Implement temporary token logic (10 min expiry)
- Add
5.3 Create 2FA Verification Flow
- Create
Session::VerifyTwoFactorinteractor- Validate temporary token
- Verify 2FA code
- Issue full authentication token
- Update sign-in metrics
Phase 6: API Layer Implementation
6.1 Controller Tests (Write First - TDD)
- Write request specs for setup endpoints
- Write request specs for verification endpoints
- Write request specs for management endpoints
- Write request specs for error scenarios
6.2 Controllers Implementation
- Create
TwoFactorController- Setup actions
-
initiate_totpaction -
verify_totpaction -
confirm_totpaction -
setup_smsaction
-
- Verification actions
-
verifyaction -
verify_recoveryaction -
resend_smsaction
-
- Management actions
-
statusaction -
disableaction -
generate_recovery_codesaction -
recovery_codes_countaction
-
- Setup actions
6.3 Routes Configuration
- Configure routes in
parts/two_factor/routes.rb - Add namespace and endpoints
- Configure authentication requirements
- Add rate limiting middleware
6.4 Serializers
- Create
TwoFactorSettingSerializer - Create
TwoFactorStatusSerializer - Create
RecoveryCodesSerializer - Create
QrCodeSerializer
6.5 Policy Implementation
- Create
TwoFactorControllerPolicy- Ensure user can only manage own 2FA
- Admin override capabilities
- Rate limiting enforcement
Phase 7: Security & Error Handling
7.1 Security Tests
- Write tests for rate limiting
- Write tests for encryption
- Write tests for audit logging
- Write tests for error scenarios
7.2 Security Implementation
- Implement rate limiting for all endpoints
- Setup attempts: 3 per hour
- Verification attempts: 5 per 15 minutes
- SMS sends: 3 per hour
- Recovery code attempts: 3 per hour
- Implement account lockout
- After 10 consecutive failures
- 15-minute cooldown period
- Admin unlock capability
- Implement encryption
- TOTP secrets encryption
- Secure key management
- Implement comprehensive audit logging
- All 2FA actions logged
- IP address tracking
- User agent tracking
7.3 Error Handling
- Create custom error classes
-
TwoFactorNotEnabledError -
InvalidTwoFactorCodeError -
TwoFactorRateLimitError -
RecoveryCodeExhaustedError
-
- Implement error responses
- Standardized error format
- Appropriate HTTP status codes
- User-friendly error messages
- No sensitive data in errors
Phase 8: Admin Tools & Support
8.1 Admin Interface Tests
- Write tests for admin override functionality
- Write tests for admin 2FA management
- Write tests for audit log viewing
8.2 Admin Tools Implementation
- Create admin endpoints
- View user's 2FA status
- Disable user's 2FA (emergency)
- View audit logs
- Generate usage reports
- Create support tools
- User lockout reset
- Recovery code regeneration
- 2FA troubleshooting guide
Phase 9: Documentation
9.1 Technical Documentation
- API documentation
- Endpoint descriptions
- Request/response examples
- Error codes reference
- Integration guide
- Frontend integration steps
- Mobile app integration
- Testing procedures
9.2 User Documentation
- Setup guides
- TOTP setup guide
- SMS setup guide
- Recovery codes guide
- Troubleshooting guide
- Common issues
- Recovery procedures
- FAQ section
9.3 Security Documentation
- Security architecture
- Threat model
- Incident response procedures
- Audit log analysis guide
Phase 10: Testing & Quality Assurance
10.1 Test Coverage
- Achieve >95% code coverage for 2FA components
- All edge cases covered
- Performance tests completed
- Security tests passed
10.2 Integration Testing
- End-to-end login flow with 2FA
- Recovery code usage flow
- SMS fallback testing
- Rate limiting verification
- Cross-browser testing
10.3 Security Testing
- Penetration testing
- TOTP implementation validation
- Encryption verification
- Session management testing
- Rate limiting effectiveness
10.4 Performance Testing
- Load testing for 2FA endpoints
- Database query optimization
- Redis performance validation
- API response time validation (<500ms)
Phase 11: Deployment Preparation
11.1 Feature Flag Setup
- Implement feature flag for 2FA
- Configure gradual rollout capability
- Set up A/B testing framework
11.2 Monitoring & Alerting
- Set up monitoring for 2FA endpoints
- Configure alerts for failures
- Set up audit log monitoring
- Create dashboards for 2FA metrics
11.3 Rollback Plan
- Document rollback procedures
- Create database rollback scripts
- Test rollback scenarios
- Prepare emergency disable switch
Phase 12: Post-Deployment
12.1 Monitoring
- Monitor adoption rates
- Track support tickets
- Analyze failure patterns
- Performance monitoring
12.2 Optimization
- Optimize based on usage patterns
- Improve error messages based on feedback
- Enhance documentation based on support tickets
- Performance tuning if needed
12.3 Success Metrics Tracking
- 2FA adoption rate measurement
- Support ticket analysis
- Security incident tracking
- Performance metrics collection
Dependencies & Blockers
External Dependencies
- Approval of technical specification
- Security team review
- Infrastructure for Redis rate limiting
- SMS provider capacity confirmation
Potential Blockers
- JWT token size limitations
- Redis availability for rate limiting
- SMS delivery reliability
- Mobile app integration timeline
Notes & Considerations
- Priority Order: Follow the phase order as each phase builds on the previous
- TDD Approach: Always write tests before implementation
- Code Review: Each phase should be reviewed before moving to next
- Security First: Any security concerns should block progress until resolved
- Documentation: Keep documentation updated as implementation progresses
- Feature Flag: Use feature flag for gradual rollout and easy rollback
- Integration with Existing Auth: Leverage existing
Verifiableconcern and SMS infrastructure - Consistent Patterns: Follow existing auth module patterns for consistency
- Google Authenticator Support: TOTP implementation works with ALL authenticator apps (Google, Microsoft, Authy, etc.)
- Backup Codes: "Recovery codes" serve as backup/emergency access codes
- Clinic vs User Settings: Later phases will add clinic-level policy enforcement
Phase 13: Clinic-Level 2FA Policy (Future Enhancement)
13.1 Database Schema for Policies
- Create migration for
two_factor_policiestable- Add clinic_id foreign key
- Add enforcement_level enum (disabled, optional, required, role_based)
- Add required_method enum (any_method, totp_only, sms_only)
- Add role_requirements jsonb field
- Add grace_period_days and enforcement_starts_at
- Update
two_factor_settingstable- Add policy_notified_at timestamp
- Add policy_deadline timestamp
- Add policy_compliant boolean
13.2 Policy Models and Logic
- Create
TwoFactorPolicymodel- Associations with clinic
- Enum definitions
- Policy validation methods
- Enhance
TwoFactorSettingmodel- Policy compliance checking
- Grace period calculations
- Enhance User model
- Role determination logic
- Policy status methods
13.3 Clinic Admin Interface
- Create admin endpoints for policy management
- Set clinic 2FA policy
- View compliance reports
- Send policy notifications
- Extend grace periods
- Policy enforcement interactors
- Notify users of policy changes
- Check compliance during login
- Grace period management
13.4 Enhanced User Experience
- Policy status endpoint for users
- Policy compliance warnings in UI
- Help documentation for policy requirements
- Grace period countdown display
Phase 14: Advanced Policy Features (Future Enhancement)
14.1 Role-Based Requirements
- Implement role-specific 2FA requirements
- Dynamic policy application based on user role
- Policy inheritance and overrides
14.2 Compliance Reporting
- Clinic-wide compliance dashboards
- User compliance history
- Policy violation alerts
- Audit reports for regulatory compliance
14.3 Emergency Features
- Admin override capabilities
- Emergency bypass codes
- Temporary policy suspensions
Team Assignments
To be determined based on team availability and expertise:
- Backend Development: [TBD]
- Testing & QA: [TBD]
- Security Review: [TBD]
- Documentation: [TBD]
- DevOps Support: [TBD]
Change Log
- Date Created: [Current Date]
- Last Updated: [Current Date]
- Version: 1.0
- Author: Backend Architecture Team
This task list will be updated as implementation progresses. Each task should be marked with the appropriate status emoji when work begins or completes.