proposal: migrate to external API authentication

Create OpenSpec proposal for migrating from local database authentication
to external API authentication using Microsoft Azure AD.

Changes proposed:
- Replace local username/password auth with external API
- Integrate with https://pj-auth-api.vercel.app/api/auth/login
- Use Azure AD tokens instead of local JWT
- Display user 'name' from API response in UI
- Maintain backward compatibility with feature flag

Benefits:
- Single Sign-On (SSO) capability
- Leverage enterprise identity management
- Reduce local user management overhead
- Consistent authentication across applications

Database changes:
- Add external_user_id for Azure AD user mapping
- Add display_name for UI display
- Keep existing schema for rollback capability

Implementation includes:
- Detailed migration plan with phased rollout
- Comprehensive task list for implementation
- Test script for API validation
- Risk assessment and mitigation strategies

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
egg
2025-11-14 15:14:48 +08:00
parent b048f2d640
commit 28e419f5fa
3 changed files with 577 additions and 0 deletions

View File

@@ -0,0 +1,180 @@
# Implementation Tasks
## 1. Database Schema Updates
- [ ] 1.1 Create database migration script
- Add `external_user_id` column (VARCHAR 255)
- Add `display_name` column (VARCHAR 255)
- Add `azure_email` column (VARCHAR 255)
- Add `last_token_refresh` column (DATETIME)
- Mark `hashed_password` as nullable (for gradual migration)
- [ ] 1.2 Update User model
- Add new fields to SQLAlchemy model
- Update model relationships if needed
- Add migration version with Alembic
- [ ] 1.3 Create user sync mechanism
- Script to map existing users to external IDs
- Handle users without external accounts
- Backup existing user data
## 2. Configuration Management
- [ ] 2.1 Update environment configuration
- Add `EXTERNAL_AUTH_API_URL` to `.env.local`
- Add `EXTERNAL_AUTH_ENDPOINT` configuration
- Add `EXTERNAL_AUTH_TIMEOUT` setting
- Add `USE_EXTERNAL_AUTH` feature flag
- Add `TOKEN_REFRESH_BUFFER` setting
- [ ] 2.2 Update Settings class
- Add external auth settings to `backend/app/core/config.py`
- Add validation for new configuration values
- Implement feature flag logic
## 3. External API Integration Service
- [ ] 3.1 Create auth API client
- Implement `backend/app/services/external_auth_service.py`
- Create async HTTP client for API calls
- Implement request/response models
- Add proper error handling and logging
- [ ] 3.2 Implement authentication methods
- `authenticate_user()` - Call external API
- `validate_token()` - Verify token validity
- `refresh_token()` - Handle token refresh
- `get_user_info()` - Fetch user details
- [ ] 3.3 Add resilience patterns
- Implement retry logic with exponential backoff
- Add circuit breaker pattern
- Implement timeout handling
- Add fallback mechanisms
## 4. Backend Authentication Updates
- [ ] 4.1 Modify login endpoint
- Update `backend/app/api/v1/endpoints/auth.py`
- Route to external API based on feature flag
- Handle both authentication modes during transition
- Return appropriate token format
- [ ] 4.2 Update token validation
- Modify `backend/app/core/security.py`
- Support both local and external tokens
- Implement token type detection
- Update JWT validation logic
- [ ] 4.3 Update authentication dependencies
- Modify `backend/app/core/auth.py`
- Update `get_current_user()` dependency
- Handle external user information
- Implement proper user context
## 5. Session and Token Management
- [ ] 5.1 Implement token storage
- Store external tokens securely
- Implement token encryption at rest
- Handle multiple token types (access, ID, refresh)
- [ ] 5.2 Create token refresh mechanism
- Background task for token refresh
- Refresh tokens before expiration
- Update stored tokens atomically
- Handle refresh failures gracefully
- [ ] 5.3 Session invalidation
- Clear tokens on logout
- Handle token revocation
- Implement session timeout
## 6. Frontend Updates
- [ ] 6.1 Update authentication service
- Modify `frontend/src/services/authService.ts`
- Handle new token format
- Store user display information
- Implement token refresh on client side
- [ ] 6.2 Update auth store
- Modify `frontend/src/stores/authStore.ts`
- Store external user information
- Update user display logic
- Handle token expiration
- [ ] 6.3 Update UI components
- Modify `frontend/src/components/Header.tsx`
- Display user `name` instead of username
- Show additional user information
- Update login form if needed
- [ ] 6.4 Error handling
- Handle external API errors
- Display appropriate error messages
- Implement retry UI for failures
- Add loading states
## 7. Testing
- [ ] 7.1 Unit tests
- Test external auth service
- Test token validation
- Test user information mapping
- Test error scenarios
- [ ] 7.2 Integration tests
- Test full authentication flow
- Test token refresh mechanism
- Test fallback scenarios
- Test feature flag switching
- [ ] 7.3 Load testing
- Test external API response times
- Test system under high authentication load
- Measure impact on performance
- [ ] 7.4 Security testing
- Test token security
- Verify HTTPS enforcement
- Test rate limiting
- Validate error message security
## 8. Migration Execution
- [ ] 8.1 Pre-migration preparation
- Backup database
- Document rollback procedure
- Prepare user communication
- Set up monitoring
- [ ] 8.2 Staged rollout
- Enable for test users first
- Monitor for issues
- Gradually increase user percentage
- Collect feedback
- [ ] 8.3 Post-migration validation
- Verify all users can login
- Check audit logs
- Monitor error rates
- Validate performance metrics
## 9. Documentation
- [ ] 9.1 Technical documentation
- Update API documentation
- Document authentication flow
- Update deployment guide
- Create troubleshooting guide
- [ ] 9.2 User documentation
- Update login instructions
- Document new features
- Create FAQ for common issues
- [ ] 9.3 Operations documentation
- Document monitoring points
- Create runbook for issues
- Document rollback procedure
## 10. Monitoring and Observability
- [ ] 10.1 Add monitoring metrics
- Authentication success/failure rates
- External API response times
- Token refresh success rate
- Error rate monitoring
- [ ] 10.2 Implement logging
- Log all authentication attempts
- Log external API calls
- Log token operations
- Structured logging for analysis
- [ ] 10.3 Create alerts
- Alert on high failure rates
- Alert on external API unavailability
- Alert on token refresh failures
- Alert on unusual patterns
## 11. Cleanup (Post-Stabilization)
- [ ] 11.1 Remove legacy code
- Remove local authentication code (after stable period)
- Remove unused database columns
- Clean up configuration
- [ ] 11.2 Optimize performance
- Implement caching where appropriate
- Optimize database queries
- Review and optimize API calls