Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 9 additions & 4 deletions litellm/integrations/gcs_bucket/gcs_bucket.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,14 @@
from litellm._uuid import uuid
from datetime import datetime, timedelta, timezone
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple
from urllib.parse import quote

from litellm._logging import verbose_logger
from litellm.constants import LITELLM_ASYNCIO_QUEUE_MAXSIZE
from litellm.integrations.additional_logging_utils import AdditionalLoggingUtils
from litellm.integrations.gcs_bucket.gcs_bucket_base import GCSBucketBase
from litellm.litellm_core_utils.cloud_storage_security import (
sanitize_cloud_object_component,
)
from litellm.proxy._types import CommonProxyErrors
from litellm.types.integrations.base_health_check import IntegrationHealthCheckStatus
from litellm.types.integrations.gcs_bucket import *
Expand Down Expand Up @@ -335,7 +337,11 @@ def _get_object_name(
_litellm_params = kwargs.get("litellm_params", None) or {}
_metadata = _litellm_params.get("metadata", None) or {}
if "gcs_log_id" in _metadata:
object_name = _metadata["gcs_log_id"]
safe_log_id = sanitize_cloud_object_component(
_metadata.get("gcs_log_id"), fallback=""
)
if safe_log_id:
object_name = f"{current_date}/custom-{uuid.uuid4().hex}-{safe_log_id}"
Comment on lines 339 to +344

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Backwards-incompatible gcs_log_id behavior change without a feature flag

Previously gcs_log_id in metadata was used as the exact GCS object path. This PR changes it to a sanitized hint incorporated into a new randomized path ({date}/custom-{uuid}-{safe_hint}). Any deployment that reads GCS log objects by a predictable gcs_log_id-derived path (e.g., external tooling, dashboards, or audit pipelines that construct GCS paths from known gcs_log_id values) will silently stop finding those objects after this change.

Per the project's backwards-compatibility rule, breaking behavior changes should be gated behind a server-side flag (e.g. litellm.enforce_safe_gcs_log_paths or an env var), so existing deployments can opt in on their own schedule. The analogous file retrieval path has allow_legacy_cloud_file_ids for exactly this reason.

Rule Used: What: avoid backwards-incompatible changes without... (source)


return object_name

Expand Down Expand Up @@ -367,8 +373,7 @@ async def get_request_response_payload(
request_date_str=date_str,
response_id=request_id,
)
encoded_object_name = quote(object_name, safe="")
response = await self.download_gcs_object(encoded_object_name)
response = await self.download_gcs_object(object_name)

if response is not None:
loaded_response = json.loads(response)
Expand Down
13 changes: 10 additions & 3 deletions litellm/integrations/gcs_bucket/gcs_bucket_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@

from litellm._logging import verbose_logger
from litellm.integrations.custom_batch_logger import CustomBatchLogger
from litellm.litellm_core_utils.cloud_storage_security import (
encode_gcs_object_name_for_url,
split_configured_cloud_bucket_name,
)
from litellm.llms.custom_httpx.http_handler import (
get_async_httpx_client,
httpxSpecialProvider,
Expand Down Expand Up @@ -133,8 +137,8 @@ def _handle_folders_in_bucket_name(
- Returns: bucket_name="my-bucket", object_name="my-folder/dev/my-object"

"""
if "/" in bucket_name:
bucket_name, prefix = bucket_name.split("/", 1)
bucket_name, prefix = split_configured_cloud_bucket_name(bucket_name)
if prefix:
object_name = f"{prefix}/{object_name}"
return bucket_name, object_name
return bucket_name, object_name
Expand Down Expand Up @@ -248,6 +252,7 @@ async def download_gcs_object(self, object_name: str, **kwargs):
bucket_name=bucket_name,
object_name=object_name,
)
object_name = encode_gcs_object_name_for_url(object_name)

url = f"https://storage.googleapis.com/storage/v1/b/{bucket_name}/o/{object_name}?alt=media"

Expand Down Expand Up @@ -288,6 +293,7 @@ async def delete_gcs_object(self, object_name: str, **kwargs):
bucket_name=bucket_name,
object_name=object_name,
)
object_name = encode_gcs_object_name_for_url(object_name)

url = f"https://storage.googleapis.com/storage/v1/b/{bucket_name}/o/{object_name}"

Expand Down Expand Up @@ -334,10 +340,11 @@ async def _log_json_data_on_gcs(
bucket_name=bucket_name,
object_name=object_name,
)
encoded_object_name = encode_gcs_object_name_for_url(object_name)

response = await self.async_httpx_client.post(
headers=headers,
url=f"https://storage.googleapis.com/upload/storage/v1/b/{bucket_name}/o?uploadType=media&name={object_name}",
url=f"https://storage.googleapis.com/upload/storage/v1/b/{bucket_name}/o?uploadType=media&name={encoded_object_name}",
data=json_logged_payload,
)

Expand Down
143 changes: 143 additions & 0 deletions litellm/litellm_core_utils/cloud_storage_security.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
import posixpath
import re
from typing import Optional, Sequence, Tuple
from urllib.parse import quote, unquote

from litellm._uuid import uuid

VERTEX_AI_MANAGED_GCS_PREFIX = "litellm-vertex-files/"
BEDROCK_MANAGED_S3_BATCH_PREFIX = "litellm-bedrock-files-"
BEDROCK_MANAGED_S3_UPLOAD_PREFIX = "litellm-bedrock-files/"
BEDROCK_MANAGED_S3_OUTPUT_PREFIX = "litellm-batch-outputs/"
BEDROCK_MANAGED_S3_PREFIXES = (
BEDROCK_MANAGED_S3_BATCH_PREFIX,
BEDROCK_MANAGED_S3_UPLOAD_PREFIX,
BEDROCK_MANAGED_S3_OUTPUT_PREFIX,
)

_SAFE_OBJECT_COMPONENT_PATTERN = re.compile(r"[^A-Za-z0-9._-]+")


def sanitize_cloud_object_component(
value: Optional[str], fallback: str = "file"
) -> str:
if not isinstance(value, str):
return fallback

component = posixpath.basename(value.replace("\\", "/")).strip()
if component in {"", ".", ".."}:
return fallback

component = "".join(
"_" if ord(char) < 32 or ord(char) == 127 else char for char in component
)
component = _SAFE_OBJECT_COMPONENT_PATTERN.sub("_", component)
component = component.strip("._")
if not component:
return fallback
return component[:255]


def sanitize_cloud_object_path(value: Optional[str], fallback: str = "file") -> str:
if not isinstance(value, str):
return fallback

segments = []
for segment in value.replace("\\", "/").split("/"):
sanitized_segment = sanitize_cloud_object_component(segment, fallback="")
if sanitized_segment:
segments.append(sanitized_segment)

if not segments:
return fallback
return "/".join(segments)


def build_managed_cloud_object_name(
prefix: str, filename: Optional[str], fallback_filename: str = "file"
) -> str:
safe_filename = sanitize_cloud_object_component(
filename, fallback=fallback_filename
)
return f"{prefix}{uuid.uuid4().hex}-{safe_filename}"


def _validate_cloud_object_path(object_name: str) -> None:
if not object_name:
raise ValueError("Cloud storage object name is required")
if object_name.startswith("/"):
raise ValueError("Cloud storage object name must be relative")
if any(ord(char) < 32 or ord(char) == 127 for char in object_name):
raise ValueError("Cloud storage object name contains control characters")
segments = object_name.split("/")
if any(segment in {".", ".."} for segment in segments):
raise ValueError("Cloud storage object name contains an invalid path segment")
if "" in segments[:-1]:
raise ValueError("Cloud storage object name contains an invalid path segment")


def split_configured_cloud_bucket_name(bucket_name: str) -> Tuple[str, str]:
if not isinstance(bucket_name, str) or not bucket_name.strip():
raise ValueError("Cloud storage bucket name is required")

bucket_name = bucket_name.strip()
if "://" in bucket_name or "?" in bucket_name or "#" in bucket_name:
raise ValueError(
"Cloud storage bucket name must not include a URI scheme or query"
)
if any(ord(char) < 32 or ord(char) == 127 for char in bucket_name):
raise ValueError("Cloud storage bucket name contains control characters")

bucket, _, prefix = bucket_name.partition("/")
if not bucket:
raise ValueError("Cloud storage bucket name is required")
if "\\" in bucket:
raise ValueError("Cloud storage bucket name contains an invalid separator")

prefix = prefix.strip("/")
if prefix:
_validate_cloud_object_path(prefix)

return bucket, prefix


def encode_gcs_object_name_for_url(object_name: str) -> str:
return quote(unquote(object_name), safe="")


def encode_s3_object_key_for_url(object_key: str) -> str:
return quote(unquote(object_key), safe="/")


def validate_managed_cloud_file_id(
file_id: str,
scheme: str,
configured_bucket_name: str,
allowed_object_prefixes: Sequence[str],
) -> Tuple[str, str]:
decoded_file_id = unquote(file_id)
if not decoded_file_id.startswith(scheme):
raise ValueError(f"file_id must be a {scheme} URI")

full_path = decoded_file_id[len(scheme) :]
if "/" not in full_path:
raise ValueError("file_id must include a cloud storage object name")

bucket_name, object_name = full_path.split("/", 1)
configured_bucket, configured_prefix = split_configured_cloud_bucket_name(
configured_bucket_name
)
if bucket_name != configured_bucket:
raise ValueError("file_id bucket does not match the configured storage bucket")

_validate_cloud_object_path(object_name)
allowed_prefixes = tuple(allowed_object_prefixes)
if configured_prefix:
allowed_prefixes = tuple(
f"{configured_prefix.rstrip('/')}/{prefix}" for prefix in allowed_prefixes
)

if not object_name.startswith(allowed_prefixes):
raise ValueError("file_id must reference a LiteLLM-managed storage object")

return bucket_name, object_name
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,11 @@ def validate_no_callback_env_reference(
"lunary_public_key",
]

_request_blocked_callback_params = {
"gcs_bucket_name",
"gcs_path_service_account",
}
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved


def initialize_standard_callback_dynamic_params(
kwargs: Optional[Dict] = None,
Expand All @@ -71,6 +76,8 @@ def initialize_standard_callback_dynamic_params(
if kwargs:
# 1. Check top-level kwargs
for param in _supported_callback_params:
if param in _request_blocked_callback_params:
continue
if param in kwargs:
_param_value = kwargs.get(param)
validate_no_callback_env_reference(
Expand All @@ -86,6 +93,8 @@ def initialize_standard_callback_dynamic_params(

if isinstance(metadata, dict):
for param in _supported_callback_params:
if param in _request_blocked_callback_params:
continue
if param not in standard_callback_dynamic_params and param in metadata:
_param_value = metadata.get(param)
validate_no_callback_env_reference(
Expand Down
48 changes: 29 additions & 19 deletions litellm/llms/bedrock/files/handler.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
import asyncio
import base64
import os
from typing import Any, Coroutine, Optional, Tuple, Union

import httpx

from litellm import LlmProviders
from litellm.litellm_core_utils.cloud_storage_security import (
BEDROCK_MANAGED_S3_PREFIXES,
validate_managed_cloud_file_id,
)
from litellm.llms.custom_httpx.http_handler import get_async_httpx_client
from litellm.types.llms.openai import (
FileContentRequest,
Expand Down Expand Up @@ -35,7 +40,7 @@ def _extract_s3_uri_from_file_id(self, file_id: str) -> str:

The file ID can be in two formats:
1. Base64-encoded unified file ID containing: llm_output_file_id,s3://bucket/path
2. Direct S3 URI: s3://bucket/path
2. Direct S3 URI: s3://bucket/litellm-managed-prefix/path

Args:
file_id: Encoded file ID or direct S3 URI
Expand All @@ -58,14 +63,16 @@ def _extract_s3_uri_from_file_id(self, file_id: str) -> str:
except Exception:
pass

# If not base64 encoded or doesn't contain llm_output_file_id, assume it's already an S3 URI
# If not base64 encoded or doesn't contain llm_output_file_id, accept only
# explicit S3 URIs. Bucket and key validation happens before any S3 call.
if file_id.startswith("s3://"):
return file_id

# If it doesn't start with s3://, assume it's a direct S3 URI and add the prefix
return f"s3://{file_id}"
raise ValueError("file_id must be a managed LiteLLM S3 file id")

def _parse_s3_uri(self, s3_uri: str) -> Tuple[str, str]:
def _parse_s3_uri(
self, s3_uri: str, configured_bucket_name: str
) -> Tuple[str, str]:
"""
Parse S3 URI to extract bucket name and object key.

Expand All @@ -75,21 +82,20 @@ def _parse_s3_uri(self, s3_uri: str) -> Tuple[str, str]:
Returns:
Tuple of (bucket_name, object_key)
"""
if not s3_uri.startswith("s3://"):
return validate_managed_cloud_file_id(
file_id=s3_uri,
scheme="s3://",
configured_bucket_name=configured_bucket_name,
allowed_object_prefixes=BEDROCK_MANAGED_S3_PREFIXES,
)

def _get_configured_s3_bucket_name(self, optional_params: dict) -> str:
bucket_name = os.getenv("AWS_S3_BUCKET_NAME")
if not bucket_name:
raise ValueError(
f"Invalid S3 URI format: {s3_uri}. Expected format: s3://bucket-name/path/to/file"
"S3 bucket_name is required. Set AWS_S3_BUCKET_NAME for Bedrock file content retrieval."
)

# Remove 's3://' prefix
path = s3_uri[5:]

if "/" in path:
bucket_name, object_key = path.split("/", 1)
else:
bucket_name = path
object_key = ""

return bucket_name, object_key
return bucket_name
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved

async def afile_content(
self,
Expand Down Expand Up @@ -119,7 +125,11 @@ async def afile_content(

# Extract S3 URI from file ID
s3_uri = self._extract_s3_uri_from_file_id(file_id)
bucket_name, object_key = self._parse_s3_uri(s3_uri)
configured_bucket_name = self._get_configured_s3_bucket_name(optional_params)
bucket_name, object_key = self._parse_s3_uri(
s3_uri=s3_uri,
configured_bucket_name=configured_bucket_name,
)

# Get AWS credentials
aws_region_name = self._get_aws_region_name(
Expand Down
Loading
Loading