Browse Source

fix(discord): Fix 400 error from bad user id request (#63362)

Fixing `400 Client Error: Bad Request for url:
https://discord.com/api/v10/oauth2/token`.
If the state is missing the code, the request for the token will be
malformed.

Adds a try/except to catch before we try to get the user id.
Julia Hoge 1 year ago
parent
commit
ed29d77191

+ 6 - 1
src/sentry/integrations/discord/integration.py

@@ -172,7 +172,12 @@ class DiscordIntegrationProvider(IntegrationProvider):
         else:
             use_configure = False
         url = self.configure_url if use_configure else self.setup_url
-        discord_user_id = self._get_discord_user_id(str(state.get("code")), url)
+
+        auth_code = str(state.get("code"))
+        if auth_code:
+            discord_user_id = self._get_discord_user_id(auth_code, url)
+        else:
+            raise IntegrationError("Missing code from state.")
 
         return {
             "name": guild_name,

+ 17 - 0
tests/sentry/integrations/discord/test_integration.py

@@ -259,6 +259,23 @@ class DiscordIntegrationTest(IntegrationTestCase):
         result = provider.build_integration({"guild_id": "guild_id", "code": user_id})
         assert result["name"] == guild_name
 
+    @responses.activate
+    def test_build_integration_no_code_in_state(self):
+        provider = self.provider()
+        guild_id = "guild_id"
+        guild_name = "guild_name"
+        responses.add(
+            responses.GET,
+            url=f"{DiscordClient.base_url}{GUILD_URL.format(guild_id=guild_id)}",
+            match=[header_matcher({"Authorization": f"Bot {self.bot_token}"})],
+            json={
+                "id": guild_id,
+                "name": guild_name,
+            },
+        )
+        with pytest.raises(IntegrationError):
+            provider.build_integration({"guild_id": "guild_id", "code": ""})
+
     @responses.activate
     def test_get_guild_name_failure(self):
         provider = self.provider()