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!: response cookie extraction #3045

Open
wants to merge 2 commits into
base: v3.0
Choose a base branch
from
Open
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
17 changes: 10 additions & 7 deletions litestar/data_extractors.py
Original file line number Diff line number Diff line change
Expand Up @@ -318,7 +318,7 @@ class ExtractedResponseData(TypedDict, total=False):
body: bytes
status_code: int
headers: dict[str, str]
cookies: dict[str, str]
cookies: list[dict[str, str]]


class ResponseDataExtractor:
Expand Down Expand Up @@ -424,7 +424,7 @@ def extract_headers(self, messages: tuple[HTTPResponseStartEvent, HTTPResponseBo
else headers
)

def extract_cookies(self, messages: tuple[HTTPResponseStartEvent, HTTPResponseBodyEvent]) -> dict[str, str]:
def extract_cookies(self, messages: tuple[HTTPResponseStartEvent, HTTPResponseBodyEvent]) -> list[dict[str, str]]:
"""Extract cookies from a ``Message``

Args:
Expand All @@ -435,9 +435,12 @@ def extract_cookies(self, messages: tuple[HTTPResponseStartEvent, HTTPResponseBo
Returns:
The Response's cookies dict.
"""
if cookie_string := ";".join(
[x[1].decode("latin-1") for x in filter(lambda x: x[0].lower() == b"set-cookie", messages[0]["headers"])]
cookies: list[dict[str, str]] = []
for cookie_string in (
x[1].decode("latin-1") for x in filter(lambda x: x[0].lower() == b"set-cookie", messages[0]["headers"])
):
parsed_cookies = parse_cookie_string(cookie_string)
return _obfuscate(parsed_cookies, self.obfuscate_cookies) if self.obfuscate_cookies else parsed_cookies
return {}
parsed_cookie = parse_cookie_string(cookie_string)
if self.obfuscate_cookies:
parsed_cookie = _obfuscate(parsed_cookie, self.obfuscate_cookies)
cookies.append(parsed_cookie)
return cookies
7 changes: 5 additions & 2 deletions tests/unit/test_data_extractors.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ def test_request_extraction_cookie_obfuscation(req: Request[Any, Any, Any], key:

async def test_response_data_extractor() -> None:
headers = {"common": "abc", "special": "123", "content-type": "application/json"}
cookies = [Cookie(key="regular"), Cookie(key="auth")]
cookies = [Cookie(key="regular"), Cookie(key="auth", path="/auth", httponly=True, samesite="strict")]
response = ASGIResponse(body=b'{"hello":"world"}', cookies=cookies, headers=headers)
extractor = ResponseDataExtractor()
messages: List[Any] = []
Expand All @@ -109,7 +109,10 @@ async def send(message: "Any") -> None:
assert extracted_data.get("status_code") == HTTP_200_OK
assert extracted_data.get("body") == b'{"hello":"world"}'
assert extracted_data.get("headers") == {**headers, "content-length": "17"}
assert extracted_data.get("cookies") == {"Path": "/", "SameSite": "lax", "auth": "", "regular": ""}
assert extracted_data.get("cookies") == [
{"Path": "/", "SameSite": "lax", "regular": ""},
{"Path": "/auth", "SameSite": "strict", "auth": "", "": "HttpOnly"},
]


async def test_request_data_extractor_skip_keys() -> None:
Expand Down
5 changes: 4 additions & 1 deletion tests/unit/test_middleware/test_logging_middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,10 @@ def test_logging_middleware_struct_logger(handler: HTTPRouteHandler) -> None:
}
assert cap_logs[1] == {
"status_code": 200,
"cookies": {"first-cookie": "abc", "Path": "/", "SameSite": "lax", "second-cookie": "xxx"},
"cookies": [
{"first-cookie": "abc", "Path": "/", "SameSite": "lax"},
{"second-cookie": "xxx", "Path": "/", "SameSite": "lax"},
],
"headers": {"token": "123", "regular": "abc", "content-length": "17", "content-type": "application/json"},
"body": '{"hello":"world"}',
"event": "HTTP Response",
Expand Down
Loading