getsentry / getsentry/sentry-python

Django ASGI: send_default_pii triggers request.user.is_authenticated sync access

オープン
#5,274 コメント 2 件 リアクション 0 件 担当者 1 名 @sl0thentr0py が担当を希望しています GitHub で見る
Better Async Support Bug Integration: Django Python
主要言語
Python
スター
2.2k
フォーク
669
平均マージ
1日 1時間
マージ済み PR(30日)
213

説明

### Summary
When running Django under ASGI with `send_default_pii=True`, Sentry’s Django integration calls `request.user.is_authenticated` in the ASGI event processor. On Django 5.x this triggers lazy session-backed user resolution in an async context and raises `SynchronousOnlyOperation: You cannot call this from an async context`.

This appears to happen when the request uses Django’s session auth (e.g. Django admin). It does not occur when user objects are already concretely loaded (custom auth middleware). Disabling `send_default_pii` avoids the error.

### Environment
- Python: 3.11
- Django: 5.1.2
- sentry-sdk: 2.48.0
- Deployment: ASGI (gunicorn + uvicorn worker)

### Steps to Reproduce
1. Configure Django with `AuthenticationMiddleware` + `SessionMiddleware`.
2. Run under ASGI.
3. Configure Sentry with `send_default_pii=True`.
4. Hit `/admin/` (or any endpoint using Django session auth).

### Actual Behavior
Sentry logs an internal SDK error:
```
.../django/utils/functional.py in _setup
.../sentry_sdk/integrations/django/__init__.py in is_authenticated
return request_user.is_authenticated
.../sentry_sdk/integrations/django/__init__.py in _set_user_info
if user is None or not is_authenticated(user):
.../sentry_sdk/integrations/django/asgi.py in asgi_request_event_processor
_set_user_info(request, event)
.../django/contrib/sessions/backends/base.py in _get_session
return self._session_cache
SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async.
```

### Expected Behavior
In async contexts, the Django integration should avoid touching `request.user` synchronously. Ideally it should use async-safe APIs (e.g. `request.auser()` / `auth.aget_user`) or skip user capture in ASGI when `send_default_pii` is enabled.

### Notes
- This appears limited to async requests; WSGI does not raise.
- A workaround is `send_default_pii=False` and manually calling `sentry_sdk.set_user()` after resolving the user asynchronously.

コントリビューションガイド

コントリビューションガイドを開く

評価

この issue はまだ評価されていません。

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。