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

Update sentry-sdk requirement from ==1.45.* to ==2.5.* #4176

Merged
merged 3 commits into from
Jun 10, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
66 changes: 9 additions & 57 deletions src/pretix/sentry.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,59 +19,22 @@
# You should have received a copy of the GNU Affero General Public License along with this program. If not, see
# <https://www.gnu.org/licenses/>.
#
import re
import weakref
from collections import OrderedDict

from celery.exceptions import Retry
from sentry_sdk import Hub
from sentry_sdk.integrations import django as djangosentry
from sentry_sdk.scrubber import EventScrubber

Check warning on line 27 in src/pretix/sentry.py

View check run for this annotation

Codecov / codecov/patch

src/pretix/sentry.py#L27

Added line #L27 was not covered by tests
from sentry_sdk.utils import capture_internal_exceptions

MASK = '*' * 8
KEYS = frozenset([
'password',
'secret',
'passwd',
'authorization',
'api_key',
'apikey',
'sentry_dsn',
'access_token',
'session',
])
VALUES_RE = re.compile(r'^(?:\d[ -]*?){13,16}$')


def scrub_data(data):
if isinstance(data, dict):
for k, v in data.items():
if isinstance(k, bytes):
key = k.decode('utf-8', 'replace')
else:
key = k
key = key.lower()
data[k] = scrub_data(v)
for blk in KEYS:
if blk in key:
data[k] = MASK
elif isinstance(data, list):
for i, l in enumerate(list(data)):
data[i] = scrub_data(l)
elif isinstance(data, str):
if '=' in data:
# at this point we've assumed it's a standard HTTP query
# or cookie
if '&' in data:
delimiter = '&'
else:
delimiter = ';'

qd = scrub_data(OrderedDict(e.split('=', 1) if '=' in e else (e, None) for e in data.split(delimiter)))
return delimiter.join((k + '=' + v if v is not None else k) for k, v in qd.items())
if VALUES_RE.match(data):
return MASK
return data

class PretixEventScrubber(EventScrubber):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.denylist += [

Check warning on line 34 in src/pretix/sentry.py

View check run for this annotation

Codecov / codecov/patch

src/pretix/sentry.py#L31-L34

Added lines #L31 - L34 were not covered by tests
"access_token",
"sentry_dsn",
]
Copy link
Contributor

Choose a reason for hiding this comment

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

Suggested change
]
]
self.recursive = True

...sonst scheint er nur top-level-keys zu filtern, und wir sind ja bisher rekursiv unterwegs

Copy link
Contributor

Choose a reason for hiding this comment

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

eigentlich können wir uns den eigenen PretixEventScrubber auch sparen und einfach wie in der doku nur eine eigene denylist definieren und den EventScrubber direkt nutzen

from sentry_sdk.scrubber import EventScrubber, DEFAULT_DENYLIST
        # custom denylist
        pretix_denylist = DEFAULT_DENYLIST + [
            "access_token",
            "sentry_dsn",
        ]
        sentry_sdk.init(
            # ...
            event_scrubber=EventScrubber(denylist=pretix_denylist, recursive=True),



def _make_event_processor(weak_request, integration):
Expand All @@ -82,8 +45,6 @@

with capture_internal_exceptions():
djangosentry._set_user_info(request, event)
request_info = event.setdefault("request", {})
request_info["cookies"] = dict(request.COOKIES)

# Sentry's DjangoIntegration already sets the transaction, but it gets confused by our multi-domain stuff
# where the URL resolver changes in the middleware stack. Additionally, we'd like to get the method.
Expand All @@ -96,15 +57,6 @@
request.method,
url
)

# We want to scrub data not only from the request, but from traceback frames as well!
scrub_data(event.get("request", {}))
if 'exception' in event:
exc = event.get("exception", {})
for val in exc.get('values', []):
stack = val.get('stacktrace', {})
for frame in stack.get('frames', []):
scrub_data(frame['vars'])
return event

return event_processor
Expand Down
11 changes: 9 additions & 2 deletions src/pretix/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -629,13 +629,14 @@

SENTRY_ENABLED = False
if config.has_option('sentry', 'dsn') and not any(c in sys.argv for c in ('shell', 'shell_scoped', 'shell_plus')):
import django.db.models.signals
import sentry_sdk
from sentry_sdk.integrations.celery import CeleryIntegration
from sentry_sdk.integrations.logging import (
LoggingIntegration, ignore_logger,
)

from .sentry import PretixSentryIntegration, setup_custom_filters
from .sentry import PretixSentryIntegration, PretixEventScrubber, setup_custom_filters

SENTRY_TOKEN = config.get('sentry', 'traces_sample_token', fallback='')

Expand All @@ -649,7 +650,12 @@ def traces_sampler(sampling_context):
sentry_sdk.init(
dsn=config.get('sentry', 'dsn'),
integrations=[
PretixSentryIntegration(),
PretixSentryIntegration(
signals_denylist=[
django.db.models.signals.pre_init,
django.db.models.signals.post_init,
]
),
CeleryIntegration(),
LoggingIntegration(
level=logging.INFO,
Expand All @@ -659,6 +665,7 @@ def traces_sampler(sampling_context):
traces_sampler=traces_sampler,
environment=urlparse(SITE_URL).netloc,
release=__version__,
event_scrubber=PretixEventScrubber(),
send_default_pii=False,
propagate_traces=False, # see https://github.com/getsentry/sentry-python/issues/1717
)
Expand Down
Loading