Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
46 commits
Select commit Hold shift + click to select a range
7541460
ref(integrations): route HTTP header filtering through data collectio…
ericapisani Jul 8, 2026
5e9f610
Merge branch 'master' into py-2584-update-wsgi-filter-headers
ericapisani Jul 9, 2026
a590c8e
Make changes to adjust to the data collection option being within the…
ericapisani Jul 9, 2026
16ed0c8
fix test
ericapisani Jul 9, 2026
486f0bc
make sure host header is not filtered when being added to the url
ericapisani Jul 9, 2026
7d14a81
add test coverage for edge case around host header being dropped but …
ericapisani Jul 9, 2026
bb98334
add aws lambda test coverage
ericapisani Jul 9, 2026
61d1618
fix(aws-lambda): Remove vendored deps from new embedded-sdk test fixt…
ericapisani Jul 9, 2026
951c408
add test coverage within the wsgi test file
ericapisani Jul 9, 2026
a19be39
feat(integrations): apply data_collection cookie filtering to wsgi, s…
ericapisani Jul 10, 2026
620e222
fix(integrations): omit cookies field when data_collection cookies mo…
ericapisani Jul 10, 2026
ec6f520
update tornado test
ericapisani Jul 10, 2026
4dd3ba6
ref(integrations): route HTTP header filtering through data collectio…
ericapisani Jul 8, 2026
d0bae90
Make changes to adjust to the data collection option being within the…
ericapisani Jul 9, 2026
a6c4688
fix test
ericapisani Jul 9, 2026
d7b378b
make sure host header is not filtered when being added to the url
ericapisani Jul 9, 2026
52c2da1
add test coverage for edge case around host header being dropped but …
ericapisani Jul 9, 2026
aa645d7
add aws lambda test coverage
ericapisani Jul 9, 2026
8b6e3ad
fix(aws-lambda): Remove vendored deps from new embedded-sdk test fixt…
ericapisani Jul 9, 2026
d717172
add test coverage within the wsgi test file
ericapisani Jul 9, 2026
c7f590f
Merge branch 'py-2584-update-wsgi-filter-headers' of github.com:getse…
ericapisani Jul 14, 2026
293a291
feat(integrations): apply data_collection cookie filtering to wsgi, s…
ericapisani Jul 10, 2026
530e83c
fix(integrations): omit cookies field when data_collection cookies mo…
ericapisani Jul 10, 2026
326d796
update tornado test
ericapisani Jul 10, 2026
e9f0e20
Merge branch 'master' into py-2584-update-wsgi-filter-headers
ericapisani Jul 15, 2026
48f7c7b
Merge branch 'py-2581-cookies' of github.com:getsentry/sentry-python …
ericapisani Jul 15, 2026
621d79b
Merge branch 'py-2584-update-wsgi-filter-headers' into py-2581-cookies
ericapisani Jul 15, 2026
3d7bddb
test(aiohttp): Expect single span in streaming passthrough test
ericapisani Jul 15, 2026
fad2292
Merge branch 'py-2584-update-wsgi-filter-headers' into py-2581-cookies
ericapisani Jul 15, 2026
40d9f38
feat(wsgi): Apply data_collection filtering to URL query strings
ericapisani Jul 15, 2026
e6e7148
Merge branch 'py-2581-cookies' into py-2583-query-parameters
ericapisani Jul 15, 2026
1f9bce7
lint
ericapisani Jul 15, 2026
fad0c9a
Do not encode what is added to event/span attributes in order to conf…
ericapisani Jul 16, 2026
21cf40b
feat(asgi): Apply data_collection filtering to URL query strings
ericapisani Jul 16, 2026
3f0bc2a
lint
ericapisani Jul 16, 2026
eee4ea2
feat(aiohttp): Apply data_collection filtering to URL query strings
ericapisani Jul 16, 2026
3b17dd3
feat(tornado): Apply data_collection filtering to URL query strings
ericapisani Jul 16, 2026
96e0ac0
test(tornado): Use literal [Filtered] in query param expectations
ericapisani Jul 16, 2026
c3baf08
feat(sanic): Apply data_collection filtering to URL query strings
ericapisani Jul 17, 2026
ea22fc5
feat(quart): Apply data_collection filtering to URL query strings
ericapisani Jul 17, 2026
14652a9
feat(gcp): Apply data_collection filtering to URL query strings
ericapisani Jul 17, 2026
57ef596
feat(aws): Apply data_collection filtering to URL query strings
ericapisani Jul 17, 2026
6918529
lint
ericapisani Jul 17, 2026
0f58e13
feat(asgi): Gate client IP/user info behind data_collection config
ericapisani Jul 17, 2026
8c9f43d
Add starlette tests, fix potential unbound error
ericapisani Jul 20, 2026
b308065
fix(tracing): Handle traces_sampler raising by falling back
ericapisani Jul 20, 2026
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
4 changes: 2 additions & 2 deletions sentry_sdk/_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,7 @@ class DataCollectionUserOptions(TypedDict, total=False):
cookies: "KeyValueCollectionBehaviour"
http_headers: "HttpHeadersCollectionUserOptions"
http_bodies: "List[str]"
query_params: "KeyValueCollectionBehaviour"
url_query_params: "KeyValueCollectionBehaviour"
graphql: "GraphQLCollectionUserOptions"
gen_ai: "GenAICollectionUserOptions"
database_query_data: bool
Expand All @@ -197,7 +197,7 @@ class DataCollection(TypedDict):
cookies: "KeyValueCollectionBehaviour"
http_headers: "HttpHeadersCollectionBehaviour"
http_bodies: "List[str]"
query_params: "KeyValueCollectionBehaviour"
url_query_params: "KeyValueCollectionBehaviour"
graphql: "GraphQLCollectionBehaviour"
gen_ai: "GenAICollectionBehaviour"
database_query_data: bool
Expand Down
94 changes: 86 additions & 8 deletions sentry_sdk/data_collection.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

``data_collection`` supersedes the single ``send_default_pii`` boolean with a
structured configuration that lets users enable or restrict automatically
collected data by category (user identity, cookies, HTTP headers, query params,
collected data by category (user identity, cookies, HTTP headers, URL query params,
HTTP bodies, generative AI inputs/outputs, stack frame variables, source
context).

Expand All @@ -23,10 +23,13 @@
"""

import warnings
from typing import TYPE_CHECKING, cast
from typing import TYPE_CHECKING, List, Mapping, Optional, Union, cast
from urllib.parse import parse_qs

from sentry_sdk._types import SENSITIVE_DATA_SUBSTITUTE

if TYPE_CHECKING:
from typing import Any, Dict, Literal
from typing import Any, Dict

from sentry_sdk._types import (
DataCollection,
Expand All @@ -48,7 +51,7 @@
# Default number of source lines captured above and below a stack frame.
_DEFAULT_FRAME_CONTEXT_LINES = 5

# Collection modes for key-value data (cookies, headers, query params).
# Collection modes for key-value data (cookies, headers, URL query params).
# snake_case (Python-only deviation from the spec's camelCase); never
# serialized to Sentry.
_VALID_KEY_VALUE_COLLECTION_BEHAVIOUR_MODES = ("off", "denylist", "allowlist")
Expand Down Expand Up @@ -77,6 +80,82 @@
]


def _is_sensitive_key(key: str, extra_terms: "Optional[List[str]]" = None) -> bool:
"""
Return whether ``key`` matches the sensitive denylist using a partial,
case-insensitive substring match.

:param extra_terms: additional deny terms (e.g. user-provided) to consider
alongside the built-in `_SENSITIVE_DENYLIST`.
"""
lowered = key.lower()
for term in _SENSITIVE_DENYLIST:
if term in lowered:
return True
if extra_terms:
for term in extra_terms:
if term and term.lower() in lowered:
return True
return False


def _apply_data_collection_filtering_to_query_string(
query_string: str,
behaviour: "KeyValueCollectionBehaviour",
) -> "Union[str, None]":
parsed_qs = parse_qs(query_string, keep_blank_values=True)
filtered_qs = _apply_key_value_collection_filtering(
items=parsed_qs, behaviour=behaviour
)

if filtered_qs:
parts = []
for key, value in filtered_qs.items():
values = value if isinstance(value, list) else [value]
for item in values:
parts.append(f"{key}={item}")
return "&".join(parts)

Check warning on line 117 in sentry_sdk/data_collection.py

View check run for this annotation

@sentry/warden / warden: code-review

Query string reconstruction does not URL-encode values, risking parameter injection

Use `urlencode(filtered_qs, doseq=True)` instead of manual `f"{key}={item}"` formatting so decoded `&`, `=`, and spaces are re-encoded and a single value cannot split into spurious parameters.

return None

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Query string rebuilt without encoding

Medium Severity

_apply_data_collection_filtering_to_query_string parses with parse_qs then rejoins as raw key=value pairs without quoting. Values containing reserved characters such as spaces, &, or = are corrupted, so filtered query_string / url.query attributes can be invalid or misleading.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit b308065. Configure here.



def _apply_key_value_collection_filtering(
items: "Mapping[str, Any]",
behaviour: "KeyValueCollectionBehaviour",
substitute: "Any" = SENSITIVE_DATA_SUBSTITUTE,
) -> "Dict[str, Any]":

if behaviour["mode"] == "off":
return {}

result: "Dict[str, Any]" = {}

if behaviour["mode"] == "allowlist":
for key, value in items.items():
is_allowed = False
if isinstance(key, str):
lowered = key.lower()
is_allowed = any(
term and term.lower() in lowered
for term in behaviour.get("terms", [])
)
if is_allowed and not _is_sensitive_key(key):
result[key] = value
else:
result[key] = substitute
return result

# denylist behaviour
for key, value in items.items():
if isinstance(key, str) and _is_sensitive_key(
key=key, extra_terms=behaviour.get("terms", [])
):
result[key] = substitute
else:
result[key] = value
return result


def _map_from_send_default_pii(
*,
send_default_pii: bool,
Expand All @@ -88,13 +167,12 @@
``send_default_pii`` collects today. Used when ``data_collection`` is not
provided explicitly.
"""
kv_mode: "Literal['denylist', 'off']" = "denylist" if send_default_pii else "off"
terms = [] if send_default_pii else ["forwarded", "-ip", "remote-", "via", "-user"]

return {
"provided_by_user": False,
"user_info": send_default_pii,
"cookies": {"mode": kv_mode, "terms": terms},
"cookies": {"mode": "denylist", "terms": terms},
# Headers are collected in both PII modes today (sensitive ones filtered
# when PII is off), so this never maps to "off".
"http_headers": {
Expand All @@ -103,7 +181,7 @@
# Bodies are collected regardless of PII today, bounded by
# ``max_request_body_size``.
"http_bodies": list(_ALL_HTTP_BODY_TYPES),
"query_params": {"mode": kv_mode, "terms": terms},
"url_query_params": {"mode": "denylist", "terms": terms},
"graphql": {"document": send_default_pii, "variables": send_default_pii},
"gen_ai": {"inputs": send_default_pii, "outputs": send_default_pii},
"database_query_data": send_default_pii,
Expand Down Expand Up @@ -153,7 +231,7 @@
"cookies": _kvcb_from_value(d.get("cookies") or {}),
"http_headers": _http_headers_from_value(d.get("http_headers") or {}),
"http_bodies": http_bodies,
"query_params": _kvcb_from_value(d.get("query_params") or {}),
"url_query_params": _kvcb_from_value(d.get("url_query_params") or {}),
"graphql": _graphql_from_value(d.get("graphql") or {}),
"gen_ai": _gen_ai_from_value(d.get("gen_ai") or {}),
"database_query_data": d.get("database_query_data", True),
Expand Down
88 changes: 75 additions & 13 deletions sentry_sdk/integrations/_asgi_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,11 @@
from enum import Enum
from typing import TYPE_CHECKING

import sentry_sdk
from sentry_sdk.data_collection import _apply_data_collection_filtering_to_query_string
from sentry_sdk.integrations._wsgi_common import _filter_headers
from sentry_sdk.scope import should_send_default_pii
from sentry_sdk.utils import has_data_collection_enabled

if TYPE_CHECKING:
from typing import Any, Dict, Optional, Union
Expand Down Expand Up @@ -75,7 +78,7 @@
return path


def _get_query(asgi_scope: "Any") -> "Any":
def _get_query(asgi_scope: "Any") -> "Optional[str]":
"""
Extract querystring from the ASGI scope, in the format that the Sentry protocol expects.
"""
Expand Down Expand Up @@ -112,13 +115,30 @@
"""
request_data: "Dict[str, Any]" = {}
ty = asgi_scope["type"]
client_options = sentry_sdk.get_client().options
if ty in ("http", "websocket"):
request_data["method"] = asgi_scope.get("method")

request_data["headers"] = headers = _filter_headers(
_get_headers(asgi_scope),
headers = _get_headers(asgi_scope)

request_data["headers"] = _filter_headers(
headers,
use_annotated_value=False,
)
request_data["query_string"] = _get_query(asgi_scope)

if has_data_collection_enabled(client_options):
qs = _get_query(asgi_scope)
if qs:
filtered_query_string = (
_apply_data_collection_filtering_to_query_string(
query_string=qs,
behaviour=client_options["data_collection"]["url_query_params"],
)
)
if filtered_query_string:
request_data["query_string"] = filtered_query_string
else:
request_data["query_string"] = _get_query(asgi_scope)

request_data["url"] = _get_url(
asgi_scope,
Expand All @@ -128,8 +148,12 @@
)

client = asgi_scope.get("client")
if client and should_send_default_pii():
request_data["env"] = {"REMOTE_ADDR": _get_ip(asgi_scope)}
if client:
if has_data_collection_enabled(client_options):
if client_options["data_collection"]["user_info"]:
request_data["env"] = {"REMOTE_ADDR": _get_ip(asgi_scope)}
elif should_send_default_pii():
request_data["env"] = {"REMOTE_ADDR": _get_ip(asgi_scope)}

return request_data

Expand All @@ -148,34 +172,72 @@
if asgi_scope.get("method"):
attributes["http.request.method"] = asgi_scope["method"].upper()

headers = _filter_headers(_get_headers(asgi_scope), use_annotated_value=False)
for header, value in headers.items():
headers = _get_headers(asgi_scope)

filtered_headers = _filter_headers(headers, use_annotated_value=False)
for header, value in filtered_headers.items():
attributes[f"http.request.header.{header.lower()}"] = value

if should_send_default_pii():
client_options = sentry_sdk.get_client().options
if has_data_collection_enabled(client_options):
filtered_query_string = None
query = _get_query(asgi_scope)

if query:
filtered_query_string = (
_apply_data_collection_filtering_to_query_string(
query_string=query,
behaviour=client_options["data_collection"]["url_query_params"],
)
)
if filtered_query_string:
attributes["http.query"] = filtered_query_string

path = _get_path(asgi_scope=asgi_scope, root_path_in_path=root_path_in_path)
attributes["url.path"] = path

url_without_query_string = _get_url(
asgi_scope,
"http" if ty == "http" else "ws",
headers.get("host"),
path=path,
)

attributes["url.full"] = (
f"{url_without_query_string}?{filtered_query_string}"
if filtered_query_string is not None
else url_without_query_string
)

elif should_send_default_pii():
query = _get_query(asgi_scope)
if query:
attributes["http.query"] = query

path = _get_path(asgi_scope=asgi_scope, root_path_in_path=root_path_in_path)
attributes["url.path"] = path

url_without_query_string = _get_url(
asgi_scope,
"http" if ty == "http" else "ws",
headers.get("host"),
path=path,
)
query_string = _get_query(asgi_scope)
attributes["url.full"] = (
f"{url_without_query_string}?{query_string}"
if query_string is not None

Check warning on line 229 in sentry_sdk/integrations/_asgi_common.py

View check run for this annotation

@sentry/warden / warden: code-review

client_options may cause NameError for non-http/websocket ASGI scopes

`client_options` is assigned inside the `if ty in ("http", "websocket")` block but referenced later outside it when checking `asgi_scope_client`. Move the assignment to the top of `_get_request_attributes`, before the `if ty` block.
else url_without_query_string
)

client = asgi_scope.get("client")
if client and should_send_default_pii():
ip = _get_ip(asgi_scope)
attributes["client.address"] = ip
asgi_scope_client = asgi_scope.get("client")
if asgi_scope_client:
if has_data_collection_enabled(client_options):
if client_options["data_collection"]["user_info"]:
ip = _get_ip(asgi_scope)
attributes["client.address"] = ip
elif should_send_default_pii():
ip = _get_ip(asgi_scope)
attributes["client.address"] = ip

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unbound client_options on non-HTTP ASGI

High Severity

In _get_request_attributes, client_options is only assigned inside the http/websocket branch, but later used when attaching client.address. For other ASGI scope types that still carry a client, that read raises UnboundLocalError and can break span attribute collection. _get_request_data already assigns client_options before the type check.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit b308065. Configure here.


return attributes
54 changes: 41 additions & 13 deletions sentry_sdk/integrations/_wsgi_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@

import sentry_sdk
from sentry_sdk._types import SENSITIVE_DATA_SUBSTITUTE
from sentry_sdk.data_collection import _apply_key_value_collection_filtering
from sentry_sdk.scope import should_send_default_pii
from sentry_sdk.utils import AnnotatedValue, logger
from sentry_sdk.utils import AnnotatedValue, has_data_collection_enabled, logger

try:
from django.http.request import RawPostDataException
Expand Down Expand Up @@ -88,7 +89,14 @@ def extract_into_event(self, event: "Event") -> None:
content_length = self.content_length()
request_info = event.get("request", {})

if should_send_default_pii():
if has_data_collection_enabled(client.options):
cookies = _apply_key_value_collection_filtering(
items=dict(self.cookies()),
behaviour=client.options["data_collection"]["cookies"],
)
if cookies:
request_info["cookies"] = cookies
elif should_send_default_pii():
request_info["cookies"] = dict(self.cookies())

if not request_body_within_bounds(client, content_length):
Expand Down Expand Up @@ -206,19 +214,39 @@ def _filter_headers(
headers: "Mapping[str, str]",
use_annotated_value: bool = True,
) -> "Mapping[str, Union[AnnotatedValue, str]]":
if should_send_default_pii():
return headers
client_options = sentry_sdk.get_client().options

substitute: "Union[AnnotatedValue, str]" = (
SENSITIVE_DATA_SUBSTITUTE
if not use_annotated_value
else AnnotatedValue.removed_because_over_size_limit()
)
if has_data_collection_enabled(client_options):
data_collection_configuration = client_options["data_collection"]

filtered = _apply_key_value_collection_filtering(
items=headers,
behaviour=data_collection_configuration["http_headers"]["request"],
)

return {
k: (v if k.upper().replace("-", "_") not in SENSITIVE_HEADERS else substitute)
for k, v in headers.items()
}
for key in filtered:
if isinstance(key, str) and key.lower() in ("cookie", "set-cookie"):
filtered[key] = SENSITIVE_DATA_SUBSTITUTE

return filtered
else:
if should_send_default_pii():
return headers

substitute: "Union[AnnotatedValue, str]" = (
SENSITIVE_DATA_SUBSTITUTE
if not use_annotated_value
else AnnotatedValue.removed_because_over_size_limit()
)

return {
k: (
v
if k.upper().replace("-", "_") not in SENSITIVE_HEADERS
else substitute
)
for k, v in headers.items()
}


def _in_http_status_code_range(
Expand Down
Loading
Loading