-
Notifications
You must be signed in to change notification settings - Fork 0
🔐 Security & Authentication System Implementation #7
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
🔐 Security & Authentication System Implementation #7
Conversation
- Multi-factor authentication (MFA) with TOTP and backup codes - OAuth2 integration (Google, GitHub, Microsoft) - SAML 2.0 enterprise SSO support - Role-based access control (RBAC) with granular permissions - HashiCorp Vault integration for secret management - Comprehensive audit logging with compliance reporting - JWT token management with refresh tokens - API key management with scopes and rotation - Security middleware with rate limiting and threat detection - React frontend components for authentication - Docker deployment with monitoring stack - Vulnerability scanning and security policies - SOC2, GDPR, PCI DSS, HIPAA compliance support Features: ✅ Local authentication with secure password policies ✅ Account lockout and progressive security measures ✅ Session management with device tracking ✅ Context-aware permission evaluation ✅ Automatic secret rotation capabilities ✅ Real-time security event monitoring ✅ Compliance reporting and audit trails ✅ Enterprise-grade deployment configuration
|
Important Review skippedBot user detected. To trigger a single review, invoke the You can disable this status message by setting the 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Join our Discord community for assistance with any issues or questions. Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
Reviewer's GuideThis PR introduces a complete security and authentication subsystem under security-system/, integrating audit logging, secret management, authentication providers (local, OAuth2, SAML), token and API-key services, FastAPI middleware with RBAC enforcement, React frontend components, and full deployment artifacts. Sequence Diagram for User Local Login with MFAsequenceDiagram
actor User
participant LoginForm as FE_LoginForm
participant AuthService as FE_AuthService
participant BackendAPI as BE_API
participant LocalAuthP as BE_LocalAuthProvider
participant MFAP as BE_MFAProvider
participant TokenSvc as BE_TokenService
participant AuditLogSvc as BE_AuditLogger
User->>FE_LoginForm: Submits email & password
FE_LoginForm->>FE_AuthService: login(email, password)
FE_AuthService->>BE_API: POST /auth/login (email, password)
BE_API->>BE_LocalAuthProvider: authenticate_user(email, password)
BE_LocalAuthProvider-->>BE_API: User object (if valid, MFA enabled)
BE_API->>BE_AuditLogger: log_authentication_event(LOGIN_ATTEMPT)
alt MFA Required
BE_API-->>FE_AuthService: { mfaRequired: true, mfaToken: "..." }
FE_AuthService-->>FE_LoginForm: Update UI for MFA
User->>FE_LoginForm: Submits MFA code
FE_LoginForm->>FE_AuthService: verifyMFA(mfaToken, mfaCode)
FE_AuthService->>BE_API: POST /auth/mfa/verify (mfaToken, mfaCode)
BE_API->>BE_MFAProvider: verify_mfa(user, mfaCode)
BE_MFAProvider-->>BE_API: MFA valid
BE_API->>BE_TokenService: generate_access_token(user)
BE_TokenService-->>BE_API: accessToken
BE_API->>BE_TokenService: generate_refresh_token(user)
BE_TokenService-->>BE_API: refreshToken
BE_API->>BE_AuditLogger: log_authentication_event(LOGIN_SUCCESS_MFA)
BE_API-->>FE_AuthService: { user, accessToken, refreshToken }
else Credentials Invalid / MFA not set up (but password valid)
BE_API->>BE_TokenService: generate_access_token(user) "(if no MFA)"
BE_TokenService-->>BE_API: accessToken "(if no MFA)"
BE_API->>BE_TokenService: generate_refresh_token(user) "(if no MFA)"
BE_TokenService-->>BE_API: refreshToken "(if no MFA)"
BE_API->>BE_AuditLogger: log_authentication_event(LOGIN_SUCCESS / LOGIN_FAILURE)
BE_API-->>FE_AuthService: { user, accessToken, refreshToken } or { error }
end
FE_AuthService-->>FE_LoginForm: LoginResponse / Error
FE_LoginForm->>User: Shows success / error message
Sequence Diagram for API Request Authentication via MiddlewaresequenceDiagram
participant Client
participant AuthMiddleware as BE_AuthMiddleware
participant TokenSvc as BE_TokenService
participant PermissionEval as BE_PermissionEvaluator
participant DB as Database
participant APIEndpoint as BE_APIEndpoint
participant AuditLogSvc as BE_AuditLogger
Client->>AuthMiddleware: API Request (e.g., GET /data)
AuthMiddleware->>AuthMiddleware: _authenticate_request()
alt API Key Auth
AuthMiddleware->>DB: Find APIKey by hashed key
DB-->>AuthMiddleware: APIKey object (if found)
AuthMiddleware->>DB: Get User from APIKey.user_id
DB-->>AuthMiddleware: User object
Note over AuthMiddleware: Set request.state.user, .api_key
else JWT Auth
AuthMiddleware->>TokenSvc: verify_access_token(jwt_from_header)
TokenSvc-->>AuthMiddleware: Decoded payload (if valid)
AuthMiddleware->>DB: Get User from payload.sub
DB-->>AuthMiddleware: User object
Note over AuthMiddleware: Set request.state.user, .mfa_verified
else No/Invalid Auth
AuthMiddleware-->>Client: 401 Unauthorized Response
AuthMiddleware->>AuditLogSvc: log_authentication_event(AUTH_FAILURE)
end
alt Auth Successful
AuthMiddleware->>PermissionEval: _check_permissions(request, user)
PermissionEval->>DB: Load user roles/permissions
DB-->>PermissionEval: Roles/Permissions data
PermissionEval-->>AuthMiddleware: Permission granted/denied
alt Permission Denied
AuthMiddleware-->>Client: 403 Forbidden Response
AuthMiddleware->>AuditLogSvc: log_authorization_event(PERMISSION_DENIED)
else Permission Granted
AuthMiddleware->>APIEndpoint: call_next(request)
APIEndpoint->>APIEndpoint: Process request
APIEndpoint-->>AuthMiddleware: Response
AuthMiddleware->>AuthMiddleware: Add security headers
AuthMiddleware-->>Client: API Response
AuthMiddleware->>AuditLogSvc: log_resource_access(...)
end
end
Entity Relationship Diagram for Security System ModelserDiagram
User {
UUID id PK
string email
string password_hash
boolean mfa_enabled
string mfa_secret
list_str backup_codes
datetime last_login
integer failed_login_attempts
datetime locked_until
boolean is_active
boolean is_verified
list_Role roles
list_UserSession sessions
list_APIKeyModel api_keys
list_AuditLog audit_logs
}
Role {
UUID id PK
string name
string description
list_Permission permissions
}
Permission {
UUID id PK
string name
string description
}
UserSession {
UUID id PK
UUID user_id FK
string session_token
datetime expires_at
datetime last_activity
string ip_address
string user_agent
boolean is_mfa_verified
boolean is_active
}
APIKeyModel {
UUID id PK
UUID user_id FK
string key_hash
string key_prefix
list_str scopes
datetime expires_at
datetime last_used
integer usage_count
boolean is_active
}
AuditLog {
UUID id PK
string event_id
string event_type
string severity
datetime timestamp
UUID user_id FK "Nullable"
string session_id "Nullable"
string ip_address "Nullable"
string user_agent "Nullable"
string resource_type "Nullable"
string resource_id "Nullable"
string action "Nullable"
string outcome
string message
json details "Nullable"
string correlation_id "Nullable"
list_str compliance_tags "Nullable"
}
User ||--o{ UserSession : "has"
User ||--o{ APIKeyModel : "has"
User ||--o{ AuditLog : "generates"
User }o--o{ Role : "has (many-to-many)"
Role }o--o{ Permission : "has (many-to-many)"
Class Diagram for Audit Logging SystemclassDiagram
class AuditEventType {
<<Enumeration>>
LOGIN_SUCCESS
LOGIN_FAILURE
PERMISSION_DENIED
RESOURCE_READ
# ... other event types
}
class AuditSeverity {
<<Enumeration>>
LOW
MEDIUM
HIGH
CRITICAL
}
class AuditEvent {
<<Dataclass>>
string event_id
AuditEventType event_type
AuditSeverity severity
datetime timestamp
string user_id
string outcome
string message
dict details
}
class AuditLogger {
db_session_factory
bool enable_async
ThreadPoolExecutor executor
Queue event_queue
log_event(event_type, message, severity, user_id, outcome, details)
log_authentication_event(event_type, user_id, ip_address, outcome)
log_authorization_event(user_id, resource_type, action, outcome)
log_resource_access(user_id, resource_type, action, outcome)
search_events(start_time, end_time, event_types)
_process_events_async()
_flush_batch(events)
_write_event_sync(event)
}
AuditLogger ..> AuditEvent : uses
AuditLogger ..> AuditEventType : uses
AuditLogger ..> AuditSeverity : uses
AuditLogger ..> AuditLog : writes
Class Diagram for Vault Client (Secret Management)classDiagram
class VaultAuthMethod {
<<Enumeration>>
TOKEN
USERPASS
APPROLE
AWS_IAM
KUBERNETES
LDAP
}
class SecretMetadata {
<<Dataclass>>
string path
int version
datetime created_time
}
class VaultClient {
hvac.Client client
string url
VaultAuthMethod auth_method
dict auth_config
_authenticate()
read_secret(path, version) Optional~dict~
write_secret(path, secret_data) bool
delete_secret(path, versions) bool
list_secrets(path) Optional~list~
get_secret_metadata(path) Optional~SecretMetadata~
create_database_credentials(db_role) Optional~dict~
encrypt_data(plaintext, key_name) Optional~str~
decrypt_data(ciphertext, key_name) Optional~str~
}
VaultClient ..> VaultAuthMethod : uses
VaultClient ..> SecretMetadata : uses
Class Diagram for Token and Key Rotation ServicesclassDiagram
class TokenService {
string secret_key
string algorithm
string private_key "Nullable (for RS256)"
string public_key "Nullable (for RS256)"
int access_token_expire_minutes
int refresh_token_expire_days
generate_access_token(user_id, email, roles, permissions) string
generate_refresh_token(user_id, session_id) string
verify_access_token(token) Optional~dict~
verify_refresh_token(token) Optional~dict~
refresh_access_token(refresh_token, user_data) Optional~tuple~
generate_api_key(prefix) tuple~str,str,str~
hash_api_key(api_key) string
verify_api_key(api_key, stored_hash) bool
_encode_token(payload) string
_decode_token(token) dict
}
class KeyRotationService {
TokenService token_service
list key_history
generate_new_rsa_keypair() tuple~str,str~
rotate_keys() tuple~str,str~
verify_token_with_history(token) Optional~dict~
cleanup_old_keys(max_age_days)
}
KeyRotationService o-- TokenService : uses
Class Diagram for Authentication MiddlewareclassDiagram
class AuthenticationMiddleware {
db_session_factory
TokenService token_service
SessionService session_service
PermissionEvaluator permission_evaluator
list excluded_paths
dispatch(request, call_next) Response
_authenticate_request(request, db_session) dict
_authenticate_api_key(request, db_session) dict
_authenticate_jwt(request, db_session) dict
_authenticate_session(request, db_session) dict
_check_permissions(request, user, db_session) bool
}
class RequireAuth {
bool require_mfa
list required_permissions
__call__(request) User
}
AuthenticationMiddleware o-- TokenService : uses
AuthenticationMiddleware o-- SessionService : uses "(Conceptual)"
AuthenticationMiddleware o-- PermissionEvaluator : uses "(Conceptual)"
Class Diagram for Local Authentication and MFA ProvidersclassDiagram
class PasswordPolicy {
int min_length
bool require_uppercase
validate_password(password, user_info) tuple~bool,list~
}
class AccountLockoutPolicy {
int max_attempts
int lockout_duration_minutes
calculate_lockout_duration(attempt_count) timedelta
}
class LocalAuthProvider {
PasswordPolicy password_policy
AccountLockoutPolicy lockout_policy
int bcrypt_rounds
hash_password(password) string
verify_password(password, hashed_password) bool
authenticate_user(email, password, user_model, db_session) tuple~bool,User,str~
handle_failed_login(user)
handle_successful_login(user)
}
class MFAProvider {
string issuer_name
generate_secret() string
generate_qr_code(secret, user_email) bytes
verify_totp(secret, token, window) bool
generate_backup_codes(count) list~str~
verify_backup_code(code, hashed_codes) tuple~bool,str~
setup_mfa(user, db_session) tuple~str,list,bytes~
verify_mfa(user, token) tuple~bool,str~
}
LocalAuthProvider o-- PasswordPolicy : uses
LocalAuthProvider o-- AccountLockoutPolicy : uses
File-Level Changes
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
🎯 Feature Implementation
This PR implements a comprehensive security and authentication system that provides secure access control, API authentication, secret management, and audit logging for the entire AI workflow platform.
🚀 Key Features Implemented
🔐 Authentication & Authorization
🔒 Secret Management
📊 Security & Compliance
🛡️ Security Features
🎨 Frontend Components
📁 Implementation Structure
🔧 Technical Implementation
Database Models
Authentication Providers
Security Services
🚀 Deployment Ready
Docker Configuration
Monitoring & Observability
🛡️ Security Measures
Password Policy
Account Protection
API Security
📋 Compliance Features
Audit Events
Compliance Mappings
🧪 Testing & Quality
📚 Documentation
🔗 Integration Points
This security system integrates seamlessly with:
✅ Ready for Production
This implementation provides enterprise-grade security features that are:
The security system is now ready to protect the entire AI workflow platform with comprehensive authentication, authorization, and audit capabilities.
Files Modified:
security-system/- Complete security system implementationrequirements.txt- Python dependenciesdocker-compose.yml- Full deployment stackDockerfile- Production-ready containerREADME.md- Comprehensive documentation💻 View my work • About Codegen
Note
I'm currently writing a description for your pull request. I should be done shortly (<1 minute). Please don't edit the description field until I'm finished, or we may overwrite each other. If I find nothing to write about, I'll delete this message.
Summary by Sourcery
Implement a comprehensive security and authentication subsystem for the AI workflow platform, including authentication flows, authorization controls, secret management, audit logging, and deployment orchestration.
New Features:
Build:
Documentation: