pytmbot

๐Ÿ“œ Access Control for pyTMBot ๐Ÿšช๐Ÿ”

๐Ÿ” Overview

The access control mechanism in pyTMBot ensures that only authorized users can access certain functionalities. This process involves several key components working together: AccessControl middleware, SessionManager, user identification, authentication, authorization, and comprehensive security monitoring with real-time admin alerts.

๐Ÿ—๏ธ Architecture Components

1. AccessControl Middleware ๐Ÿ›ก๏ธ

2. SessionManager ๐Ÿ”

๐Ÿ”ง Session Management

The SessionManager implements several advanced features:

Thread-Safe Architecture

Session States (_StateFabric)

Automatic Cleanup System

Security Features

๐Ÿšจ Security Monitoring & Admin Alerts

AccessControl Middleware Protection

  1. Real-time Admin Notifications:
    • Immediate alerts sent to admin via global_chat_id
    • Detailed information with masked user data for privacy
    • Smart suppression (300 seconds per user) to prevent spam
  2. Automatic Blocking System:
    • Users blocked after 3 failed attempts (MAX_ATTEMPTS)
    • 1-hour block duration (BLOCK_DURATION)
    • Automatic cleanup every hour (CLEANUP_INTERVAL)
  3. Security Intelligence:
    • Token leak detection hints
    • Proactive security recommendations
    • Comprehensive audit trail with timestamps
  4. Data Privacy Protection:
    • Username masking via mask_username() function
    • User ID masking via mask_user_id() function
    • Automatic sensitive data protection in communications

๐Ÿ“Š Updated Comprehensive Workflow Diagram

graph TD
    UserRequest[๐Ÿ‘ค User Request] --> AccessMiddleware[๐Ÿ›ก๏ธ Access Control Middleware]
    
    AccessMiddleware --> CheckBlocked{๐Ÿšซ User Blocked?}
    CheckBlocked -->|Yes| BlockResponse[โ›” Block Response]
    CheckBlocked -->|No| CheckAllowed{โœ… User Allowed?}
    
    CheckAllowed -->|No| HandleUnauth[๐Ÿšจ Handle Unauthorized]
    CheckAllowed -->|Yes| SessionCheck[๐Ÿ” Session Check]
    
    HandleUnauth --> IncrementAttempts[๐Ÿ“Š Increment Attempts]
    IncrementAttempts --> CheckMaxAttempts{Max Attempts?}
    CheckMaxAttempts -->|Yes| BlockUser[๐Ÿšซ Block User]
    CheckMaxAttempts -->|No| NotifyAdmin[๐Ÿ“ข Notify Admin]
    BlockUser --> NotifyAdmin
    NotifyAdmin --> DenyAccess[โŒ Deny Access]
    
    SessionCheck --> SessionManager[๐Ÿ” Session Manager]
    SessionManager --> CheckAuthState{Auth State?}
    
    CheckAuthState -->|BLOCKED| BlockResponse
    CheckAuthState -->|UNAUTHENTICATED| StartAuth[๐Ÿ”‘ Start Authentication]
    CheckAuthState -->|PROCESSING| ContinueAuth[โณ Continue Authentication]
    CheckAuthState -->|AUTHENTICATED| ValidateSession{Session Valid?}
    
    ValidateSession -->|Expired| ExpireSession[โฐ Expire Session]
    ValidateSession -->|Valid| HandleRequest[โœ… Handle Request]
    ExpireSession --> StartAuth
    
    StartAuth --> CheckTOTP{TOTP Required?}
    CheckTOTP -->|Yes| Generate2FA[๐Ÿ” Generate 2FA]
    CheckTOTP -->|No| SetAuthenticated[โœ… Set Authenticated]
    
    Generate2FA --> ShowQR[๐Ÿ“ฑ Show QR Code]
    ShowQR --> SetProcessing[โณ Set Processing State]
    SetProcessing --> WaitTOTP[โฑ๏ธ Wait for TOTP]
    
    ContinueAuth --> VerifyTOTP{Verify TOTP?}
    VerifyTOTP -->|Valid| ResetAttempts[๐Ÿ”„ Reset TOTP Attempts]
    VerifyTOTP -->|Invalid| IncrementTOTP[๐Ÿ“ˆ Increment TOTP Attempts]
    
    ResetAttempts --> SetAuthenticated
    IncrementTOTP --> CheckTOTPMax{Max TOTP Attempts?}
    CheckTOTPMax -->|Yes| BlockUserTOTP[๐Ÿšซ Block User - TOTP]
    CheckTOTPMax -->|No| RetryTOTP[๐Ÿ”„ Retry TOTP]
    
    BlockUserTOTP --> SecurityAlert[๐Ÿšจ Security Alert]
    SecurityAlert --> DenyAccess
    RetryTOTP --> WaitTOTP
    
    SetAuthenticated --> SetLoginTime[โฐ Set Login Time]
    SetLoginTime --> HandleRequest
    
    HandleRequest --> LogAccess[๐Ÿ“ Log Access]
    LogAccess --> ProcessRequest[โš™๏ธ Process Request]
    ProcessRequest --> Done[โœ… Done]
    
    DenyAccess --> Done
    BlockResponse --> Done
    
    %% Background Processes
    CleanupThread[๐Ÿงน Cleanup Thread] --> CleanupExpired[๐Ÿ—‘๏ธ Clean Expired Sessions]
    CleanupThread --> CleanupBlocked[๐Ÿ—‘๏ธ Clean Expired Blocks]
    CleanupExpired --> CleanupBlocked
    
    %% Admin Monitoring
    AdminDashboard[๐Ÿ“Š Admin Dashboard] --> SessionStats[๐Ÿ“ˆ Session Statistics]
    AdminDashboard --> SecurityAlerts[๐Ÿšจ Security Alerts]
    AdminDashboard --> AuditTrail[๐Ÿ“‹ Audit Trail]
    
    style UserRequest fill:#e1f5fe
    style AccessMiddleware fill:#f3e5f5
    style SessionManager fill:#e8f5e8
    style HandleRequest fill:#e8f5e8
    style SecurityAlert fill:#ffebee
    style BlockUser fill:#ffebee
    style CleanupThread fill:#fff3e0
    style AdminDashboard fill:#f1f8e9

๐Ÿ“ฑ Enhanced Access Control Process

1. User Request Processing ๐Ÿ“ฒ

When a user initiates a request, it passes through multiple security layers:

Access Control Middleware Layer

Session Management Layer

2. Security Alert System ๐Ÿšจ

Unauthorized Access Handling

# Key Constants
MAX_ATTEMPTS = 3  # Maximum failed attempts
BLOCK_DURATION = 3600  # 1 hour block duration
ADMIN_NOTIFY_SUPPRESSION = 300  # 5 minutes notification suppression

Process Flow:

  1. Attempt Tracking: Increment unauthorized access counter
  2. Threshold Check: Evaluate against MAX_ATTEMPTS
  3. Auto-Blocking: Apply temporary block if threshold exceeded
  4. Admin Notification: Send masked security alert to admin
  5. Audit Logging: Record detailed security event

Privacy-Compliant Notifications

3. Session State Management ๐Ÿ”

Authentication States

class _StateFabric:
    AUTHENTICATED = "authenticated"  # Full access granted
    PROCESSING = "processing"  # Authentication in progress
    BLOCKED = "blocked"  # Temporarily blocked
    UNAUTHENTICATED = "unauthenticated"  # Needs authentication

Session Lifecycle

  1. Creation: New session with UNAUTHENTICATED state
  2. Authentication: State progression through auth process
  3. Validation: Continuous session validity checks
  4. Expiration: Automatic cleanup after timeout
  5. Cleanup: Background thread removes expired sessions

4. Two-Factor Authentication (2FA) ๐Ÿ”

TOTP Management

Security Features

5. Background Maintenance ๐Ÿงน

Cleanup Operations

Statistics and Monitoring

# Available Session Statistics
{
    "total_sessions": int,
    "authenticated_sessions": int,
    "blocked_sessions": int,
    "expired_sessions": int,
    "processing_sessions": int
}

๐Ÿ”’ Security Configuration

AccessControl Middleware Settings

MAX_ATTEMPTS = 3  # Failed attempts before blocking
BLOCK_DURATION = 3600  # Block duration in seconds
CLEANUP_INTERVAL = 3600  # Cleanup interval in seconds
ADMIN_NOTIFY_SUPPRESSION = 300  # Admin notification suppression

SessionManager Settings

cleanup_interval = 600  # Background cleanup interval
session_timeout = 10  # Session timeout in minutes
max_totp_attempts = 5  # Maximum TOTP attempts
block_duration = 10  # Block duration in minutes

๐Ÿ›ก๏ธ Advanced Security Features

Thread-Safe Architecture

Comprehensive Logging

Admin Security Dashboard

๐Ÿš€ Best Practices

  1. Regular Monitoring: Review admin alerts and session statistics
  2. Token Management: Follow recommendations for token rotation
  3. Configuration Tuning: Adjust timeouts and attempt limits based on usage
  4. Audit Reviews: Regular security event analysis
  5. Update Management: Keep security settings current

๐Ÿ“Š Monitoring and Diagnostics

Session Statistics

Security Metrics

๐Ÿ“ฌ Conclusion

This comprehensive access control system provides enterprise-grade security through multi-layered protection, intelligent monitoring, and automated threat response. The combination of AccessControl middleware and SessionManager ensures robust security while maintaining usability and performance.

The system balances security with user experience through intelligent blocking, session management, and privacy-compliant monitoring, making it suitable for production environments requiring strict access control.

For further information or to report issues, please refer to our GitHub repository or contact support.