getsentry / getsentry/sentry-python

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

Abierto
#5,274 2 comentarios 0 reacciones 1 asignado Reclamado por @sl0thentr0py Ver en GitHub
Better Async Support Bug Integration: Django Python
Lenguaje dominante
Python
Estrellas
2.2k
Forks
669
Merge medio
1 d 1 h
PR fusionados (30 d)
213

Descripción

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

Guía de contribución

Abrir la guía de contribución

Evaluación

Este issue todavía no se ha evaluado.

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.