You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Implement comprehensive CSRF (Cross-Site Request Forgery) protection for all state-changing operations in MCP Gateway. This includes double-submit cookie pattern, per-session tokens, SameSite cookies, and automatic token validation for forms and API requests.
Why Now?
Security Compliance: OWASP Top 10 requires CSRF protection for authenticated applications
Enterprise Requirements: SOC2, HIPAA, and other compliance frameworks mandate CSRF protection
As a security engineer I want all POST/PUT/DELETE requests to require CSRF tokens So that attackers cannot forge requests from authenticated users
Acceptance Criteria:
Scenario: CSRF token required for mutationsGiven I am authenticated as an admin
When I submit a POST request without CSRF token
Then the request should be rejected with 403 Forbidden
And the response should indicate "CSRF token missing"Scenario: Valid CSRF token allows requestGiven I am authenticated as an admin
And I have obtained a CSRF token
When I submit a POST request with valid CSRF token in header
Then the request should be processed normally
Scenario: Safe methods exemptGiven I am authenticated as an admin
When I submit a GET request without CSRF token
Then the request should succeed
And no CSRF validation should occur
Technical Requirements:
Validate CSRF token on POST, PUT, DELETE, PATCH methods
Skip validation for GET, HEAD, OPTIONS, TRACE
Return 403 with clear error message on failure
US-2: Frontend - Automatic CSRF Token Handling
As a frontend developer I want CSRF tokens automatically included in requests So that I don't need to manually manage tokens
Acceptance Criteria:
Scenario: Token in cookie readable by JavaScriptGiven I log into the Admin UI
Then a CSRF token cookie should be set
And the cookie should be accessible to JavaScript (httponly=false)
Scenario: Automatic token inclusionGiven I have a valid CSRF token in cookie
When I use fetch() to make a POST request
Then the X-CSRF-Token header should be automatically included
Scenario: Token refresh on expirationGiven my CSRF token has expired
When I make a POST request
Then a new token should be fetched automatically
And the request should be retried with the new token
Technical Requirements:
Set CSRF cookie with httponly=false for JS access
Provide fetchWithCSRF() wrapper function
Handle 403 errors with automatic token refresh and retry
US-3: Admin - Configure CSRF Protection
As a platform administrator I want to configure CSRF protection behavior So that I can tune it for my deployment
Acceptance Criteria:
Scenario: Disable CSRF for developmentGiven CSRF_ENABLED=false
When I make a POST request without CSRF token
Then the request should succeed
Scenario: Configure token expiryGiven CSRF_TOKEN_EXPIRY=7200
When a CSRF token is generated
Then it should be valid for 2 hours (7200 seconds)
Scenario: Add trusted originsGiven CSRF_TRUSTED_ORIGINS=https://app.example.com
When a request comes from https://app.example.com
And the referer header matches the trusted origin
Then CSRF validation should pass
Technical Requirements:
CSRF_ENABLED toggle (default: true in production)
CSRF_TOKEN_EXPIRY in seconds (default: 3600)
CSRF_TRUSTED_ORIGINS for cross-origin deployments
CSRF_EXEMPT_PATHS for public endpoints
US-4: Security - Token Binding and Rotation
As a security engineer I want CSRF tokens bound to user sessions and rotated regularly So that stolen tokens have limited usefulness
Acceptance Criteria:
Scenario: Token bound to sessionGiven user Alice has CSRF token "token-A"When user Bob tries to use "token-A"Then the request should be rejected
Because the token is bound to Alice's session
Scenario: Token rotation on loginGiven CSRF_ROTATE_ON_LOGIN=true
When a user logs in
Then a new CSRF token should be generated
And the old token should be invalidated
Scenario: Token rotation on errorGiven CSRF_ROTATE_ON_ERROR=true
When a request returns 4xx or 5xx error
Then the CSRF token should be rotated
And a new token should be set in the response
Technical Requirements:
Bind token to user_id and session_id
Rotate tokens on login
Optional rotation on errors
Use HMAC for token integrity
🏗 Architecture
CSRF Validation Flow
sequenceDiagram
participant Client
participant Middleware as CSRF Middleware
participant Service
participant DB
Client->>Middleware: POST /admin/gateways
Middleware->>Middleware: Check method (POST = requires CSRF)
Middleware->>Middleware: Extract token from header/cookie
alt Token Missing
Middleware-->>Client: 403 "CSRF token missing"
else Token Invalid
Middleware-->>Client: 403 "Invalid CSRF token"
else Token Valid
Middleware->>Service: Process request
Service->>DB: Execute operation
Service-->>Middleware: Response
Middleware-->>Client: Success + new token
end
Loading
Double-Submit Cookie Pattern
flowchart TD
A[Login] --> B[Generate CSRF Token]
B --> C[Set Cookie: csrf_token=xxx]
B --> D[Return Token in Response]
E[Subsequent Request] --> F{Method Safe?}
F -->|GET/HEAD| G[Skip Validation]
F -->|POST/PUT/DELETE| H[Extract Token]
H --> I[From Header: X-CSRF-Token]
H --> J[From Cookie: csrf_token]
I --> K{Tokens Match?}
J --> K
K -->|Yes| L[Process Request]
K -->|No| M[403 Forbidden]
[FEATURE][SECURITY]: CSRF Token Protection System
Goal
Implement comprehensive CSRF (Cross-Site Request Forgery) protection for all state-changing operations in MCP Gateway. This includes double-submit cookie pattern, per-session tokens, SameSite cookies, and automatic token validation for forms and API requests.
Why Now?
📖 User Stories
US-1: Security - Protect State-Changing Operations
As a security engineer
I want all POST/PUT/DELETE requests to require CSRF tokens
So that attackers cannot forge requests from authenticated users
Acceptance Criteria:
Technical Requirements:
US-2: Frontend - Automatic CSRF Token Handling
As a frontend developer
I want CSRF tokens automatically included in requests
So that I don't need to manually manage tokens
Acceptance Criteria:
Technical Requirements:
httponly=falsefor JS accessfetchWithCSRF()wrapper functionUS-3: Admin - Configure CSRF Protection
As a platform administrator
I want to configure CSRF protection behavior
So that I can tune it for my deployment
Acceptance Criteria:
Technical Requirements:
CSRF_ENABLEDtoggle (default: true in production)CSRF_TOKEN_EXPIRYin seconds (default: 3600)CSRF_TRUSTED_ORIGINSfor cross-origin deploymentsCSRF_EXEMPT_PATHSfor public endpointsUS-4: Security - Token Binding and Rotation
As a security engineer
I want CSRF tokens bound to user sessions and rotated regularly
So that stolen tokens have limited usefulness
Acceptance Criteria:
Technical Requirements:
🏗 Architecture
CSRF Validation Flow
sequenceDiagram participant Client participant Middleware as CSRF Middleware participant Service participant DB Client->>Middleware: POST /admin/gateways Middleware->>Middleware: Check method (POST = requires CSRF) Middleware->>Middleware: Extract token from header/cookie alt Token Missing Middleware-->>Client: 403 "CSRF token missing" else Token Invalid Middleware-->>Client: 403 "Invalid CSRF token" else Token Valid Middleware->>Service: Process request Service->>DB: Execute operation Service-->>Middleware: Response Middleware-->>Client: Success + new token endDouble-Submit Cookie Pattern
flowchart TD A[Login] --> B[Generate CSRF Token] B --> C[Set Cookie: csrf_token=xxx] B --> D[Return Token in Response] E[Subsequent Request] --> F{Method Safe?} F -->|GET/HEAD| G[Skip Validation] F -->|POST/PUT/DELETE| H[Extract Token] H --> I[From Header: X-CSRF-Token] H --> J[From Cookie: csrf_token] I --> K{Tokens Match?} J --> K K -->|Yes| L[Process Request] K -->|No| M[403 Forbidden]📋 Implementation Tasks
Phase 1: CSRF Service
mcpgateway/services/csrf_service.pyPhase 2: CSRF Middleware
mcpgateway/middleware/csrf_middleware.pyPhase 3: Configuration
config.py.env.examplePhase 4: Frontend Integration
getCSRFToken()function toadmin.jsfetchWithCSRF()wrapperPhase 5: Authentication Integration
/auth/csrf-tokenendpoint for token refreshPhase 6: Testing
⚙️ Configuration Example
✅ Success Criteria
🏁 Definition of Done
.env.examplemake verify📝 Additional Notes
Security Benefits
Migration Guide
CSRF_ENABLED=truefetchWithCSRF()wrapper🔗 Related Issues