[Frontend] Consolidate entrypoint exception handler (#52261)

Signed-off-by: wang.yuqi <yuqi.wang@daocloud.io>
This commit is contained in:
wang.yuqi
2026-08-14 09:27:24 +00:00
committed by GitHub
parent 103c419f04
commit b8165e5e58
31 changed files with 418 additions and 343 deletions
@@ -0,0 +1,134 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Tests that error messages in Anthropic and speech-to-text entrypoints
are sanitized to prevent memory address leakage.
Verifies the fix for the incomplete CVE-2026-22778 remediation where
PIL repr addresses leaked via the Anthropic API router and the
speech-to-text WebSocket paths.
"""
import pytest
from vllm.entrypoints.serve.exception_handling.utils import sanitize_message
def test_sanitize_message():
assert (
sanitize_message("<_io.BytesIO object at 0x7a95e299e750>")
== "<_io.BytesIO object>"
)
class TestSanitizeMessageFilePaths:
"""sanitize_message should also strip file paths and traceback
frames, not just memory addresses - see #31683."""
def test_strips_traceback_style_frame(self):
msg = (
"1 validation error:\n"
" {'type': 'list_type', 'loc': ('body', 'messages')}\n"
'\n File "/usr/local/lib/python3.12/dist-packages/vllm/'
'entrypoints/serve/utils/api_utils.py", line 40, '
"in create_chat_completion\n"
" POST /v1/chat/completions"
)
result = sanitize_message(msg)
assert "/usr/local/" not in result
assert "api_utils.py" not in result
assert "list_type" in result
def test_strips_arbitrary_absolute_path(self):
result = sanitize_message("Error in /home/user/project/vllm/server.py")
assert "/home/user" not in result
def test_strips_single_parent_container_path(self):
"""Regression: /app/server.py and /workspace/server.py (common in
container deployments) were missed by the original {2,} quantifier."""
assert "/app/" not in sanitize_message("Error in /app/server.py")
assert "/workspace/" not in sanitize_message("Error in /workspace/server.py")
def test_preserves_api_endpoint_paths(self):
msg = "POST /v1/chat/completions failed"
assert "/v1/chat/completions" in sanitize_message(msg)
def test_preserves_short_field_references(self):
msg = "Invalid value for field 'body.messages'"
assert sanitize_message(msg) == msg
def test_strips_both_address_and_path(self):
msg = (
"<Request at 0x7f123> failed at "
"/usr/local/lib/python3.12/dist-packages/vllm/server.py"
)
result = sanitize_message(msg)
assert "0x" not in result
assert "/usr/local/" not in result
class TestSanitizeMessageCoversLeakPatterns:
"""Ensure sanitize_message strips addresses from realistic exceptions."""
@pytest.mark.parametrize(
("raw", "expected"),
[
(
"cannot identify image file <_io.BytesIO object at 0x7a95e299e750>",
"cannot identify image file <_io.BytesIO object>",
),
(
"cannot identify image file <_io.BytesIO object at 0x7f3c1a2b4d90>",
"cannot identify image file <_io.BytesIO object>",
),
(
"<PIL.PngImagePlugin.PngImageFile image mode=RGB "
"size=8x8 at 0x7f3c1a2b4d90>",
"<PIL.PngImagePlugin.PngImageFile image mode=RGB size=8x8>",
),
(
"Error processing <_io.BytesIO object at 0xdeadbeef>: invalid header",
"Error processing <_io.BytesIO object>: invalid header",
),
],
ids=[
"bytesio-standard",
"bytesio-different-addr",
"pil-image-repr",
"mid-string-repr",
],
)
def test_address_stripped(self, raw: str, expected: str):
assert sanitize_message(raw) == expected
def test_safe_message_unchanged(self):
msg = "Invalid request: missing 'messages' field"
assert sanitize_message(msg) == msg
def test_multiple_addresses_stripped(self):
raw = "<obj at 0xaaa> and <obj at 0xbbb>"
result = sanitize_message(raw)
assert "0x" not in result
class TestAffectedModulesUseSanitize:
"""Verify that affected modules call sanitize_message (source-level)."""
@pytest.mark.parametrize(
"module",
[
"vllm.entrypoints.anthropic.api_router",
"vllm.entrypoints.anthropic.serving",
"vllm.entrypoints.speech_to_text.realtime.connection",
],
)
def test_module_calls_sanitize_message(self, module: str):
import importlib.util
from pathlib import Path
spec = importlib.util.find_spec(module)
assert spec is not None and spec.origin is not None, (
f"Cannot locate module {module}"
)
source = Path(spec.origin).read_text()
assert "sanitize_message" in source, f"{module} does not call sanitize_message"
assert "import" in source and "sanitize_message" in source
@@ -0,0 +1,222 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Test that http_requests_total metric records correct status codes.
Regression test for: Prometheus http_requests_total records 4xx exceptions
(ValueError, TypeError, etc.) as 5xx because they propagate through the
PrometheusInstrumentatorMiddleware before being caught by ServerErrorMiddleware.
"""
from argparse import Namespace
import httpx
import pytest
from fastapi import HTTPException
from prometheus_client import CollectorRegistry
from vllm.entrypoints.openai.api_server import build_app
from vllm.exceptions import (
VLLMNotFoundError,
VLLMServerError,
VLLMValidationError,
)
@pytest.fixture(scope="module")
def should_do_global_cleanup_after_test() -> bool:
# This suite never initializes distributed/accelerator state.
return False
def _build_args() -> Namespace:
"""Minimal args for ``build_app``; avoids ``make_arg_parser`` device probing."""
return Namespace(
disable_fastapi_docs=True,
enable_offline_docs=False,
root_path=None,
allowed_origins=["*"],
allow_credentials=False,
allowed_methods=["*"],
allowed_headers=["*"],
api_key=None,
enable_request_id_headers=False,
enable_fault_tolerance=False,
middleware=[],
log_error_stack=False,
)
@pytest.fixture(scope="module")
def registry():
"""Shared Prometheus registry for the module-scoped app."""
return CollectorRegistry()
@pytest.fixture(scope="module")
def app(registry):
"""Build the real vLLM FastAPI app once and attach probe routes that raise.
Patch the name used by ``attach_router`` (imported into the instrumentator
metrics module), not ``vllm.v1.metrics.prometheus`` alone — that binding is
captured at import time.
"""
import vllm.entrypoints.serve.instrumentator.metrics as metrics_mod
original = metrics_mod.get_prometheus_registry
metrics_mod.get_prometheus_registry = lambda: registry
try:
app = build_app(_build_args(), supported_tasks=())
finally:
metrics_mod.get_prometheus_registry = original
@app.get("/raise_http_exception_400")
async def raise_http_exception_400():
raise HTTPException(status_code=400, detail="bad request")
@app.get("/raise_http_exception_404")
async def raise_http_exception_404():
raise HTTPException(status_code=404, detail="not found")
@app.get("/raise_request_validation_error")
async def raise_request_validation_error(n: int):
# Invalid ``n`` triggers FastAPI's RequestValidationError.
return {"n": n}
@app.get("/raise_vllm_validation_error")
async def raise_vllm_validation_error():
raise VLLMValidationError("bad parameter", parameter="temperature")
@app.get("/raise_vllm_not_found_error")
async def raise_vllm_not_found_error():
raise VLLMNotFoundError("model not found")
@app.get("/raise_vllm_server_error")
async def raise_vllm_server_error():
# Bare VLLMServerError goes through vllm_error_handler → 500.
# EngineGenerateError / EngineDeadError are not used here: they call
# terminate_if_errored and need engine/server state.
raise VLLMServerError("internal server failure")
@app.get("/raise_value_error")
async def raise_value_error():
raise ValueError("invalid input value")
@app.get("/raise_type_error")
async def raise_type_error():
raise TypeError("wrong type")
@app.get("/raise_overflow_error")
async def raise_overflow_error():
raise OverflowError("number too large")
@app.get("/raise_not_implemented_error")
async def raise_not_implemented_error():
raise NotImplementedError("feature not supported")
@app.get("/raise_runtime_error")
async def raise_runtime_error():
raise RuntimeError("unexpected server error")
@app.get("/success")
async def success():
return {"status": "ok"}
return app
def _get_http_requests_total(registry, method: str, handler: str):
"""Extract the http_requests_total metric values grouped by status.
Returns a dict like {"2xx": 1.0, "5xx": 1.0} for the given handler.
"""
results: dict[str, float] = {}
for metric in registry.collect():
if metric.name == "http_requests":
for sample in metric.samples:
if (
sample.name == "http_requests_total"
and sample.labels.get("method") == method
and sample.labels.get("handler") == handler
):
status = sample.labels.get("status")
results[status] = results.get(status, 0) + sample.value
return results
@pytest.mark.asyncio
@pytest.mark.parametrize(
"endpoint,expected_status_group,expected_http_code,request_kwargs",
[
("/raise_http_exception_400", "4xx", 400, {}),
("/raise_http_exception_404", "4xx", 404, {}),
("/raise_request_validation_error", "4xx", 400, {"params": {"n": "x"}}),
("/raise_vllm_validation_error", "4xx", 400, {}),
("/raise_vllm_not_found_error", "4xx", 404, {}),
("/raise_vllm_server_error", "5xx", 500, {}),
("/raise_value_error", "4xx", 400, {}),
("/raise_type_error", "4xx", 400, {}),
("/raise_overflow_error", "4xx", 400, {}),
("/raise_not_implemented_error", "5xx", 501, {}),
("/raise_runtime_error", "5xx", 500, {}),
("/success", "2xx", 200, {}),
],
ids=[
"HTTPException(400)->4xx",
"HTTPException(404)->4xx",
"RequestValidationError->4xx",
"VLLMValidationError->4xx",
"VLLMNotFoundError->4xx",
"VLLMServerError->5xx",
"ValueError->4xx",
"TypeError->4xx",
"OverflowError->4xx",
"NotImplementedError->5xx",
"RuntimeError->5xx",
"success->2xx",
],
)
async def test_http_requests_total_records_correct_status(
app,
registry,
endpoint,
expected_status_group,
expected_http_code,
request_kwargs,
):
"""Verify that http_requests_total records the correct status group.
The Prometheus metric should reflect the actual HTTP status code returned
to the client, not a default 500 for all exceptions.
"""
# raise_app_exceptions=False allows the full ASGI middleware stack
# (including ServerErrorMiddleware) to handle exceptions and generate
# proper HTTP responses, just like a real server would.
transport = httpx.ASGITransport(app=app, raise_app_exceptions=False)
async with httpx.AsyncClient(
transport=transport, base_url="http://testserver"
) as client:
response = await client.get(endpoint, **request_kwargs)
# Verify the HTTP response code returned to the client is correct
assert response.status_code == expected_http_code, (
f"Expected HTTP {expected_http_code} for {endpoint}, got {response.status_code}"
)
# Verify Prometheus recorded the correct status group
metrics = _get_http_requests_total(registry, "GET", endpoint)
assert expected_status_group in metrics, (
f"Expected Prometheus to record '{expected_status_group}' for "
f"{endpoint}, but got: {metrics}"
)
assert metrics[expected_status_group] == 1.0, (
f"Expected 1 request recorded as '{expected_status_group}' for "
f"{endpoint}, but got {metrics[expected_status_group]}"
)
# For endpoints that should be recorded as 4xx, verify they are NOT
# incorrectly recorded as 5xx
if expected_status_group == "4xx":
assert "5xx" not in metrics, (
f"Expected NO '5xx' recording for {endpoint} "
f"(should be '4xx'), but found: {metrics}"
)
@@ -0,0 +1,153 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Tests that validation_exception_handler populates the `param` field
in its error response using the Pydantic error's `loc`, even when no
custom VLLMValidationError context is present.
Previously, `param` was only populated for errors carrying a custom
VLLMValidationError in their Pydantic `ctx`. Plain validation failures
(missing fields, wrong types) left `param` as None, even though the
field name was readily available from `error['loc']`.
"""
import json
from types import SimpleNamespace
import pytest
from fastapi.exceptions import RequestValidationError
from vllm.entrypoints.serve.exception_handling.handlers.validation import (
clean_loc_for_param,
validation_exception_handler,
)
def _fake_request(log_error_stack: bool = False) -> SimpleNamespace:
"""Minimal stand-in for a FastAPI Request - just enough for the
handler to read req.app.state.args.log_error_stack."""
return SimpleNamespace(
app=SimpleNamespace(
state=SimpleNamespace(args=SimpleNamespace(log_error_stack=log_error_stack))
),
state=SimpleNamespace(), # no request_metadata -> hasattr(...) is False
)
class TestValidationErrorParamFallback:
"""Ensure `param` falls back to the Pydantic error's `loc` when no
custom VLLMValidationError context is present."""
@pytest.mark.parametrize(
("error_type", "msg"),
[
("missing", "Field required"),
("list_type", "Input should be a valid list"),
],
ids=["missing-field", "wrong-type"],
)
@pytest.mark.asyncio
async def test_param_falls_back_to_loc(self, error_type: str, msg: str):
errors = [{"type": error_type, "loc": ("body", "messages"), "msg": msg}]
exc = RequestValidationError(errors)
response = await validation_exception_handler(_fake_request(), exc)
body = json.loads(response.body)
assert body["error"]["param"] == "body.messages"
@pytest.mark.asyncio
async def test_param_fallback_does_not_crash_on_non_dict_error(self):
"""Schemathesis fuzzing found that errors[0] isn't always a dict.
The fallback must not crash in that case - it should just leave
param as None instead of raising."""
exc = RequestValidationError(["some unexpected non-dict error"])
response = await validation_exception_handler(_fake_request(), exc)
body = json.loads(response.body)
assert body["error"]["param"] is None
class TestCleanLocForParam:
"""Guards against PR #1's naive dot-joined `loc` fallback leaking
Pydantic-internal wrapper/union-branch markers into `param`, e.g.
'body.function-wrap[__log_extra_fields__()].prompt' instead of the
clean 'body.prompt' an API consumer would recognize.
"""
@pytest.mark.parametrize(
"loc,expected",
[
(("body", "prompt"), "body.prompt"),
(("body", "messages", 2, "content"), "body.messages.2.content"),
(
("body", "function-wrap[__log_extra_fields__()]", "prompt"),
"body.prompt",
),
(("body", "stop", "str"), "body.stop"),
(("body", "stop", "list[str]"), "body.stop"),
(
("body", "prompt", "list[constrained-int]"),
"body.prompt",
),
],
)
def test_strips_internal_markers(self, loc, expected):
assert clean_loc_for_param(loc) == expected
def test_all_internal_falls_back_to_raw_join(self):
"""If every loc segment looks internal, fall back to the raw
dot-join rather than returning an empty string."""
loc = ("function-wrap[__log_extra_fields__()]",)
assert clean_loc_for_param(loc) == "function-wrap[__log_extra_fields__()]"
class TestValidationErrorDoesNotLeakServerPaths:
"""FastAPI sets endpoint_file/line/function/path on the exception
during routing, not in the constructor - so we set them manually
here to reproduce the real leak. See #31683."""
@pytest.mark.asyncio
async def test_handler_strips_endpoint_file_context(self):
errors = [
{
"type": "list_type",
"loc": ("body", "messages"),
"msg": "Input should be a valid list",
"input": "not-a-list",
}
]
exc = RequestValidationError(errors)
exc.endpoint_file = (
"/usr/local/lib/python3.12/dist-packages/vllm/"
"entrypoints/serve/utils/api_utils.py"
)
exc.endpoint_line = 40
exc.endpoint_function = "create_chat_completion"
exc.endpoint_path = "POST /v1/chat/completions"
response = await validation_exception_handler(_fake_request(), exc)
body = json.loads(response.body)
message = body["error"]["message"]
assert "/usr/local/" not in message
assert "api_utils.py" not in message
assert "create_chat_completion" not in message
assert "list_type" in message
assert "Input should be a valid list" in message
@pytest.mark.asyncio
async def test_handler_strips_endpoint_path_only_variant(self):
"""Covers the branch where only endpoint_path is set."""
errors = [
{"type": "missing", "loc": ("body", "messages"), "msg": "Field required"}
]
exc = RequestValidationError(errors)
exc.endpoint_path = "POST /v1/chat/completions"
response = await validation_exception_handler(_fake_request(), exc)
body = json.loads(response.body)
message = body["error"]["message"]
assert "missing" in message
assert "Field required" in message