getsentry / getsentry/sentry-python

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

Đang mở
#5,274 2 bình luận 0 reaction 1 người được giao Được @sl0thentr0py nhận Xem trên GitHub
Better Async Support Bug Integration: Django Python
Ngôn ngữ chính
Python
Star
2.2k
Fork
669
Merge trung bình
1 ngày 1 giờ
Pull request đã merge (30 ngày)
213

Mô tả

### 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.

Hướng dẫn đóng góp

Mở hướng dẫn đóng góp

Đánh giá

Issue này chưa được đánh giá.

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.