Skip to content

[FEATURE][SECURITY]: Enhanced session management for admin UI #541

@crivetimihai

Description

@crivetimihai

[FEATURE][SECURITY]: Enhanced Session Management for Admin UI

Goal

Implement comprehensive session management for the Admin UI including session lifecycle control, configurable timeouts, session binding (IP/user-agent), and administrative session oversight. This builds on the existing SessionRegistry to add enterprise-grade session security.

Why Now?

  1. Enterprise Security Requirements: SOC2, HIPAA require session timeout and monitoring
  2. Concurrent Session Control: Organizations need to limit sessions per user
  3. Session Hijacking Protection: Binding sessions to IP/user-agent reduces risk
  4. Admin Oversight: Administrators need visibility into active sessions
  5. Compliance Auditing: Session events must be logged for audit trails

Current State

The SessionRegistry class (mcpgateway/cache/session_registry.py) already provides:

  • Session storage with memory/Redis/database backends
  • Session add/remove/get operations
  • Cross-worker session sharing via Redis
  • Basic session metadata tracking

Missing features:

  • Session timeout (idle and absolute)
  • Session rotation
  • IP/user-agent binding
  • Max sessions per user
  • Session enumeration for admins
  • Session revocation API

📖 User Stories

US-1: Security - Enforce Session Timeouts

As a security engineer
I want sessions to expire after idle and absolute timeouts
So that abandoned sessions cannot be hijacked

Acceptance Criteria:

Scenario: Idle timeout enforcement
  Given SESSION_IDLE_TIMEOUT_MINUTES=30
  And a user session has been idle for 35 minutes
  When the user makes a request
  Then the session should be invalidated
  And the user should be redirected to login

Scenario: Absolute timeout enforcement
  Given SESSION_ABSOLUTE_TIMEOUT_MINUTES=480 (8 hours)
  And a user session was created 9 hours ago
  When the user makes a request (even if recently active)
  Then the session should be invalidated
  And the user should be required to re-authenticate

Scenario: Activity extends idle timeout
  Given SESSION_IDLE_TIMEOUT_MINUTES=30
  And a user makes a request at minute 25
  Then the idle timeout should reset to 30 minutes from now
  And the session should remain valid

Technical Requirements:

  • Add last_activity timestamp to sessions
  • Add created_at timestamp to sessions
  • Check timeouts on each authenticated request
  • Provide clear re-authentication flow
US-2: Security - Limit Concurrent Sessions

As a security administrator
I want to limit the number of concurrent sessions per user
So that credential sharing is discouraged

Acceptance Criteria:

Scenario: Max sessions enforcement
  Given MAX_SESSIONS_PER_USER=3
  And user "alice" has 3 active sessions
  When "alice" logs in from a new device
  Then the oldest session should be terminated
  And the new session should be created
  And the user should be notified of session displacement

Scenario: Session listing
  Given user "alice" has multiple sessions
  When "alice" views her active sessions in the UI
  Then she should see all active sessions
  And each session should show: device info, location, last activity

Technical Requirements:

  • Track sessions by user with metadata
  • Implement LRU eviction when limit exceeded
  • Add session listing endpoint
  • Add self-service session revocation
US-3: Security - Bind Sessions to Client

As a security engineer
I want sessions optionally bound to client attributes
So that session hijacking is detectable

Acceptance Criteria:

Scenario: IP binding enabled
  Given SESSION_BIND_TO_IP=true
  And session was created from IP 192.168.1.100
  When a request comes from IP 10.0.0.50
  Then the session should be invalidated
  And a security event should be logged

Scenario: User-agent binding enabled
  Given SESSION_BIND_TO_USER_AGENT=true
  And session was created with Chrome/120
  When a request comes with Firefox/130
  Then the session should be invalidated
  And a security event should be logged

Scenario: Bindings disabled
  Given SESSION_BIND_TO_IP=false
  And SESSION_BIND_TO_USER_AGENT=false
  When a request comes from different IP/browser
  Then the session should remain valid

Technical Requirements:

  • Store client IP and user-agent at session creation
  • Validate on each request if binding enabled
  • Log security events on binding violations
  • Support selective binding (IP only, UA only, both)
US-4: Admin - Manage User Sessions

As an administrator
I want to view and terminate user sessions
So that I can respond to security incidents

Acceptance Criteria:

Scenario: View all sessions
  Given I am logged in as an admin
  When I navigate to "Session Management"
  Then I should see all active sessions
  And each session should show: user, IP, user-agent, created, last activity

Scenario: Terminate specific session
  Given I am viewing user sessions
  When I click "Terminate" on a specific session
  Then that session should be invalidated immediately
  And the user should be logged out

Scenario: Terminate all user sessions
  Given I am viewing sessions for user "alice"
  When I click "Terminate All Sessions"
  Then all of Alice's sessions should be invalidated
  And Alice should need to re-authenticate

Technical Requirements:

  • Add /admin/sessions endpoint
  • Add session termination API
  • Add session listing to Admin UI
  • Support filtering and searching sessions

🏗 Architecture

Session Lifecycle

stateDiagram-v2
    [*] --> Created: Login
    Created --> Active: First request
    Active --> Active: Request (resets idle)
    Active --> IdleExpired: Idle timeout
    Active --> AbsoluteExpired: Absolute timeout
    Active --> Terminated: Admin/user revoke
    Active --> Displaced: Max sessions exceeded
    IdleExpired --> [*]
    AbsoluteExpired --> [*]
    Terminated --> [*]
    Displaced --> [*]
Loading

Session Data Model

classDiagram
    class EnhancedSession {
        +session_id: str
        +user_id: str
        +user_email: str
        +created_at: datetime
        +last_activity: datetime
        +ip_address: str
        +user_agent: str
        +device_info: dict
        +is_valid() bool
        +touch() void
        +terminate() void
    }

    class SessionRegistry {
        +sessions: Dict
        +max_per_user: int
        +idle_timeout: int
        +absolute_timeout: int
        +add_session()
        +get_session()
        +list_user_sessions()
        +terminate_session()
        +enforce_limits()
    }

    SessionRegistry "1" --> "*" EnhancedSession
Loading

Request Validation Flow

flowchart TD
    A[Authenticated Request] --> B{Session Exists?}
    B -->|No| C[401 Unauthorized]
    B -->|Yes| D{Absolute Timeout?}
    D -->|Yes| E[Invalidate + 401]
    D -->|No| F{Idle Timeout?}
    F -->|Yes| E
    F -->|No| G{IP Binding Check}
    G -->|Fail| H[Log + Invalidate]
    G -->|Pass| I{UA Binding Check}
    I -->|Fail| H
    I -->|Pass| J[Update last_activity]
    J --> K[Process Request]
Loading

📋 Implementation Tasks

Phase 1: Session Data Model Enhancement

  • Add created_at, last_activity to session records
  • Add ip_address, user_agent fields
  • Create EnhancedSession class
  • Update session storage schema

Phase 2: Timeout Implementation

  • Add SESSION_IDLE_TIMEOUT_MINUTES config
  • Add SESSION_ABSOLUTE_TIMEOUT_MINUTES config
  • Implement timeout checking in middleware
  • Add session cleanup for expired sessions

Phase 3: Session Binding

  • Add SESSION_BIND_TO_IP config
  • Add SESSION_BIND_TO_USER_AGENT config
  • Implement binding validation
  • Add security event logging for violations

Phase 4: Concurrent Session Limits

  • Add MAX_SESSIONS_PER_USER config
  • Implement LRU eviction strategy
  • Add notification for displaced sessions
  • Track sessions by user

Phase 5: Admin Session Management

  • Add /admin/sessions listing endpoint
  • Add /admin/sessions/{id}/terminate endpoint
  • Add /admin/users/{id}/sessions endpoint
  • Create Session Management UI section

Phase 6: User Self-Service

  • Add /me/sessions endpoint
  • Add /me/sessions/{id}/terminate endpoint
  • Add "Active Sessions" to user profile UI

Phase 7: Audit Logging

  • Log session creation events
  • Log session termination events
  • Log binding violation events
  • Log timeout events

⚙️ Configuration Example

# Session Timeout Settings
SESSION_IDLE_TIMEOUT_MINUTES=30          # Idle timeout (0 = disabled)
SESSION_ABSOLUTE_TIMEOUT_MINUTES=480     # 8 hours absolute timeout

# Concurrent Session Limits
MAX_SESSIONS_PER_USER=5                  # Max concurrent sessions (0 = unlimited)

# Session Binding
SESSION_BIND_TO_IP=false                 # Bind session to client IP
SESSION_BIND_TO_USER_AGENT=false         # Bind session to user-agent

# Token Rotation
SESSION_ROTATION_ENABLED=true            # Rotate session ID on re-auth
SESSION_TRACKING_ENABLED=true            # Track session metadata

✅ Success Criteria

  • Sessions expire after idle timeout
  • Sessions expire after absolute timeout
  • Max sessions per user enforced with LRU eviction
  • IP binding works when enabled
  • User-agent binding works when enabled
  • Admins can view and terminate sessions
  • Users can view and terminate their own sessions
  • Session events logged to audit trail
  • No performance regression in session checks

🏁 Definition of Done

  • Session timeout implemented and tested
  • Concurrent session limits working
  • Session binding options implemented
  • Admin session management UI created
  • User self-service session management added
  • Audit logging for session events
  • Unit tests with >90% coverage
  • Integration tests pass
  • Code passes make verify
  • Configuration documented in .env.example
  • User documentation updated

📝 Additional Notes

Performance Considerations

Operation Expected Latency
Session validation < 1ms (in-memory cache)
Redis lookup < 5ms
Timeout check < 0.1ms
Binding check < 0.1ms

Security References


🔗 Related Issues

Metadata

Metadata

Labels

MUSTP1: Non-negotiable, critical requirements without which the product is non-functional or unsafeenhancementNew feature or requestfrontendFrontend development (HTML, CSS, JavaScript)pythonPython / backend development (FastAPI)readyValidated, ready-to-work-on itemssecurityImproves security

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions