Reject oversized media before fully downloading it (#51896)

Signed-off-by: Clinton Thomas <1033162+KernelClint@users.noreply.github.com>
Co-authored-by: Lucas Bourtoule <35483370+dhalf@users.noreply.github.com>
This commit is contained in:
Clinton Thomas
2026-08-24 01:15:09 +00:00
committed by GitHub
co-authored by Lucas Bourtoule
parent 585bb07c70
commit 2ec6f0d71e
13 changed files with 718 additions and 24 deletions
+140 -5
View File
@@ -13,7 +13,9 @@ import requests
from urllib3.util import parse_url
import vllm.envs as envs
from vllm.exceptions import VLLMValidationError
from vllm.logger import init_logger
from vllm.utils.mem_constants import KiB_bytes, MiB_bytes
from vllm.version import __version__ as VLLM_VERSION
logger = init_logger(__name__)
@@ -25,6 +27,128 @@ _T = TypeVar("_T")
# Attempt N uses: base_timeout * (_RETRY_BACKOFF_FACTOR ** N) for the
# per-attempt timeout and sleeps _RETRY_BACKOFF_FACTOR ** N seconds.
_RETRY_BACKOFF_FACTOR = 4
_RESPONSE_READ_CHUNK_SIZE = 64 * KiB_bytes
class HTTPResponseSizeExceededError(VLLMValidationError):
"""Raised when an HTTP response exceeds a caller-supplied byte ceiling."""
def __init__(self, max_bytes: int, received_bytes: int) -> None:
self.max_bytes = max_bytes
self.received_bytes = received_bytes
super().__init__(
"Maximum file size exceeded: HTTP response exceeded maximum size "
f"of {max_bytes} bytes (received at least {received_bytes} bytes)",
parameter="audio_filesize_mb",
value=received_bytes / MiB_bytes,
)
class MediaDownloadSizeExceededError(ValueError):
"""Raised when a remote media download exceeds the configured byte limit."""
def __init__(self, max_bytes: int, received_bytes: int | None = None) -> None:
self.max_bytes = max_bytes
self.received_bytes = received_bytes
max_size_mb = max_bytes / MiB_bytes
message = (
"Remote media download exceeds "
f"VLLM_MAX_MEDIA_DOWNLOAD_SIZE_MB={max_size_mb:g}"
)
if received_bytes is not None:
message += f" (received at least {received_bytes} bytes)"
super().__init__(message)
def _get_media_download_limit_bytes() -> int | None:
max_size_mb = envs.VLLM_MAX_MEDIA_DOWNLOAD_SIZE_MB
if max_size_mb <= 0:
return None
return max_size_mb * MiB_bytes
def _get_response_size_limit(max_bytes: int | None) -> tuple[int | None, bool]:
media_max_bytes = _get_media_download_limit_bytes()
if media_max_bytes is not None and (
max_bytes is None or media_max_bytes <= max_bytes
):
return media_max_bytes, True
return max_bytes, False
def _raise_size_exceeded(
max_bytes: int, received_bytes: int, media_download_limit: bool
) -> None:
if media_download_limit:
raise MediaDownloadSizeExceededError(max_bytes, received_bytes)
raise HTTPResponseSizeExceededError(max_bytes, received_bytes)
def _check_content_length(
content_length: str | int | None,
max_bytes: int | None,
media_download_limit: bool,
) -> None:
if content_length is None or max_bytes is None:
return
try:
parsed_length = int(content_length)
except (TypeError, ValueError):
return
if parsed_length > max_bytes:
_raise_size_exceeded(max_bytes, parsed_length, media_download_limit)
def _append_chunk(
chunks: list[bytes],
chunk: bytes,
received_bytes: int,
max_bytes: int | None,
media_download_limit: bool,
) -> int:
if not chunk:
return received_bytes
received_bytes += len(chunk)
if max_bytes is not None and received_bytes > max_bytes:
_raise_size_exceeded(max_bytes, received_bytes, media_download_limit)
chunks.append(chunk)
return received_bytes
def _read_response_bytes(response: requests.Response, max_bytes: int | None) -> bytes:
max_bytes, media_download_limit = _get_response_size_limit(max_bytes)
if max_bytes is None:
return response.content
_check_content_length(
response.headers.get("Content-Length"),
max_bytes,
media_download_limit,
)
chunks: list[bytes] = []
received_bytes = 0
for chunk in response.iter_content(_RESPONSE_READ_CHUNK_SIZE):
received_bytes = _append_chunk(
chunks, chunk, received_bytes, max_bytes, media_download_limit
)
return b"".join(chunks)
async def _async_read_response_bytes(
response: aiohttp.ClientResponse, max_bytes: int | None
) -> bytes:
max_bytes, media_download_limit = _get_response_size_limit(max_bytes)
if max_bytes is None:
return await response.read()
_check_content_length(response.content_length, max_bytes, media_download_limit)
chunks: list[bytes] = []
received_bytes = 0
async for chunk in response.content.iter_chunked(_RESPONSE_READ_CHUNK_SIZE):
received_bytes = _append_chunk(
chunks, chunk, received_bytes, max_bytes, media_download_limit
)
return b"".join(chunks)
def _is_retryable(exc: Exception) -> bool:
@@ -277,14 +401,22 @@ class HTTPConnection:
@_sync_retry
def get_bytes(
self, url: str, *, timeout: float | None = None, allow_redirects: bool = True
self,
url: str,
*,
timeout: float | None = None,
allow_redirects: bool = True,
max_bytes: int | None = None,
) -> bytes:
with self.get_response(
url, timeout=timeout, allow_redirects=allow_redirects
url,
stream=True,
timeout=timeout,
allow_redirects=allow_redirects,
) as r:
r.raise_for_status()
return r.content
return _read_response_bytes(r, max_bytes)
@_async_retry
async def async_get_bytes(
@@ -293,13 +425,16 @@ class HTTPConnection:
*,
timeout: float | None = None,
allow_redirects: bool = True,
max_bytes: int | None = None,
) -> bytes:
async with await self.get_async_response(
url, timeout=timeout, allow_redirects=allow_redirects
url,
timeout=timeout,
allow_redirects=allow_redirects,
) as r:
r.raise_for_status()
return await r.read()
return await _async_read_response_bytes(r, max_bytes)
def get_text(self, url: str, *, timeout: float | None = None) -> str:
with self.get_response(url, timeout=timeout) as r:
+26 -5
View File
@@ -10,7 +10,7 @@ from argparse import Namespace
from collections.abc import Awaitable, Callable
from http import HTTPStatus
from io import BytesIO, StringIO
from typing import Any, TypeAlias
from typing import Any, NoReturn, TypeAlias
from urllib.parse import urlparse
import aiohttp
@@ -28,7 +28,7 @@ from urllib3.util import parse_url
import vllm.envs as envs
from vllm.config import config
from vllm.connections import global_http_connection
from vllm.connections import HTTPResponseSizeExceededError, global_http_connection
from vllm.engine.arg_utils import AsyncEngineArgs
from vllm.engine.protocol import EngineClient
from vllm.entrypoints.launchers.api_server.entry import init_app_state
@@ -68,11 +68,24 @@ from vllm.logger import init_logger
from vllm.reasoning import ReasoningParserManager
from vllm.utils import random_uuid
from vllm.utils.argparse_utils import FlexibleArgumentParser
from vllm.utils.mem_constants import MiB_bytes
from vllm.version import __version__ as VLLM_VERSION
logger = init_logger(__name__)
def _get_audio_download_limit_bytes() -> int:
return int(envs.VLLM_MAX_AUDIO_CLIP_FILESIZE_MB * MiB_bytes)
def _raise_audio_filesize_limit(size_bytes: int) -> NoReturn:
raise VLLMValidationError(
"Maximum file size exceeded",
parameter="audio_filesize_mb",
value=size_bytes / MiB_bytes,
)
class BatchTranscriptionRequest(TranscriptionRequest):
"""
Batch transcription request that uses file_url instead of file.
@@ -474,6 +487,9 @@ async def download_bytes_from_url(
if "," in url:
header, data = url.split(",", 1)
if "base64" in header:
decoded_size_bytes = len(data.rstrip("=")) * 3 // 4
if decoded_size_bytes > _get_audio_download_limit_bytes():
_raise_audio_filesize_limit(decoded_size_bytes)
return base64.b64decode(data)
else:
raise VLLMValidationError(
@@ -502,9 +518,14 @@ async def download_bytes_from_url(
# between urllib3 and aiohttp (e.g. backslash-@ attacks).
url = url_spec.url
return await global_http_connection.async_get_bytes(
url, allow_redirects=envs.VLLM_MEDIA_URL_ALLOW_REDIRECTS
)
try:
return await global_http_connection.async_get_bytes(
url,
allow_redirects=envs.VLLM_MEDIA_URL_ALLOW_REDIRECTS,
max_bytes=_get_audio_download_limit_bytes(),
)
except HTTPResponseSizeExceededError as exc:
_raise_audio_filesize_limit(exc.received_bytes)
else:
raise VLLMValidationError(
@@ -124,7 +124,6 @@ class SpeechToTextBaseServing(GenerateBaseServing):
self.enable_force_include_usage = enable_force_include_usage
self.max_audio_filesize_mb = envs.VLLM_MAX_AUDIO_CLIP_FILESIZE_MB
self.max_audio_decode_duration_s: int = envs.VLLM_MAX_AUDIO_DECODE_DURATION_S
self.max_audio_decode_bytes: int = envs.VLLM_MAX_AUDIO_DECODE_BYTES
if self.model_cls.supports_segment_timestamp:
@@ -274,13 +273,6 @@ class SpeechToTextBaseServing(GenerateBaseServing):
else None
)
if len(audio_data) / 1024**2 > self.max_audio_filesize_mb:
raise VLLMValidationError(
"Maximum file size exceeded",
parameter="audio_filesize_mb",
value=len(audio_data) / 1024**2,
)
# Run cpu intensive preprocess step in a separate thread pool executor.
chunks, duration = await self._decode_and_chunk_speech_async(audio_data)
+7
View File
@@ -75,6 +75,7 @@ if TYPE_CHECKING:
VLLM_MEDIA_CACHE_MAX_SIZE_MB: int = 5120
VLLM_MEDIA_CACHE_TTL_HOURS: float = 24
VLLM_MEDIA_FETCH_MAX_RETRIES: int = 3
VLLM_MAX_MEDIA_DOWNLOAD_SIZE_MB: int = 256
VLLM_MEDIA_URL_ALLOW_REDIRECTS: bool = True
VLLM_MEDIA_LOADING_THREAD_COUNT: int = 8
VLLM_MAX_AUDIO_CLIP_FILESIZE_MB: int = 25
@@ -988,6 +989,12 @@ environment_variables: dict[str, Callable[[], Any]] = {
"VLLM_MEDIA_FETCH_MAX_RETRIES": lambda: int(
os.getenv("VLLM_MEDIA_FETCH_MAX_RETRIES", "3")
),
# Maximum size in MB for a single remote media download. The limit is
# enforced while streaming the response body so oversized or infinite
# responses cannot grow the API server heap without bound. Default is 256.
"VLLM_MAX_MEDIA_DOWNLOAD_SIZE_MB": lambda: int(
os.getenv("VLLM_MAX_MEDIA_DOWNLOAD_SIZE_MB", "256")
),
# Whether to allow HTTP redirects when fetching from media URLs.
# Default to True
"VLLM_MEDIA_URL_ALLOW_REDIRECTS": lambda: bool(
+21
View File
@@ -10,6 +10,7 @@ import pybase64
import torch
import vllm.envs as envs
from vllm.exceptions import VLLMValidationError
from vllm.logger import init_logger
from vllm.multimodal.audio import resample_audio_pyav
from vllm.utils.import_utils import PlaceholderModule
@@ -275,7 +276,20 @@ class AudioMediaIO(MediaIO[tuple[npt.NDArray, float]]):
# for flexible control.
self.kwargs = kwargs
def get_max_bytes(self) -> int:
return int(envs.VLLM_MAX_AUDIO_CLIP_FILESIZE_MB * MiB_bytes)
def _validate_encoded_size(self, size: int) -> None:
max_bytes = self.get_max_bytes()
if size > max_bytes:
raise VLLMValidationError(
"Maximum file size exceeded",
parameter="audio_filesize_mb",
value=size / MiB_bytes,
)
def load_bytes(self, data: bytes) -> tuple[npt.NDArray, float]:
self._validate_encoded_size(len(data))
return load_audio(
BytesIO(data),
sr=None,
@@ -288,6 +302,13 @@ class AudioMediaIO(MediaIO[tuple[npt.NDArray, float]]):
media_type: str,
data: str,
) -> tuple[npt.NDArray, float]:
max_encoded_chars = 4 * ((self.get_max_bytes() + 2) // 3)
if len(data) > max_encoded_chars:
raise VLLMValidationError(
"Maximum file size exceeded",
parameter="audio_filesize_mb",
value=(len(data) * 3 / 4) / MiB_bytes,
)
return self.load_bytes(pybase64.b64decode(data))
def load_file(self, filepath: Path) -> tuple[npt.NDArray, float]:
+4
View File
@@ -79,6 +79,10 @@ class MediaIO(ABC, Generic[_T]):
merged.update(runtime_kwargs)
return merged
def get_max_bytes(self) -> int | None:
"""Return the maximum encoded payload size accepted by this media IO."""
return None
@abstractmethod
def load_bytes(self, data: bytes) -> _T:
raise NotImplementedError
+20 -2
View File
@@ -22,8 +22,12 @@ from PIL import Image, UnidentifiedImageError
from urllib3.util import Url, parse_url
import vllm.envs as envs
from vllm.connections import HTTPConnection, global_http_connection
from vllm.exceptions import VLLMUnprocessableEntityError
from vllm.connections import (
HTTPConnection,
MediaDownloadSizeExceededError,
global_http_connection,
)
from vllm.exceptions import VLLMUnprocessableEntityError, VLLMValidationError
from vllm.logger import init_logger
from vllm.multimodal.video import get_video_loader_backend_for_processor
from vllm.utils.registry import ExtensionManager
@@ -70,6 +74,9 @@ def _wrap_media_fetch_error(
Original exception for transient errors (5xx, 408, 429, network blips)
or other exceptions
"""
if isinstance(exc, VLLMValidationError):
return exc
if isinstance(exc, aiohttp.ClientResponseError):
if exc.status in (408, 429):
return exc
@@ -101,6 +108,13 @@ def _wrap_media_fetch_error(
value=url,
)
if isinstance(exc, MediaDownloadSizeExceededError):
return VLLMUnprocessableEntityError(
f"Failed to fetch media from URL: {exc}",
parameter="image_url",
value=url,
)
if isinstance(exc, ValueError):
return VLLMUnprocessableEntityError(
"Failed to fetch media from URL: Invalid URL",
@@ -363,6 +377,7 @@ class MediaConnector:
if url_spec.scheme and url_spec.scheme.startswith("http"):
self._assert_url_in_allowed_media_domains(url_spec)
max_bytes = media_io.get_max_bytes()
cached = self._get_cached_bytes(url)
if cached is not None:
@@ -374,6 +389,7 @@ class MediaConnector:
url_spec.url,
timeout=fetch_timeout,
allow_redirects=envs.VLLM_MEDIA_URL_ALLOW_REDIRECTS,
max_bytes=max_bytes,
)
except Exception as e:
wrapped = _wrap_media_fetch_error(url, e)
@@ -409,6 +425,7 @@ class MediaConnector:
if url_spec.scheme and url_spec.scheme.startswith("http"):
self._assert_url_in_allowed_media_domains(url_spec)
max_bytes = media_io.get_max_bytes()
cached = await loop.run_in_executor(
global_thread_pool, self._get_cached_bytes, url
@@ -425,6 +442,7 @@ class MediaConnector:
url_spec.url,
timeout=fetch_timeout,
allow_redirects=envs.VLLM_MEDIA_URL_ALLOW_REDIRECTS,
max_bytes=max_bytes,
)
except Exception as e:
wrapped = _wrap_media_fetch_error(url, e)