The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
fix: resolve OCR CodeQL alerts
Ishaan Jaff2977e2bf4272
diff --git a/litellm/ocr/main.py b/litellm/ocr/main.pyindex 8bd87ae21d3..80fde8ff9f3 100644--- a/litellm/ocr/main.py+++ b/litellm/ocr/main.py@@ -336,7 +336,16 @@ async def aocr()```"""- local_vars = locals()+ completion_kwargs: dict[str, object] = {+ "model": model,+ "document": document,+ "api_key": api_key,+ "api_base": api_base,+ "timeout": timeout,+ "custom_llm_provider": custom_llm_provider,+ "extra_headers": extra_headers,+ "kwargs": kwargs,+ }try:prepared = _prepare_ocr_request(model=model,@@ -350,7 +359,9 @@ async def aocr()model = prepared.modelcustom_llm_provider = prepared.custom_llm_provider- local_vars.update({"model": model, "custom_llm_provider": custom_llm_provider})+ completion_kwargs.update(+ {"model": model, "custom_llm_provider": custom_llm_provider}+ )if prepared.custom_llm_provider == "mistral" and rust_ocr_enabled():rust_aocr = load_rust_aocr()@@ -397,11 +408,136 @@ async def aocr(model=model,custom_llm_provider=custom_llm_provider,original_exception=e,- completion_kwargs=local_vars,+ completion_kwargs=completion_kwargs,extra_kwargs=kwargs,)+#################################################+# Public utilities — used by the SDK and the proxy+#################################################++_MIME_PATTERN = re.compile(r"^[\w.+-]+/[\w.+-]+$")++_MIME_TYPE_MAP = {+ ".pdf": "application/pdf",+ ".png": "image/png",+ ".jpg": "image/jpeg",+ ".jpeg": "image/jpeg",+ ".gif": "image/gif",+ ".webp": "image/webp",+ ".tiff": "image/tiff",+ ".tif": "image/tiff",+ ".bmp": "image/bmp",+}+++def get_mime_type(file_path: str) -> str:+ """+ Determine MIME type from file path extension.++ Falls back to mimetypes.guess_type, then to 'application/octet-stream'.+ """+ ext = os.path.splitext(file_path)[1].lower()+ mime = _MIME_TYPE_MAP.get(ext)+ if mime:+ return mime+ guessed, _ = mimetypes.guess_type(file_path)+ return guessed or "application/octet-stream"+++def convert_file_document_to_url_document(document: dict[str, Any]) -> dict[str, str]:+ """+ Convert a file-type document dict to a document_url-type document dict+ with an inline base64 data URI.++ Accepts document dicts like:+ {"type": "file", "file": Path("/path/to/doc.pdf")} # pathlib.Path+ {"type": "file", "file": <binary file-like object>} # file-like object (BinaryIO)+ {"type": "file", "file": b"raw bytes"} # raw bytes++ Bare ``str`` paths are not accepted — pass a ``pathlib.Path`` or+ ``open(path, "rb")`` instead. See the str check below for the rationale.++ Returns:+ {"type": "document_url", "document_url": "data:<mime>;base64,<data>"}+ or {"type": "image_url", "image_url": "data:<mime>;base64,<data>"}+ """+ file_input = document.get("file")+ if file_input is None:+ raise ValueError(+ "document with type='file' must include a 'file' field containing "+ "a pathlib.Path, file-like object, or bytes"+ )++ file_bytes: bytes+ mime_type: str = "application/octet-stream"+ file_name: Optional[str] = None++ if isinstance(file_input, str):+ # Bare strings are rejected here. The OCR ``document`` accepts a+ # ``{"type": "file", "file": <value>}`` shape, and when this helper+ # runs in a proxy request handler ``<value>`` is attacker-controlled.+ # Opening it as a path is an arbitrary local file read on the proxy+ # host, which is then base64-encoded and forwarded to the OCR+ # provider — an exfiltration primitive.+ raise ValueError(+ "OCR file input does not accept bare str values. Pass bytes, "+ "a pathlib.Path, or a file-like object. To OCR a local file "+ "from a path, call open(path, 'rb') yourself."+ )+ if isinstance(file_input, os.PathLike):+ # os.PathLike (pathlib.Path and custom __fspath__ classes) is a+ # Python-level type that HTTP form values can't fabricate.+ file_path = str(file_input)+ if not os.path.isfile(file_path):+ raise FileNotFoundError(f"File not found: {file_path}")+ mime_type = get_mime_type(file_path)+ file_name = os.path.basename(file_path)+ with open(file_path, "rb") as f:+ file_bytes = f.read()+ elif isinstance(file_input, bytes):+ file_bytes = file_input+ elif isinstance(file_input, IOBase) or hasattr(file_input, "read"):+ if hasattr(file_input, "name"):+ file_name = getattr(file_input, "name", None)+ if file_name:+ mime_type = get_mime_type(file_name)+ file_bytes = file_input.read()+ if isinstance(file_bytes, str):+ file_bytes = file_bytes.encode("utf-8")+ else:+ raise ValueError(+ f"Unsupported file input type: {type(file_input)}. "+ "Expected pathlib.Path, bytes, or a file-like object."+ )++ if not file_bytes:+ raise ValueError("File is empty or could not be read")++ if "mime_type" in document:+ mime_type = document["mime_type"]++ if not _MIME_PATTERN.match(mime_type):+ raise ValueError(f"Invalid MIME type: {mime_type}")++ base64_data = base64.b64encode(file_bytes).decode("utf-8")+ data_uri = f"data:{mime_type};base64,{base64_data}"++ if mime_type.startswith("image/"):+ verbose_logger.debug(+ f"OCR file input: Converted file to image_url data URI "+ f"(mime={mime_type}, size={len(file_bytes)} bytes, name={file_name})"+ )+ return {"type": "image_url", "image_url": data_uri}++ verbose_logger.debug(+ f"OCR file input: Converted file to document_url data URI "+ f"(mime={mime_type}, size={len(file_bytes)} bytes, name={file_name})"+ )+ return {"type": "document_url", "document_url": data_uri}++@clientdef ocr(model: str,@@ -475,9 +611,19 @@ def ocr(print(f"Page {page.index}: {page.markdown}")```"""- local_vars = locals()+ completion_kwargs: dict[str, object] = {+ "model": model,+ "document": document,+ "api_key": api_key,+ "api_base": api_base,+ "timeout": timeout,+ "custom_llm_provider": custom_llm_provider,+ "extra_headers": extra_headers,+ "kwargs": kwargs,+ }try:_is_async = kwargs.pop("aocr", False) is True+ completion_kwargs["aocr"] = _is_asyncprepared = _prepare_ocr_request(model=model,document=document,@@ -490,7 +636,9 @@ def ocr()model = prepared.modelcustom_llm_provider = prepared.custom_llm_provider- local_vars.update({"model": model, "custom_llm_provider": custom_llm_provider})+ completion_kwargs.update(+ {"model": model, "custom_llm_provider": custom_llm_provider}+ )# Optional Rust path: hand the whole Mistral OCR call to the Rust bridge.if prepared.custom_llm_provider == "mistral" and rust_ocr_enabled():@@ -529,131 +677,6 @@ def ocr(model=model,custom_llm_provider=custom_llm_provider,original_exception=e,- completion_kwargs=local_vars,+ completion_kwargs=completion_kwargs,extra_kwargs=kwargs,)---#################################################-# Public utilities — used by the SDK and the proxy-#################################################--_MIME_PATTERN = re.compile(r"^[\w.+-]+/[\w.+-]+$")--_MIME_TYPE_MAP = {- ".pdf": "application/pdf",- ".png": "image/png",- ".jpg": "image/jpeg",- ".jpeg": "image/jpeg",- ".gif": "image/gif",- ".webp": "image/webp",- ".tiff": "image/tiff",- ".tif": "image/tiff",- ".bmp": "image/bmp",-}---def get_mime_type(file_path: str) -> str:- """- Determine MIME type from file path extension.-- Falls back to mimetypes.guess_type, then to 'application/octet-stream'.- """- ext = os.path.splitext(file_path)[1].lower()- mime = _MIME_TYPE_MAP.get(ext)- if mime:- return mime- guessed, _ = mimetypes.guess_type(file_path)- return guessed or "application/octet-stream"---def convert_file_document_to_url_document(document: dict[str, Any]) -> dict[str, str]:- """- Convert a file-type document dict to a document_url-type document dict- with an inline base64 data URI.-- Accepts document dicts like:- {"type": "file", "file": Path("/path/to/doc.pdf")} # pathlib.Path- {"type": "file", "file": <binary file-like object>} # file-like object (BinaryIO)- {"type": "file", "file": b"raw bytes"} # raw bytes-- Bare ``str`` paths are not accepted — pass a ``pathlib.Path`` or- ``open(path, "rb")`` instead. See the str check below for the rationale.-- Returns:- {"type": "document_url", "document_url": "data:<mime>;base64,<data>"}- or {"type": "image_url", "image_url": "data:<mime>;base64,<data>"}- """- file_input = document.get("file")- if file_input is None:- raise ValueError(- "document with type='file' must include a 'file' field containing "- "a pathlib.Path, file-like object, or bytes"- )-- file_bytes: bytes- mime_type: str = "application/octet-stream"- file_name: Optional[str] = None-- if isinstance(file_input, str):- # Bare strings are rejected here. The OCR ``document`` accepts a- # ``{"type": "file", "file": <value>}`` shape, and when this helper- # runs in a proxy request handler ``<value>`` is attacker-controlled.- # Opening it as a path is an arbitrary local file read on the proxy- # host, which is then base64-encoded and forwarded to the OCR- # provider — an exfiltration primitive.- raise ValueError(- "OCR file input does not accept bare str values. Pass bytes, "- "a pathlib.Path, or a file-like object. To OCR a local file "- "from a path, call open(path, 'rb') yourself."- )- if isinstance(file_input, os.PathLike):- # os.PathLike (pathlib.Path and custom __fspath__ classes) is a- # Python-level type that HTTP form values can't fabricate.- file_path = str(file_input)- if not os.path.isfile(file_path):- raise FileNotFoundError(f"File not found: {file_path}")- mime_type = get_mime_type(file_path)- file_name = os.path.basename(file_path)- with open(file_path, "rb") as f:- file_bytes = f.read()- elif isinstance(file_input, bytes):- file_bytes = file_input- elif isinstance(file_input, IOBase) or hasattr(file_input, "read"):- if hasattr(file_input, "name"):- file_name = getattr(file_input, "name", None)- if file_name:- mime_type = get_mime_type(file_name)- file_bytes = file_input.read()- if isinstance(file_bytes, str):- file_bytes = file_bytes.encode("utf-8")- else:- raise ValueError(- f"Unsupported file input type: {type(file_input)}. "- "Expected pathlib.Path, bytes, or a file-like object."- )-- if not file_bytes:- raise ValueError("File is empty or could not be read")-- if "mime_type" in document:- mime_type = document["mime_type"]-- if not _MIME_PATTERN.match(mime_type):- raise ValueError(f"Invalid MIME type: {mime_type}")-- base64_data = base64.b64encode(file_bytes).decode("utf-8")- data_uri = f"data:{mime_type};base64,{base64_data}"-- if mime_type.startswith("image/"):- verbose_logger.debug(- f"OCR file input: Converted file to image_url data URI "- f"(mime={mime_type}, size={len(file_bytes)} bytes, name={file_name})"- )- return {"type": "image_url", "image_url": data_uri}- else:- verbose_logger.debug(- f"OCR file input: Converted file to document_url data URI "- f"(mime={mime_type}, size={len(file_bytes)} bytes, name={file_name})"- )- return {"type": "document_url", "document_url": data_uri}diff --git a/litellm/proxy/ocr_endpoints/endpoints.py b/litellm/proxy/ocr_endpoints/endpoints.pyindex e32fee6afc5..823b4a5e86c 100644--- a/litellm/proxy/ocr_endpoints/endpoints.py+++ b/litellm/proxy/ocr_endpoints/endpoints.py@@ -8,7 +8,6 @@ from fastapi import APIRouter, Depends, Request, Response, UploadFilefrom fastapi.responses import ORJSONResponsefrom litellm._logging import verbose_proxy_logger-from litellm.ocr.main import convert_file_document_to_url_document, get_mime_typefrom litellm.proxy._types import *from litellm.proxy.auth.user_api_key_auth import UserAPIKeyAuth, user_api_key_authfrom litellm.proxy.common_request_processing import ProxyBaseLLMRequestProcessing@@ -27,6 +26,8 @@ def _build_document_from_upload(Delegates to convert_file_document_to_url_document after resolving MIME typefrom the upload's content_type header or filename."""+ from litellm.ocr.main import convert_file_document_to_url_document, get_mime_type+mime_type = content_type.split(";")[0].strip() if content_type else Noneif not mime_type or mime_type == "application/octet-stream":if filename: