Skip to content
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

fix: httponly correction in CSRFMiddleware #3739

Merged
merged 2 commits into from
Sep 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions litestar/middleware/csrf.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,9 @@ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
form = await request.form()
existing_csrf_token = form.get("_csrf_token", None)

if not existing_csrf_token and self.config.cookie_httponly:
existing_csrf_token = csrf_cookie

connection_state = ScopeState.from_scope(scope)
if request.method in self.config.safe_methods:
token = connection_state.csrf_token = csrf_cookie or generate_csrf_token(secret=self.config.secret)
Expand Down
15 changes: 15 additions & 0 deletions tests/unit/test_middleware/test_csrf_middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,21 @@ def test_csrf_successful_flow(get_handler: HTTPRouteHandler, post_handler: HTTPR
assert response.status_code == HTTP_201_CREATED


def test_csrf_httponly_flow(get_handler: HTTPRouteHandler, post_handler: HTTPRouteHandler) -> None:
with create_test_client(
route_handlers=[get_handler, post_handler], csrf_config=CSRFConfig(secret="secret", cookie_httponly=True)
) as client:
response = client.get("/")
assert response.status_code == HTTP_200_OK

csrf_token: Optional[str] = response.cookies.get("csrftoken")
assert csrf_token is not None
assert "set-cookie" in response.headers
if csrf_token:
response = client.post("/")
assert response.status_code == HTTP_201_CREATED


@pytest.mark.parametrize(
"method",
["POST", "PUT", "DELETE", "PATCH"],
Expand Down
Loading