airqo-platform / airqo-platform/AirQo-api

Implement Multi-Factor Authentication (MFA) Support in Auth Service

未关闭
#5,499 0 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看
主要语言
JavaScript
星标
26
派生
24
平均合并
5 小时 36 分钟
30 天内合并 PR
81

描述

## Labels
`enhancement` `security` `auth-service` `high-priority`

## Description

### Background
Multi-Factor Authentication (MFA) adds a critical second layer of security beyond username and password. According to Microsoft security research, MFA blocks 99.9% of account compromise attacks. Given the sensitive nature of air quality data and platform administration, implementing MFA is essential for protecting user accounts and organizational data.

### Problem Statement
Currently, the AirQo platform relies solely on password-based authentication, which is vulnerable to:
- **Credential stuffing attacks**: Compromised credentials from other breaches
- **Phishing attacks**: Users tricked into revealing passwords
- **Brute force attacks**: Despite rate limiting, weak passwords remain vulnerable
- **Session hijacking**: Stolen session tokens provide full account access
- **Insider threats**: Single authentication factor is insufficient for privileged accounts

### Proposed Solution
Implement optional MFA in the auth-service with support for:
1. **Time-based One-Time Passwords (TOTP)** - Industry standard, works with Google Authenticator, Authy, 1Password, etc.
2. **SMS-based OTP** - Fallback option for users without smartphone authenticator apps
3. **Recovery codes** - Backup authentication method if primary device is lost
4. **Admin enforcement** - Allow organizations to require MFA for specific user groups

---

## Implementation Tasks

### Phase 1: Research & Architecture (Week 1)
- [ ] Research MFA libraries and best practices
- [ ] Evaluate `speakeasy` (TOTP), `otplib`, or similar Node.js libraries
- [ ] Review SMS providers (Twilio, AWS SNS, Africa's Talking)
- [ ] Study MFA implementations in similar platforms
- [ ] Design database schema for MFA data
- [ ] User MFA settings (enabled/disabled, preferred method)
- [ ] TOTP secrets (encrypted)
- [ ] Backup codes (hashed)
- [ ] MFA recovery information
- [ ] Design API endpoints and authentication flow
- [ ] Create technical design document
- [ ] Security review of proposed architecture

### Phase 2: Backend Implementation (Week 2-4)
- [ ] **Database Schema**
- [ ] Create migration for MFA-related tables
- [ ] Add encryption for TOTP secrets at rest
- [ ] Implement secure backup code storage (hashed)

- [ ] **TOTP Implementation**
- [ ] Implement TOTP secret generation
- [ ] Create QR code generation for easy setup
- [ ] Build TOTP verification endpoint
- [ ] Add time-drift tolerance (±1 time step)

- [ ] **SMS OTP Implementation**
- [ ] Integrate SMS provider (recommend Africa's Talking for African coverage)
- [ ] Implement OTP generation and validation
- [ ] Add rate limiting to prevent SMS abuse
- [ ] Implement cost controls and monitoring

- [ ] **Recovery Codes**
- [ ] Generate cryptographically secure backup codes
- [ ] Implement one-time use validation
- [ ] Add ability to regenerate codes

- [ ] **API Endpoints**

POST /api/v2/users/mfa/enable # Enable MFA for user
POST /api/v2/users/mfa/verify # Verify MFA code during login
POST /api/v2/users/mfa/disable # Disable MFA (requires current MFA code)
GET /api/v2/users/mfa/setup # Get QR code and secret for TOTP setup
POST /api/v2/users/mfa/recovery # Verify recovery code
POST /api/v2/users/mfa/recovery/regenerate # Generate new recovery codes
POST /api/v2/users/mfa/sms/send # Send SMS OTP

### Phase 3: Authentication Flow Updates (Week 4-5)
- [ ] Update login flow to handle MFA challenge
- [ ] After successful password verification, check MFA status
- [ ] If MFA enabled, prompt for second factor
- [ ] Issue session token only after successful MFA verification
- [ ] Implement "Trust this device" option (30-day bypass)
- [ ] Add MFA bypass for specific IP ranges (optional, for orgs)
- [ ] Update JWT payload to include MFA verification status
- [ ] Handle MFA enrollment during first login (if admin-enforced)

### Phase 4: Frontend Integration (Week 5-6)
_Note: Coordinate with frontend team_
- [ ] MFA setup/enrollment screens
- [ ] QR code display for TOTP setup
- [ ] MFA verification screen during login
- [ ] Recovery code display and storage prompts
- [ ] SMS OTP request and verification UI
- [ ] MFA management settings page
- [ ] Admin dashboard for MFA policy enforcement

### Phase 5: Admin Controls (Week 6-7)
- [ ] Organization-level MFA policy settings
- [ ] Optional MFA (default)
- [ ] Required for admin roles
- [ ] Required for all users
- [ ] Admin endpoints to view MFA adoption metrics
- [ ] Admin ability to reset user MFA (emergency access)
- [ ] Audit logging for all MFA events

### Phase 6: Testing & Documentation (Week 7-8)
- [ ] **Unit Tests**
- [ ] TOTP generation and verification
- [ ] SMS OTP generation and verification
- [ ] Recovery code generation and validation
- [ ] Rate limiting tests
- [ ] Edge cases (expired codes, invalid codes, replay attacks)

- [ ] **Integration Tests**
- [ ] Complete MFA enrollment flow
- [ ] Login with MFA flow
- [ ] Recovery code usage flow
- [ ] MFA disable flow

- [ ] **Security Testing**
- [ ] Penetration testing of MFA implementation
- [ ] Verify encrypted storage of secrets
- [ ] Test rate limiting effectiveness
- [ ] Verify session handling with MFA

- [ ] **Documentation**
- [ ] User guide for enabling MFA
- [ ] Admin guide for MFA policies
- [ ] API documentation with examples
- [ ] Troubleshooting guide (lost device, etc.)

### Phase 7: Rollout & Monitoring (Week 8-10)
- [ ] Beta testing with internal team
- [ ] Gradual rollout to power users
- [ ] Monitor adoption metrics
- [ ] Monitor MFA-related support requests
- [ ] Monitor SMS costs and delivery rates
- [ ] Create runbook for common MFA issues
- [ ] Full production rollout

---

## Technical Specifications

### Security Requirements
- ✅ TOTP secrets MUST be encrypted at rest using AES-256
- ✅ Recovery codes MUST be cryptographically hashed (bcrypt/argon2)
- ✅ TOTP verification MUST include time-drift tolerance (±30 seconds)
- ✅ Rate limiting: Max 5 failed MFA attempts per 15 minutes
- ✅ SMS OTP codes valid for 5 minutes only
- ✅ Recovery codes usable only once
- ✅ All MFA events MUST be audit logged
- ✅ Session tokens issued before MFA verification MUST have limited permissions

### Database Schema Example
```javascript
// MFA Settings
{
userId: ObjectId,
mfaEnabled: Boolean,
preferredMethod: String, // 'totp' | 'sms'
totpSecret: String, // encrypted
phoneNumber: String, // encrypted, for SMS
backupCodes: [String], // hashed
trustedDevices: [{
deviceId: String,
expiresAt: Date,
lastUsed: Date
}],
createdAt: Date,
updatedAt: Date
}

// MFA Audit Log
{
userId: ObjectId,
event: String, // 'mfa_enabled', 'mfa_verified', 'mfa_failed', 'recovery_used'
method: String, // 'totp' | 'sms' | 'recovery'
success: Boolean,
ipAddress: String,
userAgent: String,
timestamp: Date
}

Acceptance Criteria
Must Have

✅ Users can enable TOTP-based MFA with QR code setup
✅ MFA verification required during login when enabled
✅ Recovery codes generated and can be used for access
✅ Users can disable MFA (with current MFA verification)
✅ All MFA secrets encrypted at rest
✅ Comprehensive audit logging of all MFA events
✅ Rate limiting prevents brute force attacks
✅ Unit test coverage >80% for MFA code

Should Have

✅ SMS OTP as alternative to TOTP
✅ "Trust this device" option (30-day bypass)
✅ Admin controls for MFA policy enforcement
✅ MFA adoption metrics in admin dashboard
✅ User documentation and setup guides

Nice to Have

✅ WebAuthn/FIDO2 support (hardware keys)
✅ Biometric authentication integration
✅ Email-based OTP as additional fallback
✅ MFA reminder prompts for users without MFA enabled
✅ Organization-wide MFA enforcement date

Security Considerations
Threats Mitigated

✅ Credential Stuffing: Even with valid password, attacker needs second factor
✅ Phishing: Stolen password alone is insufficient
✅ Session Hijacking: Stolen sessions expire, require re-authentication with MFA
✅ Brute Force: Rate limiting + second factor makes attacks impractical
✅ Insider Threats: Additional verification for sensitive operations

Potential Risks & Mitigations

Risk: Users locked out if device lost

Mitigation: Recovery codes provided during enrollment
Mitigation: Admin reset capability with proper verification

Risk: SMS OTP costs and delivery reliability

Mitigation: TOTP as primary recommendation
Mitigation: Cost monitoring and alerts
Mitigation: Use Africa's Talking for better African coverage

Risk: User resistance to MFA

Mitigation: Make MFA optional initially
Mitigation: Clear documentation and benefits communication
Mitigation: "Trust this device" for reduced friction

Resources & References

[RFC 6238 - TOTP Specification](https://datatracker.ietf.org/doc/html/rfc6238)
[OWASP MFA Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Multifactor_Authentication_Cheat_Sheet.html)
[Google Authenticator PAM](https://github.com/google/google-authenticator-libpam)
[Speakeasy (Node.js TOTP library)](https://github.com/speakeasyjs/speakeasy)
[Africa's Talking SMS API](https://africastalking.com/)
[Microsoft MFA Study](https://www.microsoft.com/en-us/security/blog/2019/08/20/one-simple-action-you-can-take-to-prevent-99-9-percent-of-account-attacks/)

Timeline & Priority
Priority: High
Target Completion: End of Q2 2026
Estimated Effort: 8-10 weeks
Dependencies: None (independent feature)

Success Metrics
After 3 months of availability:

✅ 30%+ of active users have enabled MFA
✅ 100% of admin users have MFA enabled (if policy enforced)
✅ Zero account compromises for MFA-enabled accounts
✅ <5% support requests related to MFA issues
✅ 99.9%+ SMS delivery success rate

Related Issues/PRs

Builds upon recent authentication improvements: #5240, #5341, #5266
Related to RBAC hardening: #5402, #5259, #5248
Supports security policy: https://github.com/airqo-platform/AirQo-api/security/policy

Team Assignment

Backend Lead: @[backend-team]
DevOps Support: @[devops-team]

Questions or Concerns?
Comment below or reach out to [techops@airqo.net](mailto:techops@airqo.net)

贡献指南

打开贡献指南

评估

这个 Issue 还没有评估数据。

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。