Skip to content

Commit

Permalink
ref: fix AttributeError on request.auth when request is rejected by a…
Browse files Browse the repository at this point in the history
… middleware (#84386)

resolves SENTRY-3N0J



<!-- Describe your PR here. -->
  • Loading branch information
asottile-sentry authored Jan 31, 2025
1 parent e37eb2e commit 1f0d5ad
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 2 deletions.
4 changes: 3 additions & 1 deletion src/sentry/middleware/access_log.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,9 @@ def get_request_duration(self) -> float:
def _get_request_auth(request: Request) -> AuthenticatedToken | None:
if request.path_info.startswith(settings.ANONYMOUS_STATIC_PREFIXES):
return None
return request.auth
# may not be present if request was rejected by a middleware between this
# and the auth middleware
return getattr(request, "auth", None)


def _get_token_name(auth: AuthenticatedToken | None) -> str | None:
Expand Down
11 changes: 10 additions & 1 deletion tests/sentry/middleware/test_access_log_middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,6 @@ class TestAccessLogSuccess(LogCaptureAPITestCase):

def test_access_log_success(self):
self._caplog.set_level(logging.INFO, logger="sentry")
token = None
with assume_test_silo_mode(SiloMode.CONTROL):
token = ApiToken.objects.create(user=self.user, scope_list=["event:read", "org:read"])
self.login_as(user=self.create_user())
Expand All @@ -210,6 +209,16 @@ def test_access_log_success(self):
assert tested_log.token_type == "api_token"
assert tested_log.token_last_characters == token.token_last_characters

def test_with_subdomain_redirect(self):
# the subdomain middleware is in between this and the access log middelware
# meaning if a request is rejected between those then it will not have `auth`
# set up properly
# this previously logged an error to sentry
resp = self.get_response(extra_headers={"HTTP_HOST": "invalid_domain.testserver"})
assert resp.status_code == 302
records = [record for record in self._caplog.records if record.levelno == logging.ERROR]
assert not records # no errors should occur


@all_silo_test
@override_settings(LOG_API_ACCESS=False)
Expand Down

0 comments on commit 1f0d5ad

Please sign in to comment.