-
Notifications
You must be signed in to change notification settings - Fork 613
[FEATURE][SECURITY]: Enhanced session management for admin UI #541
Description
[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?
- Enterprise Security Requirements: SOC2, HIPAA require session timeout and monitoring
- Concurrent Session Control: Organizations need to limit sessions per user
- Session Hijacking Protection: Binding sessions to IP/user-agent reduces risk
- Admin Oversight: Administrators need visibility into active sessions
- 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 validTechnical Requirements:
- Add
last_activitytimestamp to sessions - Add
created_attimestamp 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 activityTechnical 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 validTechnical 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-authenticateTechnical Requirements:
- Add
/admin/sessionsendpoint - 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 --> [*]
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
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]
📋 Implementation Tasks
Phase 1: Session Data Model Enhancement
- Add
created_at,last_activityto session records - Add
ip_address,user_agentfields - Create
EnhancedSessionclass - Update session storage schema
Phase 2: Timeout Implementation
- Add
SESSION_IDLE_TIMEOUT_MINUTESconfig - Add
SESSION_ABSOLUTE_TIMEOUT_MINUTESconfig - Implement timeout checking in middleware
- Add session cleanup for expired sessions
Phase 3: Session Binding
- Add
SESSION_BIND_TO_IPconfig - Add
SESSION_BIND_TO_USER_AGENTconfig - Implement binding validation
- Add security event logging for violations
Phase 4: Concurrent Session Limits
- Add
MAX_SESSIONS_PER_USERconfig - Implement LRU eviction strategy
- Add notification for displaced sessions
- Track sessions by user
Phase 5: Admin Session Management
- Add
/admin/sessionslisting endpoint - Add
/admin/sessions/{id}/terminateendpoint - Add
/admin/users/{id}/sessionsendpoint - Create Session Management UI section
Phase 6: User Self-Service
- Add
/me/sessionsendpoint - Add
/me/sessions/{id}/terminateendpoint - 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
- Related: [FEATURE][SECURITY]: CSRF token protection system #543 (CSRF Protection)
- Related: [FEATURE][SECURITY]: Audit logging system #535 (Audit Logging)
- Existing:
mcpgateway/cache/session_registry.py - Existing:
mcpgateway/db.py:SessionRecord