Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
slack: Raise a token-free error from check_slack_token_access.
Aman Agrawal9f09b5e56402
diff --git a/zerver/data_import/slack.py b/zerver/data_import/slack.pyindex 9ac51387bf4..0d910dcbe5a 100644--- a/zerver/data_import/slack.py+++ b/zerver/data_import/slack.py@@ -1826,32 +1826,44 @@ def do_convert_directory(logging.info("Zulip data dump created at %s", output_dir)+class SlackTokenValidationError(Exception):+ """Raised by check_slack_token_access when a Slack token fails validation.+ The message never includes the token itself, so it is safe to surface to+ users -- e.g. on the self-serve import page or to a webhook's bot owner."""++def check_slack_token_access(token: str, required_scopes: set[str]) -> None:if token.startswith("xoxp-"):logging.info("This is a Slack user token, which grants all rights the user has!")elif not required_scopes:raise ValueError("required_scopes shouldn't be empty!")elif token.startswith("xoxb-"):- data = requests.get(- "https://slack.com/api/api.test", headers={"Authorization": f"Bearer {token}"}- )+ try:+ data = requests.get(+ "https://slack.com/api/api.test", headers={"Authorization": f"Bearer {token}"}+ )+ except requests.RequestException as e:+ logging.info("Slack token validation request failed: %s", e)+ raise SlackTokenValidationError(+ "Could not reach Slack to validate the token. Please try again."+ )if data.status_code != 200:- raise ValueError(- f"Failed to fetch data (HTTP status {data.status_code}) for Slack token: {token}"+ raise SlackTokenValidationError(+ f"Failed to validate the token with Slack (HTTP status {data.status_code}).")if not data.json()["ok"]:error = data.json()["error"]if error != "missing_scope":logging.info("Slack token is invalid: %s", error)- raise ValueError(f"Invalid token: {token}")+ raise SlackTokenValidationError("Invalid token.")has_scopes = set(data.headers.get("x-oauth-scopes", "").split(","))missing_scopes = required_scopes - has_scopesif missing_scopes:- raise ValueError(+ raise SlackTokenValidationError(f"Slack token is missing the following required scopes: {sorted(missing_scopes)}")else:- raise Exception("Invalid token. Valid tokens start with xoxb-.")+ raise SlackTokenValidationError("Invalid token. Valid tokens start with xoxb-.")def get_slack_api_data(diff --git a/zerver/tests/test_slack_importer.py b/zerver/tests/test_slack_importer.pyindex 7c90419eafb..5766d4f8978 100644--- a/zerver/tests/test_slack_importer.py+++ b/zerver/tests/test_slack_importer.py@@ -46,6 +46,7 @@ from zerver.data_import.slack import (MessageConversionResult,SlackBotEmail,SlackBotNotFoundError,+ SlackTokenValidationError,channel_message_to_zerver_message,channels_to_zerver_stream,check_slack_token_access,@@ -450,9 +451,12 @@ class SlackImporter(ZulipTestCase):)def exception_for(token: str, required_scopes: set[str] = SLACK_IMPORT_TOKEN_SCOPES) -> str:- with self.assertRaises(Exception) as invalid:+ with self.assertRaises(SlackTokenValidationError) as invalid:check_slack_token_access(token, required_scopes)- return invalid.exception.args[0]+ message = invalid.exception.args[0]+ # The user-facing message must never leak the token.+ self.assertNotIn(token, message)+ return messageself.assertEqual(exception_for("xoxq-unknown"),@@ -462,12 +466,12 @@ class SlackImporter(ZulipTestCase):with self.assertLogs(level="INFO"):self.assertEqual(exception_for("xoxb-invalid-token"),- "Invalid token: xoxb-invalid-token",+ "Invalid token.",)self.assertEqual(exception_for("xoxb-broken-request"),- "Failed to fetch data (HTTP status 400) for Slack token: xoxb-broken-request",+ "Failed to validate the token with Slack (HTTP status 400).",)self.assertEqual(@@ -479,10 +483,10 @@ class SlackImporter(ZulipTestCase):"Slack token is missing the following required scopes: ['team:read', 'users:read', 'users:read.email']",)- self.assertEqual(- exception_for("xoxb-valid-token", set()),- "required_scopes shouldn't be empty!",- )+ # An empty required_scopes is a caller bug, not a token problem.+ with self.assertRaises(ValueError) as empty_scopes:+ check_slack_token_access("xoxb-valid-token", set())+ self.assertEqual(empty_scopes.exception.args[0], "required_scopes shouldn't be empty!")check_slack_token_access("xoxb-valid-token", required_scopes=SLACK_IMPORT_TOKEN_SCOPES)@@ -2477,7 +2481,7 @@ To Doassert confirmation_key is not None# Check that the we show an error message if the token is invalid.- mock_check_slack_token_access.side_effect = ValueError("Invalid slack token")+ mock_check_slack_token_access.side_effect = SlackTokenValidationError("Invalid slack token")result = self.client_post("/new/import/slack/",{diff --git a/zerver/views/registration.py b/zerver/views/registration.pyindex bde15de53fd..bdfeba3287b 100644--- a/zerver/views/registration.py+++ b/zerver/views/registration.py@@ -483,12 +483,13 @@ def registration_helper(# Verify slack token access.from zerver.data_import.slack import (SLACK_IMPORT_TOKEN_SCOPES,+ SlackTokenValidationError,check_slack_token_access,)try:check_slack_token_access(slack_access_token, SLACK_IMPORT_TOKEN_SCOPES)- except Exception as e:+ except SlackTokenValidationError as e:logger.info("(%s) Slack token failed validation: %s", prereg_realm.string_id, str(e))