Skip to content

fix(security): Implement X-Force Red session token security fixes (ICACF-22)#4406

Draft
MohanLaksh wants to merge 3 commits intomainfrom
fix/icacf-22-session-token-security
Draft

fix(security): Implement X-Force Red session token security fixes (ICACF-22)#4406
MohanLaksh wants to merge 3 commits intomainfrom
fix/icacf-22-session-token-security

Conversation

@MohanLaksh
Copy link
Copy Markdown
Collaborator

Problem Statement

X-Force Red penetration testing identified critical session token vulnerabilities (ICACF-22):

  1. Token Replay Attacks: Session tokens remained valid after logout, allowing attackers to reuse stolen tokens
  2. Excessive Token Lifetime: 7-day session token expiry increased attack surface for token theft
  3. No Server-Side Revocation: Logout only cleared client-side cookies, tokens remained valid server-side

Security Impact: An attacker who steals a session token (via XSS, network sniffing, etc.) can continue using it even after the user logs out, potentially for up to 7 days.

Solution Overview

This PR implements comprehensive server-side token revocation and reduces session token lifetime per X-Force Red recommendations:

1. Reduced Token Lifetime (15 minutes)

  • Changed TOKEN_EXPIRY from 10080 minutes (7 days) to 15 minutes for session tokens
  • Added security warnings for excessive token expiry values (>20 min, >24 hours)
  • Distinguished session tokens (short-lived, interactive) from API tokens (long-lived, automation)

2. Server-Side Token Revocation

  • New POST /auth/logout endpoint that revokes session tokens server-side
  • TokenRevocation database table tracks revoked tokens with audit trail (jti, revoked_by, revoked_at, reason)
  • Auth middleware checks revocation status and rejects revoked tokens with 401 Unauthorized
  • Redis-cached revocation for performance optimization
  • Idempotent logout operations (DoS prevention)

3. Admin UI Logout Enhancement

  • Admin UI logout now calls server-side revocation before clearing cookies
  • Best-effort revocation (doesn't block logout on failure)

Technical Implementation

Files Modified

Core Implementation:

  • mcpgateway/config.py - Token expiry configuration and security warnings
  • mcpgateway/routers/auth.py - New logout endpoint with revocation logic
  • mcpgateway/admin.py - Admin UI logout with server-side revocation
  • .env.example - Updated TOKEN_EXPIRY documentation with migration guidance

Configuration:

  • pyproject.toml - Added security pytest marker registration
  • CHANGELOG.md - Breaking changes documentation with migration examples

Database:

  • Reuses existing TokenRevocation table (jti, revoked_by, revoked_at, reason)

Test Coverage (32 Tests Total)

Unit Tests (10) - tests/unit/mcpgateway/test_auth.py

  • Token lifetime validation (3 tests)
  • Token revocation enforcement (2 tests)
  • Logout endpoint functionality (3 tests)
  • Admin UI logout with revocation (2 tests)

Security Tests (15) - tests/security/test_session_token_security.py

  • Token lifetime security guidelines (4 tests)
  • Token revocation and audit trail (3 tests)
  • Logout endpoint security properties (4 tests)
  • Revocation persistence requirements (2 tests)
  • Token replay attack mitigation scenarios (3 tests)

Integration Tests (7) - tests/integration/test_auth_logout_flow.py

  • E2E login → logout → rejection flow (4 tests)
  • Database persistence verification (2 tests)
  • Token expiry enforcement (1 test)

Test Fixes (2)

  • tests/unit/mcpgateway/test_config.py - Updated warning assertion
  • tests/unit/mcpgateway/test_admin_module.py - Fixed logout test mocks

Security Properties Validated

✅ Revoked tokens rejected immediately (no replay attacks)
✅ Token expiry ≤20 minutes (X-Force Red guideline)
✅ Logout only accepts session tokens (not API tokens)
✅ Idempotent logout (DoS prevention)
✅ Complete audit trail (jti, revoked_by, revoked_at, reason)
✅ Database persistence (cache failures don't bypass revocation)
✅ Unauthenticated logout rejected (401 Unauthorized)

Breaking Changes

Session Token Lifetime Reduced: 7 days → 15 minutes

Migration Required for automation/long-running tasks:

Before (session tokens, now invalid after 15 min):

response = requests.post("https://gateway/auth/login", json={
    "email": "automation@example.com",
    "password": "SecurePassword123!"  # pragma: allowlist secret
})
token = response.json()["access_token"]  # Valid for 15 minutes only

After (use API tokens for automation):

response = requests.post("https://gateway/tokens", json={
    "name": "CI/CD Pipeline",
    "expires_in_days": 90
}, headers={"Authorization": f"Bearer {admin_session_token}"})
api_token = response.json()["token"]  # Valid for 90 days  # pragma: allowlist secret

See CHANGELOG.md for complete migration guide.

Verification

Quality Checks (All Passed)

✅ 17,881 tests passed (pytest)
✅ 0 linting issues (ruff)
✅ 10.00/10 rating (pylint)
✅ 0 security issues (bandit)
✅ 100% docstring coverage (interrogate)
✅ All doctests passed
✅ Code formatted (black, isort, autoflake)

Test Coverage

pytest tests/unit/mcpgateway/test_auth.py -v           # 10 unit tests
pytest tests/security/test_session_token_security.py -v  # 15 security tests
pytest tests/integration/test_auth_logout_flow.py -v    # 7 integration tests

Manual Testing

# 1. Login and get session token
curl -X POST http://localhost:4444/auth/login \
  -H "Content-Type: application/json" \
  -d '{"email": "test@example.com", "password": "password123"}'  # pragma: allowlist secret

# 2. Use token to access protected endpoint (should succeed)
curl http://localhost:4444/servers \
  -H "Authorization: Bearer <token>"

# 3. Logout (revoke token server-side)
curl -X POST http://localhost:4444/auth/logout \
  -H "Authorization: Bearer <token>"

# 4. Try to use token again (should fail with 401)
curl http://localhost:4444/servers \
  -H "Authorization: Bearer <token>"
# Expected: {"detail": "Token has been revoked"}

Security Audit Compliance

X-Force Red Findings Addressed:

Finding Status Implementation
Token replay after logout ✅ Fixed Server-side revocation with TokenRevocation table
Excessive token lifetime ✅ Fixed Reduced to 15 minutes (within 5-20 min guideline)
No token invalidation ✅ Fixed Auth middleware checks revocation status

Threat Model Coverage:

  • ✅ Token theft → user logout → attacker blocked (replay attack prevention)
  • ✅ Concurrent logout requests → idempotent operations (DoS prevention)
  • ✅ Cache poisoning → database fallback (cache bypass protection)
  • ✅ Long-lived tokens → reduced attack window (15 min vs 7 days)

Deployment Notes

Configuration Changes Required

# .env file
TOKEN_EXPIRY=15  # Changed from 10080 (7 days)

Database Migration

No new migrations required - reuses existing TokenRevocation table from schema.

Backward Compatibility

  • ✅ API tokens unaffected (still long-lived for automation)
  • ✅ Existing session tokens will expire naturally (no forced logout)
  • ⚠️ Users with 7-day session tokens will be logged out after 15 minutes on new deployments
  • ⚠️ Automation using session tokens must migrate to API tokens (see Breaking Changes)

Rollback Plan

# If issues arise, revert TOKEN_EXPIRY in .env:
TOKEN_EXPIRY=10080  # Restore 7-day expiry

# Existing revocation logic will continue to work but won't be triggered
# No database rollback needed

References

🚀 Ready for Review

…ACF-22)

Addresses X-Force Red penetration testing findings for session token
vulnerabilities. Implements comprehensive security improvements to prevent
token replay attacks after logout.

Changes:
- Reduce session token lifetime from 30 days to 15 minutes (configurable)
- Implement server-side token revocation with TokenRevocation table
- Add POST /auth/logout endpoint with immediate token blocklist
- Update admin UI logout to revoke tokens server-side
- Add security validation warnings for excessive token expiry values

Security improvements:
- Token replay attacks prevented via server-side revocation
- Revocation persists in database (source of truth)
- Redis-cached revocation for performance
- Complete audit trail (JTI, revoked_by, revoked_at, reason)
- Idempotent logout operations (DoS prevention)

Test coverage:
- 10 unit tests (token lifetime, revocation, logout endpoints)
- 15 security tests (threat modeling, attack scenarios)
- 7 integration tests (E2E login → logout → revocation flow)

Breaking changes:
- Session token expiry reduced from 10080 minutes (7 days) to 15 minutes
- Automation scripts using session tokens must migrate to API tokens

Migration guide included in CHANGELOG.md

Closes #4324

Signed-off-by: Mohan Lakshmaiah <mohan.economist@gmail.com>
Signed-off-by: Mohan Lakshmaiah <mohan.economist@gmail.com>
@MohanLaksh MohanLaksh force-pushed the fix/icacf-22-session-token-security branch from 9bd4650 to 851cf29 Compare April 23, 2026 11:03
@MohanLaksh MohanLaksh marked this pull request as draft April 27, 2026 04:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant