Skip to content

fix(sentry app authorizations): Return token if already made for sentry #91507

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
May 20, 2025
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 25 additions & 12 deletions src/sentry/sentry_apps/token_exchange/refresher.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import logging
from dataclasses import dataclass

from django.db import router, transaction
from django.db import OperationalError, router, transaction
from django.utils.functional import cached_property

from sentry import analytics
Expand Down Expand Up @@ -30,22 +30,35 @@ class Refresher:
user: User

def run(self) -> ApiToken:
with transaction.atomic(router.db_for_write(ApiToken)):
try:
try:
token = None
with transaction.atomic(router.db_for_write(ApiToken)):
self._validate()
self.token.delete()

self._record_analytics()
return self._create_new_token()
except (SentryAppIntegratorError, SentryAppSentryError):
logger.info(
"refresher.context",
extra={
"application_id": self.application.id,
"refresh_token": self.refresh_token[-4:],
},
Comment on lines -40 to -46
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Taking these logs out as they were to debug a prior customer issue a while back

token = self._create_new_token()
return token
except OperationalError as e:
Copy link
Member

@GabeVillalobos GabeVillalobos May 13, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instead of catching an OperationalError here, I wonder if we should instead catch and raise this in the outbox_context decorator as a distinct error. Handling DB level concerns at the API layer seems like something we want to avoid if possible.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I tried to do this via adding OutboxFlushError at the on_commit process since that lambda is responsible for all actions after the database has committed.

I was having trouble understanding what the test_outbox tests do & how to write one for the error handling changes. (I also didn't want to spend too much more time digging so I only made a test for refresher.py :bufo-hide:)

Lmk thoughts /

context = {
"installation_uuid": self.install.uuid,
"client_id": self.application.client_id[:SENSITIVE_CHARACTER_LIMIT],
"sentry_app_id": self.install.sentry_app.id,
}

if token is not None:
logger.warning(
"refresher.database-failure",
extra=context,
exc_info=e,
)
raise
return token

raise SentryAppSentryError(
message="Failed to refresh given token",
status_code=500,
webhook_context=context,
) from e

def _record_analytics(self) -> None:
analytics.record(
Expand Down
2 changes: 1 addition & 1 deletion src/sentry/sentry_apps/token_exchange/validator.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ def application(self) -> ApiApplication:
try:
return ApiApplication.objects.get(client_id=self.client_id)
except ApiApplication.DoesNotExist:
raise SentryAppSentryError(
raise SentryAppIntegratorError(
"Application does not exist",
webhook_context={"client_id": self.client_id[:SENSITIVE_CHARACTER_LIMIT]},
)
31 changes: 30 additions & 1 deletion tests/sentry/sentry_apps/token_exchange/test_refresher.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from unittest.mock import PropertyMock, patch

import pytest
from django.db.utils import OperationalError

from sentry.models.apiapplication import ApiApplication
from sentry.models.apitoken import ApiToken
Expand Down Expand Up @@ -92,8 +93,9 @@ def test_token_must_exist(self, _):
}
assert e.value.public_context == {}

@patch("sentry.sentry_apps.token_exchange.refresher.Refresher._validate")
@patch("sentry.models.ApiApplication.objects.get", side_effect=ApiApplication.DoesNotExist)
def test_api_application_must_exist(self, _):
def test_api_application_must_exist(self, _, mock_validate):
with pytest.raises(SentryAppIntegratorError) as e:
self.refresher.run()

Expand Down Expand Up @@ -133,3 +135,30 @@ def test_records_analytics(self, record):
sentry_app_installation_id=self.install.id,
exchange_type="refresh",
)

def test_returns_token_on_outbox_error(self):
# Mock the transaction to raise OperationalError after token creation
with patch(
"sentry.hybridcloud.models.outbox.process_region_outbox.send"
) as mock_transaction:
mock_transaction.atomic.side_effect = OperationalError("Outbox issue")

# The refresher should return the token even though there was an error
token = self.refresher.run()
assert SentryAppInstallation.objects.get(id=self.install.id).api_token == token

def test_raises_error_on_operational_error_before_creation(self):
# Mock the transaction to raise OperationalError before token creation
with patch("sentry.sentry_apps.token_exchange.refresher.transaction") as mock_transaction:
mock_transaction.atomic.side_effect = OperationalError("Database error")

with pytest.raises(SentryAppSentryError) as e:
self.refresher.run()

assert e.value.message == "Failed to refresh given token"
assert e.value.status_code == 500
assert e.value.webhook_context == {
"installation_uuid": self.install.uuid,
"client_id": self.client_id[:SENSITIVE_CHARACTER_LIMIT],
"sentry_app_id": self.install.sentry_app.id,
}
Loading