feat(security): add CSRF header constants and security-headers endpoint

Move X-BanGUI-Request header name/value to backend/app/utils/constants.py as single source of truth. Add GET /api/v1/config/security-headers endpoint. Update csrf middleware, frontend api client, and docs to use shared constants.
This commit is contained in:
2026-05-03 22:06:43 +02:00
parent cee3daffc1
commit dafe8d61e2
7 changed files with 109 additions and 11 deletions

View File

@@ -77,6 +77,37 @@ To verify headers are being sent correctly:
---
## CSRF Protection
BanGUI protects cookie-authenticated state-mutating requests (POST, PUT, DELETE, PATCH) with a custom header check. Requests using the session cookie must include the header `X-BanGUI-Request: 1`. Bearer token authentication is exempt since tokens in headers are not CSRF-vulnerable.
### Single Source of Truth
The header name and value are defined once in `backend/app/utils/constants.py` (`CSRF_HEADER_NAME` and `CSRF_HEADER_VALUE`) and consumed by:
- `backend/app/middleware/csrf.py` — validates the header on incoming requests
- `frontend/src/api/client.ts` — attaches the header to state-mutating fetch calls
- `frontend/src/utils/constants.ts` — mirrors the values for type-safe import
### Endpoint
**`GET /api/v1/config/security-headers`** — returns the CSRF header name and value to authenticated clients:
```json
{
"csrf_header_name": "X-BanGUI-Request",
"csrf_header_value": "1"
}
```
This allows the frontend to discover the required header at runtime. Both frontend and backend constants must remain in sync — a build-time check is recommended when updating either constant.
### Header Rationale
The custom header is required because browsers block cross-site requests from setting custom headers without a CORS preflight, which BanGUI rejects for non-allowed origins.
---
## Session Security
See `backend/app/middleware/csrf.py` and `backend/app/middleware/rate_limit.py` for CSRF protection and rate limiting.