Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
slack: Check token access scopes before importing.
Alex Vandiver7c849fa940ad
diff --git a/zerver/data_import/slack.py b/zerver/data_import/slack.pyindex f54e7a0f89c..1fd4b517da8 100755--- a/zerver/data_import/slack.py+++ b/zerver/data_import/slack.py@@ -1055,7 +1055,7 @@ def do_convert_data(slack_zip_file: str, output_dir: str, token: str, threads: irealm_id = 0domain_name = settings.EXTERNAL_HOST- log_token_warning(token)+ check_token_access(token)slack_data_dir = slack_zip_file.replace('.zip', '')if not os.path.exists(slack_data_dir):@@ -1124,11 +1124,18 @@ def get_data_file(path: str) -> Any:data = orjson.loads(fp.read())return data-def log_token_warning(token: str) -> None:- if not token.startswith("xoxp-"):- logging.info('Not a Slack legacy token.\n'- ' This token might not have all the needed scopes. We need the following scopes:\n'- ' - emoji:read\n - users:read\n - users:read.email\n - team:read')+def check_token_access(token: str) -> None:+ if token.startswith("xoxp-"):+ logging.info('This is a Slack user token, which grants all rights the user has!')+ elif token.startswith("xoxb-"):+ data = requests.get("https://slack.com/api/team.info", {"token": token})+ has_scopes = set(data.headers.get("x-oauth-scopes", "").split(","))+ required_scopes = set(['emoji:read', 'users:read', 'users:read.email', 'team:read'])+ missing_scopes = required_scopes - has_scopes+ if missing_scopes:+ raise ValueError("Slack token is missing the following required scopes: {}".format(sorted(missing_scopes)))+ else:+ raise Exception("Unknown token type -- must start with xoxb- or xoxp-")def get_slack_api_data(slack_api_url: str, get_param: str, **kwargs: Any) -> Any:diff --git a/zerver/tests/test_slack_importer.py b/zerver/tests/test_slack_importer.pyindex 058c965e009..339063e93fe 100644--- a/zerver/tests/test_slack_importer.py+++ b/zerver/tests/test_slack_importer.py@@ -756,7 +756,7 @@ class SlackImporter(ZulipTestCase):test_realm_subdomain = 'test-slack-import'output_dir = os.path.join(settings.DEPLOY_ROOT, "var", "test-slack-importer-data")- token = 'valid-token'+ token = 'xoxp-valid-token'# If the test fails, the 'output_dir' would not be deleted and hence it would give an# error when we run the tests next time, as 'do_convert_data' expects an empty 'output_dir'