fix(issues): Assert user.id is not None before ORM filter#107744
fix(issues): Assert user.id is not None before ORM filter#107744
Conversation
Found during mypy / django-stubs upgrade in #107710.
| Retrieve a list of starred views for the current organization member. | ||
| """ | ||
|
|
||
| assert request.user.id is not None |
There was a problem hiding this comment.
We should probably return a 4XX error here, instead of an assert which will produce a 500
There was a problem hiding this comment.
FWIW it is actually impossible for our code to reach here with user id being none as this is an authenticated endpoint. just an annoyance that our type checker can't handle. can see we have a lot of these peppered throughout our endpoints.
There was a problem hiding this comment.
Get your point - I think it's fine, but in general I don't love it. We should find a better way of making sure our typing works in these cases
There was a problem hiding this comment.
yeah it is not great. I think that it has to do with django/drf typing stubs, where request.user can be User or AnonymousUser. I don't think it's an easy fix.
| Retrieve a list of starred views for the current organization member. | ||
| """ | ||
|
|
||
| assert request.user.id is not None |
There was a problem hiding this comment.
Bug: The assertion assert request.user.id is not None will fail for valid API token requests that don't have an authenticated user, causing an unhandled AssertionError.
Severity: MEDIUM
Suggested Fix
Replace the assertion assert request.user.id is not None with an explicit check like if not request.user.is_authenticated: return Response(status=400). This ensures proper error handling for unauthenticated API requests, consistent with other similar endpoints in the codebase.
Prompt for AI Agent
Review the code at the location below. A potential bug has been identified by an AI
agent.
Verify if this is a real issue. If it is, propose a fix; if not, explain why it's not
valid.
Location: src/sentry/issues/endpoints/organization_group_search_views_starred.py#L33
Potential issue: The endpoint allows access via API tokens with the `member:read` scope,
which does not require an authenticated user. In such cases, `request.user` is an
`AnonymousUser` and `request.user.id` is `None`. The `assert request.user.id is not
None` statement will then raise an `AssertionError`, leading to an unhandled server
exception instead of a proper HTTP error response. This is inconsistent with similar
endpoints that explicitly check for an authenticated user and return a 400 Bad Request
status.
Did we get this right? 👍 / 👎 to inform future reviews.
There was a problem hiding this comment.
i'm pretty sure api tokens do get user ids.
Summary
Found during mypy / django-stubs upgrade in #107710.
Adds
assert request.user.id is not NonebeforeGroupSearchViewStarred.objects.filter(user_id=request.user.id)in the starred views endpoint.user.idis typed asint | None.Test plan