Validating slackbot tokens (#3695)

* added missing dependency, missing api key placeholder, updated docs

* Apply black formatting and validate bot token functionality

* acknowledging black formatting

* added the validation to update tokens as well

* Made the token validation errors looks nicer

* getting rif of duplicate dependency
This commit is contained in:
Kaveen Jayamanna
2025-01-17 14:50:22 -05:00
committed by GitHub
parent c9e0d77c93
commit 880c42ad41
5 changed files with 62 additions and 4 deletions

View File

@@ -27,6 +27,8 @@ from onyx.server.manage.models import SlackBot
from onyx.server.manage.models import SlackBotCreationRequest
from onyx.server.manage.models import SlackChannelConfig
from onyx.server.manage.models import SlackChannelConfigCreationRequest
from onyx.server.manage.validate_tokens import validate_app_token
from onyx.server.manage.validate_tokens import validate_bot_token
from onyx.utils.telemetry import create_milestone_and_report
@@ -222,6 +224,9 @@ def create_bot(
_: User | None = Depends(current_admin_user),
tenant_id: str | None = Depends(get_current_tenant_id),
) -> SlackBot:
validate_app_token(slack_bot_creation_request.app_token)
validate_bot_token(slack_bot_creation_request.bot_token)
slack_bot_model = insert_slack_bot(
db_session=db_session,
name=slack_bot_creation_request.name,
@@ -248,6 +253,8 @@ def patch_bot(
db_session: Session = Depends(get_session),
_: User | None = Depends(current_admin_user),
) -> SlackBot:
validate_bot_token(slack_bot_creation_request.bot_token)
validate_app_token(slack_bot_creation_request.app_token)
slack_bot_model = update_slack_bot(
db_session=db_session,
slack_bot_id=slack_bot_id,

View File

@@ -0,0 +1,43 @@
import requests
from fastapi import HTTPException
SLACK_API_URL = "https://slack.com/api/auth.test"
SLACK_CONNECTIONS_OPEN_URL = "https://slack.com/api/apps.connections.open"
def validate_bot_token(bot_token: str) -> bool:
headers = {"Authorization": f"Bearer {bot_token}"}
response = requests.post(SLACK_API_URL, headers=headers)
if response.status_code != 200:
raise HTTPException(
status_code=500, detail="Error communicating with Slack API."
)
data = response.json()
if not data.get("ok", False):
raise HTTPException(
status_code=400,
detail=f"Invalid bot token: {data.get('error', 'Unknown error')}",
)
return True
def validate_app_token(app_token: str) -> bool:
headers = {"Authorization": f"Bearer {app_token}"}
response = requests.post(SLACK_CONNECTIONS_OPEN_URL, headers=headers)
if response.status_code != 200:
raise HTTPException(
status_code=500, detail="Error communicating with Slack API."
)
data = response.json()
if not data.get("ok", False):
raise HTTPException(
status_code=400,
detail=f"Invalid app token: {data.get('error', 'Unknown error')}",
)
return True