π OpenHands: AI-Driven Development
feat: improve credential validation and simplify response in `get_token` (#1155)
Edwards.Arno94831083c3ee
diff --git a/opendevin/server/auth/auth.py b/opendevin/server/auth/auth.pyindex 8df2226c8f..81b73cec1f 100644--- a/opendevin/server/auth/auth.py+++ b/opendevin/server/auth/auth.py@@ -2,21 +2,36 @@ import osimport jwtfrom typing import Dictfrom opendevin.logger import opendevin_logger as logger+from jwt.exceptions import InvalidTokenErrorJWT_SECRET = os.getenv('JWT_SECRET', '5ecRe7')def get_sid_from_token(token: str) -> str:- """Gets the session id from a JWT token."""+ """+ Retrieves the session id from a JWT token.++ Parameters:+ token (str): The JWT token from which the session id is to be extracted.++ Returns:+ str: The session id if found and valid, otherwise an empty string.+ """try:+ # Decode the JWT using the specified secret and algorithmpayload = jwt.decode(token, JWT_SECRET, algorithms=['HS256'])- if payload is None:- logger.error('Invalid token')++ # Ensure the payload contains 'sid'+ if 'sid' in payload:+ return payload['sid']+ else:+ logger.error('SID not found in token')return ''- return payload['sid']+ except InvalidTokenError:+ logger.error('Invalid token')except Exception as e:- logger.exception('Error decoding token: %s', e)- return ''+ logger.exception('Unexpected error decoding token: %s', e)+ return ''def sign_token(payload: Dict[str, object]) -> str:diff --git a/opendevin/server/listen.py b/opendevin/server/listen.pyindex 5ea9aa25cd..50e3f9109d 100644--- a/opendevin/server/listen.py+++ b/opendevin/server/listen.py@@ -2,13 +2,11 @@ import uuidfrom pathlib import Pathimport litellm-from fastapi import Depends, FastAPI, WebSocket+from fastapi import Depends, FastAPI, WebSocket, statusfrom fastapi.middleware.cors import CORSMiddleware-from fastapi.responses import RedirectResponsefrom fastapi.security import HTTPAuthorizationCredentials, HTTPBearerfrom fastapi.staticfiles import StaticFiles-from starlette import status-from starlette.responses import JSONResponse+from fastapi.responses import RedirectResponse, JSONResponseimport agenthub # noqa F401 (we import this to get the agents registered)from opendevin import config, files@@ -67,11 +65,20 @@ async def get_token(credentials: HTTPAuthorizationCredentials = Depends(security_scheme),):"""- Get token for authentication when starts a websocket connection.+ Generate a JWT for authentication when starting a WebSocket connection. This endpoint checks if valid credentials+ are provided and uses them to get a session ID. If no valid credentials are provided, it generates a new session ID."""- sid = get_sid_from_token(credentials.credentials) or str(uuid.uuid4())+ if credentials and credentials.credentials:+ sid = get_sid_from_token(credentials.credentials)+ if not sid:+ sid = str(uuid.uuid4())+ logger.info(f'Invalid or missing credentials, generating new session ID: {sid}')+ else:+ sid = str(uuid.uuid4())+ logger.info(f'No credentials provided, generating new session ID: {sid}')+token = sign_token({'sid': sid})- return {'token': token}+ return {'token': token, 'status': 'ok'}@app.get('/api/messages')