Skip to content

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]

refactor(core): move path_utils from proxy common_utils to litellm_core_utils (#45775)

nate-berri9d559d85795b
diff --git a/litellm/litellm_core_utils/path_utils.py b/litellm/litellm_core_utils/path_utils.py
new file mode 100644
index 00000000000..3494a4c3fa0
--- /dev/null
+++ b/litellm/litellm_core_utils/path_utils.py
@@ -0,0 +1,96 @@
+"""
+Safe filesystem path construction for user-controlled inputs.
+
+Use safe_join() instead of os.path.join() whenever a path component
+comes from user input (request parameters, uploaded filenames, etc.)
+to prevent directory traversal attacks.
+"""
+
+import os
+from typing import Final
+
+
+def safe_join(base_dir: str, *parts: str) -> str:
+ """
+ Join path components and verify the result stays within base_dir.
+
+ Resolves symlinks and '..' sequences, then checks the final path
+ is a descendant of base_dir. Raises ValueError if traversal is
+ detected.
+
+ Args:
+ base_dir: The trusted base directory.
+ *parts: User-controlled path components to append.
+
+ Returns:
+ The resolved absolute path as a string.
+
+ Raises:
+ ValueError: If the resolved path escapes base_dir.
+ """
+ for part in parts:
+ if "\x00" in part:
+ raise ValueError("Path contains null byte")
+ base: Final = os.path.realpath(base_dir)
+ resolved: Final = os.path.realpath(os.path.join(base, *parts))
+ if not (resolved.startswith(base + os.sep) or resolved == base):
+ raise ValueError(f"Path {resolved!r} escapes base directory {base!r}")
+ return resolved
+
+
+def try_safe_join(base_dir: str, *parts: str) -> str | None:
+ """safe_join, with None instead of ValueError when the path escapes base_dir."""
+ try:
+ return safe_join(base_dir, *parts)
+ except ValueError:
+ return None
+
+
+def is_within(path: str, base_dir: str) -> bool:
+ """True when path, with symlinks resolved, is base_dir or sits inside it."""
+ base: Final = os.path.realpath(base_dir)
+ resolved: Final = os.path.realpath(path)
+ return resolved.startswith(base + os.sep) or resolved == base
+
+
+def join_within(base_dir: str, *parts: str) -> str | None:
+ """Join without following symlinks; None when the joined path leaves base_dir.
+
+ Only the supplied components are checked (``..`` and absolute parts are
+ rejected), so a symlink stored inside base_dir that points elsewhere is
+ still returned. Use safe_join when the target itself must stay inside.
+ """
+ for part in parts:
+ if "\x00" in part:
+ return None
+ base: Final = os.path.normpath(os.path.abspath(base_dir))
+ joined: Final = os.path.normpath(os.path.join(base, *parts))
+ if not joined.startswith(base + os.sep):
+ return None
+ return joined
+
+
+def safe_filename(filename: str) -> str:
+ """
+ Extract a safe filename from a user-supplied path.
+
+ Strips all directory components (both Unix and Windows separators),
+ returning only the final name. Use this for uploaded file names
+ before writing to disk.
+
+ Args:
+ filename: User-supplied filename (may contain path separators).
+
+ Returns:
+ The basename only, with no directory components.
+
+ Raises:
+ ValueError: If the resulting filename is empty or contains null bytes.
+ """
+ if "\x00" in filename:
+ raise ValueError("Filename contains null byte")
+ # Normalize backslash separators for cross-platform safety
+ name: Final = filename.replace("\\", "/").rsplit("/", 1)[-1]
+ if not name or name in (".", ".."):
+ raise ValueError("Empty or unsafe filename")
+ return name
diff --git a/litellm/llms/base_llm/files/azure_blob_storage_backend.py b/litellm/llms/base_llm/files/azure_blob_storage_backend.py
index a192226110c..82ac92d5dcd 100644
--- a/litellm/llms/base_llm/files/azure_blob_storage_backend.py
+++ b/litellm/llms/base_llm/files/azure_blob_storage_backend.py
@@ -14,7 +14,7 @@ from urllib.parse import quote, urlparse
from litellm._logging import verbose_logger
from litellm._uuid import uuid
from litellm.integrations.azure_storage.azure_storage import AzureBlobStorageLogger
-from litellm.proxy.common_utils.path_utils import safe_filename
+from litellm.litellm_core_utils.path_utils import safe_filename
from .storage_backend import BaseFileStorageBackend
diff --git a/litellm/proxy/common_utils/path_utils.py b/litellm/proxy/common_utils/path_utils.py
index 3494a4c3fa0..9ec0136d544 100644
--- a/litellm/proxy/common_utils/path_utils.py
+++ b/litellm/proxy/common_utils/path_utils.py
@@ -1,96 +1,3 @@
-"""
-Safe filesystem path construction for user-controlled inputs.
+from litellm.litellm_core_utils.path_utils import is_within, join_within, safe_filename, safe_join, try_safe_join
-Use safe_join() instead of os.path.join() whenever a path component
-comes from user input (request parameters, uploaded filenames, etc.)
-to prevent directory traversal attacks.
-"""
-
-import os
-from typing import Final
-
-
-def safe_join(base_dir: str, *parts: str) -> str:
- """
- Join path components and verify the result stays within base_dir.
-
- Resolves symlinks and '..' sequences, then checks the final path
- is a descendant of base_dir. Raises ValueError if traversal is
- detected.
-
- Args:
- base_dir: The trusted base directory.
- *parts: User-controlled path components to append.
-
- Returns:
- The resolved absolute path as a string.
-
- Raises:
- ValueError: If the resolved path escapes base_dir.
- """
- for part in parts:
- if "\x00" in part:
- raise ValueError("Path contains null byte")
- base: Final = os.path.realpath(base_dir)
- resolved: Final = os.path.realpath(os.path.join(base, *parts))
- if not (resolved.startswith(base + os.sep) or resolved == base):
- raise ValueError(f"Path {resolved!r} escapes base directory {base!r}")
- return resolved
-
-
-def try_safe_join(base_dir: str, *parts: str) -> str | None:
- """safe_join, with None instead of ValueError when the path escapes base_dir."""
- try:
- return safe_join(base_dir, *parts)
- except ValueError:
- return None
-
-
-def is_within(path: str, base_dir: str) -> bool:
- """True when path, with symlinks resolved, is base_dir or sits inside it."""
- base: Final = os.path.realpath(base_dir)
- resolved: Final = os.path.realpath(path)
- return resolved.startswith(base + os.sep) or resolved == base
-
-
-def join_within(base_dir: str, *parts: str) -> str | None:
- """Join without following symlinks; None when the joined path leaves base_dir.
-
- Only the supplied components are checked (``..`` and absolute parts are
- rejected), so a symlink stored inside base_dir that points elsewhere is
- still returned. Use safe_join when the target itself must stay inside.
- """
- for part in parts:
- if "\x00" in part:
- return None
- base: Final = os.path.normpath(os.path.abspath(base_dir))
- joined: Final = os.path.normpath(os.path.join(base, *parts))
- if not joined.startswith(base + os.sep):
- return None
- return joined
-
-
-def safe_filename(filename: str) -> str:
- """
- Extract a safe filename from a user-supplied path.
-
- Strips all directory components (both Unix and Windows separators),
- returning only the final name. Use this for uploaded file names
- before writing to disk.
-
- Args:
- filename: User-supplied filename (may contain path separators).
-
- Returns:
- The basename only, with no directory components.
-
- Raises:
- ValueError: If the resulting filename is empty or contains null bytes.
- """
- if "\x00" in filename:
- raise ValueError("Filename contains null byte")
- # Normalize backslash separators for cross-platform safety
- name: Final = filename.replace("\\", "/").rsplit("/", 1)[-1]
- if not name or name in (".", ".."):
- raise ValueError("Empty or unsafe filename")
- return name
+__all__ = ("is_within", "join_within", "safe_filename", "safe_join", "try_safe_join")
diff --git a/tests/unit/proxy/common_utils/test_path_utils.py b/tests/unit/litellm_core_utils/test_path_utils.py
similarity index 98%
rename from tests/unit/proxy/common_utils/test_path_utils.py
rename to tests/unit/litellm_core_utils/test_path_utils.py
index 8cf1ef6467b..480a6de2b08 100644
--- a/tests/unit/proxy/common_utils/test_path_utils.py
+++ b/tests/unit/litellm_core_utils/test_path_utils.py
@@ -2,7 +2,7 @@ import os
import pytest
-from litellm.proxy.common_utils.path_utils import is_within, join_within, safe_filename, safe_join, try_safe_join
+from litellm.litellm_core_utils.path_utils import is_within, join_within, safe_filename, safe_join, try_safe_join
class TestSafeJoin: