-
Notifications
You must be signed in to change notification settings - Fork 0
feat(admin): add CSRF protection to mutation endpoints #83
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 2 commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
63a9997
feat(admin): add CSRF protection to mutation endpoints
x3ek 8e2d042
feat(admin): add GET /admin/csrf for JSON callers, use CSRF_SESSION_K…
x3ek 67dbf3d
refactor(auth): make CSRF dep resolve after auth so 401 fires before 403
x3ek 9e4b8e5
refactor(deps): consolidate is_htmx + fix stale test patch targets
x3ek 3ddad10
refactor(csrf): self-review pass — integration tests, generic error, …
x3ek cc403fc
feat(csrf): log rejection reason + rotation event for operability
x3ek File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,64 @@ | ||
| """CSRF token generation and verification for admin mutation endpoints. | ||
|
|
||
| Tokens are stored in the signed session cookie under ``SESSION_KEY`` and | ||
| validated on POST/PUT/DELETE requests via the ``verify_csrf_token`` dependency. | ||
| Clients send the token in the ``X-CSRF-Token`` header (HTMX, JSON API) or a | ||
| ``csrf_token`` form field (plain form fallback). | ||
|
x3ek marked this conversation as resolved.
Outdated
|
||
| """ | ||
|
|
||
| import logging | ||
| import secrets | ||
|
|
||
| from fastapi import HTTPException, Request | ||
|
|
||
| from squishmark.config import get_settings | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
| SESSION_KEY = "csrf_token" | ||
| HEADER_NAME = "X-CSRF-Token" | ||
| FORM_FIELD = "csrf_token" | ||
|
|
||
|
|
||
| def get_or_create_csrf_token(request: Request) -> str: | ||
| """Return the session's CSRF token, minting a new one if absent.""" | ||
| token = request.session.get(SESSION_KEY) | ||
| if not token: | ||
| token = secrets.token_urlsafe(32) | ||
| request.session[SESSION_KEY] = token | ||
| return token | ||
|
|
||
|
|
||
| async def _extract_submitted_token(request: Request) -> str | None: | ||
| """Read the submitted CSRF token from header or form body.""" | ||
| header_token = request.headers.get(HEADER_NAME) | ||
| if header_token: | ||
| return header_token | ||
|
|
||
| content_type = request.headers.get("content-type", "") | ||
| if content_type.startswith(("application/x-www-form-urlencoded", "multipart/form-data")): | ||
| form = await request.form() | ||
| value = form.get(FORM_FIELD) | ||
| if isinstance(value, str): | ||
| return value | ||
| return None | ||
|
|
||
|
|
||
| async def verify_csrf_token(request: Request) -> None: | ||
| """FastAPI dependency that rejects requests missing or with an invalid CSRF token. | ||
|
|
||
| Skipped when ``debug`` and ``dev_skip_auth`` are both set, matching the | ||
| auth-bypass behavior in ``get_current_admin``. | ||
| """ | ||
| settings = get_settings() | ||
| if settings.debug and settings.dev_skip_auth: | ||
| logger.warning("CSRF bypassed - dev_skip_auth is enabled") | ||
| return | ||
|
|
||
| expected = request.session.get(SESSION_KEY) if hasattr(request, "session") else None | ||
| if not expected: | ||
| raise HTTPException(status_code=403, detail="CSRF token missing from session") | ||
|
|
||
| submitted = await _extract_submitted_token(request) | ||
| if not submitted or not secrets.compare_digest(submitted, expected): | ||
| raise HTTPException(status_code=403, detail="CSRF token invalid") | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,156 @@ | ||
| """Tests for CSRF token generation and verification.""" | ||
|
|
||
| from unittest.mock import AsyncMock, MagicMock, patch | ||
|
|
||
| import pytest | ||
| from fastapi import HTTPException | ||
|
|
||
| from squishmark.services.csrf import ( | ||
| FORM_FIELD, | ||
| HEADER_NAME, | ||
| SESSION_KEY, | ||
| get_or_create_csrf_token, | ||
| verify_csrf_token, | ||
| ) | ||
|
|
||
|
|
||
| def _request( | ||
| *, | ||
| session: dict | None = None, | ||
| header_token: str | None = None, | ||
| form_body: dict | None = None, | ||
| content_type: str = "application/json", | ||
| ) -> MagicMock: | ||
| """Build a mock Request with a session dict and optional token sources.""" | ||
| request = MagicMock() | ||
| request.session = session if session is not None else {} | ||
| headers = {"content-type": content_type} | ||
| if header_token is not None: | ||
| headers[HEADER_NAME] = header_token | ||
| request.headers = headers | ||
| request.form = AsyncMock(return_value=form_body or {}) | ||
| return request | ||
|
|
||
|
|
||
| def test_get_or_create_csrf_token_mints_when_absent(): | ||
| request = _request() | ||
| token = get_or_create_csrf_token(request) | ||
|
|
||
| assert token | ||
| assert len(token) > 20 | ||
| assert request.session[SESSION_KEY] == token | ||
|
|
||
|
|
||
| def test_get_or_create_csrf_token_returns_existing(): | ||
| request = _request(session={SESSION_KEY: "preexisting-token"}) | ||
|
|
||
| token = get_or_create_csrf_token(request) | ||
|
|
||
| assert token == "preexisting-token" | ||
|
|
||
|
|
||
| def test_get_or_create_csrf_token_is_idempotent(): | ||
| """Calling twice on the same request returns the same token.""" | ||
| request = _request() | ||
|
|
||
| first = get_or_create_csrf_token(request) | ||
| second = get_or_create_csrf_token(request) | ||
|
|
||
| assert first == second | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_verify_csrf_token_accepts_matching_header(): | ||
| request = _request( | ||
| session={SESSION_KEY: "good-token"}, | ||
| header_token="good-token", | ||
| ) | ||
| with patch("squishmark.services.csrf.get_settings") as mock_settings: | ||
| mock_settings.return_value = MagicMock(debug=False, dev_skip_auth=False) | ||
| await verify_csrf_token(request) # should not raise | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_verify_csrf_token_rejects_missing_session_token(): | ||
| request = _request(session={}, header_token="anything") | ||
| with patch("squishmark.services.csrf.get_settings") as mock_settings: | ||
| mock_settings.return_value = MagicMock(debug=False, dev_skip_auth=False) | ||
| with pytest.raises(HTTPException) as exc: | ||
| await verify_csrf_token(request) | ||
|
|
||
| assert exc.value.status_code == 403 | ||
| assert "missing" in str(exc.value.detail).lower() | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_verify_csrf_token_rejects_missing_submitted_token(): | ||
| request = _request(session={SESSION_KEY: "good-token"}) # no header, no form | ||
| with patch("squishmark.services.csrf.get_settings") as mock_settings: | ||
| mock_settings.return_value = MagicMock(debug=False, dev_skip_auth=False) | ||
| with pytest.raises(HTTPException) as exc: | ||
| await verify_csrf_token(request) | ||
|
|
||
| assert exc.value.status_code == 403 | ||
| assert "invalid" in str(exc.value.detail).lower() | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_verify_csrf_token_rejects_wrong_header(): | ||
| request = _request( | ||
| session={SESSION_KEY: "good-token"}, | ||
| header_token="wrong-token", | ||
| ) | ||
| with patch("squishmark.services.csrf.get_settings") as mock_settings: | ||
| mock_settings.return_value = MagicMock(debug=False, dev_skip_auth=False) | ||
| with pytest.raises(HTTPException) as exc: | ||
| await verify_csrf_token(request) | ||
|
|
||
| assert exc.value.status_code == 403 | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_verify_csrf_token_accepts_form_field_fallback(): | ||
| """For form submissions without the header, the csrf_token form field is honored.""" | ||
| request = _request( | ||
| session={SESSION_KEY: "good-token"}, | ||
| form_body={FORM_FIELD: "good-token"}, | ||
| content_type="application/x-www-form-urlencoded", | ||
| ) | ||
| with patch("squishmark.services.csrf.get_settings") as mock_settings: | ||
| mock_settings.return_value = MagicMock(debug=False, dev_skip_auth=False) | ||
| await verify_csrf_token(request) # should not raise | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_verify_csrf_token_header_takes_precedence_over_form(): | ||
| """A valid header passes even if the form field is wrong.""" | ||
| request = _request( | ||
| session={SESSION_KEY: "good-token"}, | ||
| header_token="good-token", | ||
| form_body={FORM_FIELD: "wrong"}, | ||
| content_type="application/x-www-form-urlencoded", | ||
| ) | ||
| with patch("squishmark.services.csrf.get_settings") as mock_settings: | ||
| mock_settings.return_value = MagicMock(debug=False, dev_skip_auth=False) | ||
| await verify_csrf_token(request) # header wins, no raise | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_verify_csrf_token_bypassed_in_dev_skip_auth(): | ||
| """When debug and dev_skip_auth are both set, CSRF check is skipped.""" | ||
| request = _request() # no session, no token — would normally fail | ||
| with patch("squishmark.services.csrf.get_settings") as mock_settings: | ||
| mock_settings.return_value = MagicMock(debug=True, dev_skip_auth=True) | ||
| await verify_csrf_token(request) # should not raise | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_verify_csrf_token_not_bypassed_in_prod_mode(): | ||
| """dev_skip_auth without debug doesn't bypass.""" | ||
| request = _request() | ||
| with patch("squishmark.services.csrf.get_settings") as mock_settings: | ||
| mock_settings.return_value = MagicMock(debug=False, dev_skip_auth=True) | ||
| with pytest.raises(HTTPException) as exc: | ||
| await verify_csrf_token(request) | ||
|
|
||
| assert exc.value.status_code == 403 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.