diff --git a/backend/open_webui/utils/auth.py b/backend/open_webui/utils/auth.py index 133dc3c7f..c1f6910dd 100644 --- a/backend/open_webui/utils/auth.py +++ b/backend/open_webui/utils/auth.py @@ -44,8 +44,6 @@ from open_webui.env import ( from fastapi import BackgroundTasks, Depends, HTTPException, Request, Response, status from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer -from sqlalchemy.orm import Session -from open_webui.internal.db import get_session log = logging.getLogger(__name__) @@ -279,7 +277,10 @@ async def get_current_user( response: Response, background_tasks: BackgroundTasks, auth_token: HTTPAuthorizationCredentials = Depends(bearer_security), - db: Session = Depends(get_session), + # NOTE: We intentionally do NOT use Depends(get_session) here. + # Sessions are managed internally with short-lived context managers. + # This ensures connections are released immediately after auth queries, + # not held for the entire request duration (e.g., during 30+ second LLM calls). ): token = None @@ -294,7 +295,7 @@ async def get_current_user( # auth by api key if token.startswith("sk-"): - user = get_current_user_by_api_key(request, token, db=db) + user = get_current_user_by_api_key(request, token) # Add user info to current span current_span = trace.get_current_span() @@ -323,7 +324,7 @@ async def get_current_user( detail="Invalid token", ) - user = Users.get_user_by_id(data["id"], db=db) + user = Users.get_user_by_id(data["id"]) if user is None: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, @@ -373,8 +374,9 @@ async def get_current_user( raise e -def get_current_user_by_api_key(request, api_key: str, db: Session = None): - user = Users.get_user_by_api_key(api_key, db=db) +def get_current_user_by_api_key(request, api_key: str): + # Each function call manages its own short-lived session internally + user = Users.get_user_by_api_key(api_key) if user is None: raise HTTPException( @@ -402,7 +404,7 @@ def get_current_user_by_api_key(request, api_key: str, db: Session = None): current_span.set_attribute("client.user.role", user.role) current_span.set_attribute("client.auth.type", "api_key") - Users.update_last_active_by_id(user.id, db=db) + Users.update_last_active_by_id(user.id) return user