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 sanic cookies headers serialization #2194

Merged
merged 3 commits into from
Jan 15, 2025
Merged
Show file tree
Hide file tree
Changes from 2 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
11 changes: 9 additions & 2 deletions elasticapm/contrib/sanic/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@

from sanic import Sanic
from sanic import __version__ as version
from sanic.cookies import CookieJar
from sanic.cookies import Cookie, CookieJar
from sanic.request import Request
from sanic.response import HTTPResponse

Expand Down Expand Up @@ -120,7 +120,14 @@ async def get_response_info(config: Config, response: HTTPResponse, event_type:
result["status_code"] = response.status

if config.capture_headers:
result["headers"] = dict(response.headers)

def normalize(v):
# we are getting entries for Set-Cookie headers as Cookie instances
if isinstance(v, Cookie):
return str(v)
return v

result["headers"] = {k: normalize(v) for k, v in response.headers.items()}

if config.capture_body in ("all", event_type) and "octet-stream" not in response.content_type:
result["body"] = response.body.decode("utf-8")
Expand Down
5 changes: 4 additions & 1 deletion tests/contrib/sanic/fixtures.py
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,10 @@ async def custom_headers(request):
@app.get("/add-cookies")
async def add_cookies(request):
response = json({"data": "message"}, headers={"sessionid": 1234555})
response.add_cookie("some", "cookie")
if hasattr(response, "add_cookie"):
response.add_cookie("some", "cookie")
else:
response.cookies["some"] = "cookie"
return response

try:
Expand Down
1 change: 1 addition & 0 deletions tests/contrib/sanic/sanic_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,7 @@ def test_cookies_normalization(sanic_elastic_app, elasticapm_client):
_, resp = sanic_app.test_client.get(
"/add-cookies",
)
assert resp.status_code == 200
assert len(apm._client.events[constants.TRANSACTION]) == 1
transaction = apm._client.events[constants.TRANSACTION][0]
assert transaction["context"]["response"]["cookies"] == {"some": {"value": "cookie", "path": "/"}}
Expand Down
Loading