litellm/tests/unit/proxy/guardrails/test_endpoint_image_scan.py
Agung Besti d7ab7255e2
feat(guardrails): scan an image on /apply_guardrail with a Bedrock guardrail (#51016)
* fix(guardrails): record the guardrail verdict on a request dict that starts empty

The Bedrock guardrail and the shared `log_guardrail_information` wrapper both picked the request dict with `or {}`. An empty dict is falsy, so a caller that passed one had the verdict written to a throwaway dict. /apply_guardrail passes an empty dict for a request that carries no messages and no metadata, so nothing downstream could see what the guardrail decided. The verdict now goes to the dict the caller passed, and only a missing dict falls back to a new one.

* fix(guardrails): log requests that a guardrail blocks on /apply_guardrail

A request a guardrail blocked on /apply_guardrail was missing from the logs. The endpoint skipped the failure handlers for an HTTPException, the spend log failure hook wrote no row because the route is not an LLM API route, and the guardrail's verdict stayed on a request dict no logger reads.

The endpoint now runs the failure handlers for every exception and copies the verdict onto the logged request, so allowed and blocked requests both carry it along with the guardrail's cost. It marks the failure of a request it had set up with a sentinel, and the spend log failure hook writes its row for that mark. A request rejected before setup, such as one with a bad key or an unknown guardrail, is still not logged. Guardrail records a caller sends in metadata are dropped for both response formats so a verdict cannot be forged in the logs.

* feat(guardrails): scan an image on /apply_guardrail with a Bedrock guardrail

/apply_guardrail only took text. It now takes `images`, one base64 data URI per request, and `text` becomes optional. The image is validated with the attachment reader the Bedrock guardrail already uses for chat completions and sent to ApplyGuardrail through the same call, with source OUTPUT for a response-direction scan. The image is scanned first, and the text scan is skipped only when the request has neither text nor messages.

A request the guardrail cannot judge answers 422 instead of 200 or 400. That covers an unreadable image, a guardrail that is not a Bedrock ApplyGuardrail guardrail, and an answer in which Bedrock does not report the image as guarded.

* test(guardrails): run the image tests through the endpoint's real request setup

The endpoint test helper on main now goes through the real request setup and guardrail lookup, and expects each request to leave one log entry. A body the request model refuses never reaches the endpoint, so those two cases are checked on the model. The guardrail that cannot scan images now carries the name the request asks for.

* fix(guardrails): log an image Bedrock did not evaluate as not run

An ApplyGuardrail image call that Bedrock answered without guarding the image
was logged as a guardrail success, so the request log read as a pass for an
image nobody checked. It now logs as not_run. A Bedrock error inside a 200
body on /apply_guardrail answers 502 naming the AWS error type instead of the
Image modality message

* fix(guardrails): refuse message text a Bedrock guardrail would not scan

* fix(guardrails): answer 422 when Bedrock cannot evaluate an image on /apply_guardrail

* refactor(guardrails): return image scan failures as values and type the test override

* fix(guardrails): keep Bedrock API errors reporting as HTTPException and log image-only prompts

* fix(guardrails): keep the scanned image in the apply_guardrail spend log request

* fix(guardrails): redact the apply_guardrail image when message logging is off and keep Bedrock API errors a plain HTTPException

---------

Co-authored-by: mateo-berri <277851410+mateo-berri@users.noreply.github.com>
2026-11-17 18:13:28 +00:00

208 lines
8 KiB
Python

import json
from collections.abc import Callable, Mapping
from typing import Final, Literal
import httpx
import pytest
from fastapi import HTTPException
import litellm
from litellm.integrations.custom_guardrail import CustomGuardrail
from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler
from litellm.proxy.guardrails.endpoint_image_scan import scan_images
from litellm.proxy.guardrails.guardrail_hooks.bedrock_guardrails import BedrockGuardrail
from litellm.types.guardrails import GuardrailEventHooks
from litellm.types.llms.openai import AllMessageValues
from litellm.types.proxy.guardrails.guardrail_hooks.bedrock_guardrails import BedrockGuardrailResponse
_PNG_BASE64: Final = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg=="
_PNG: Final = f"data:image/png;base64,{_PNG_BASE64}"
_RECORDS_KEY: Final = "standard_logging_guardrail_information"
_EVALUATED: Final = {
"action": "NONE",
"outputs": [],
"assessments": [],
"guardrailCoverage": {"images": {"guarded": 1, "total": 1}},
}
_NOT_EVALUATED: Final = {
"action": "NONE",
"outputs": [],
"assessments": [],
"guardrailCoverage": {"images": {"guarded": 0, "total": 1}},
}
_BLOCKED: Final = {
"action": "GUARDRAIL_INTERVENED",
"outputs": [{"text": "blocked"}],
"assessments": [{"contentPolicy": {"filters": [{"type": "VIOLENCE", "confidence": "HIGH", "action": "BLOCKED"}]}}],
"guardrailCoverage": {"images": {"guarded": 1, "total": 1}},
}
class _Bedrock:
def __init__(self, answer: Mapping[str, object], status_code: int = 200) -> None:
self.answer: Final = answer
self.status_code: Final = status_code
self.requests: Final[list[httpx.Request]] = []
def __call__(self, request: httpx.Request) -> httpx.Response:
self.requests.append(request)
return httpx.Response(self.status_code, json=self.answer)
def _apply_guardrail_api(bedrock: _Bedrock) -> BedrockGuardrail:
return BedrockGuardrail(
guardrail_name="image-guard",
guardrailIdentifier="gr-1",
guardrailVersion="1",
aws_region_name="us-east-1",
aws_access_key_id="test-access-key",
aws_secret_access_key="test-secret-key",
async_handler=AsyncHTTPHandler(transport=httpx.MockTransport(bedrock)),
)
def _guardrail_checks_api(bedrock: _Bedrock) -> BedrockGuardrail:
return BedrockGuardrail(
guardrail_name="image-guard",
checks={"contentFilter": {"categories": [{"category": "VIOLENCE"}]}},
aws_region_name="us-east-1",
aws_access_key_id="test-access-key",
aws_secret_access_key="test-secret-key",
async_handler=AsyncHTTPHandler(transport=httpx.MockTransport(bedrock)),
)
def _another_provider(bedrock: _Bedrock) -> CustomGuardrail:
return CustomGuardrail(guardrail_name="image-guard")
class _OwnBedrockCall(BedrockGuardrail):
async def make_bedrock_api_request(
self,
source: Literal["INPUT", "OUTPUT"],
messages: list[AllMessageValues] | None = None,
response: litellm.ModelResponse | None = None,
request_data: dict | None = None,
logging_event_type: GuardrailEventHooks | None = None,
) -> BedrockGuardrailResponse:
return {"action": "NONE"}
def _subclass_with_its_own_bedrock_call(bedrock: _Bedrock) -> CustomGuardrail:
return _OwnBedrockCall(
guardrail_name="image-guard",
guardrailIdentifier="gr-1",
guardrailVersion="1",
aws_region_name="us-east-1",
aws_access_key_id="test-access-key",
aws_secret_access_key="test-secret-key",
async_handler=AsyncHTTPHandler(transport=httpx.MockTransport(bedrock)),
)
@pytest.mark.asyncio
@pytest.mark.parametrize(
("input_type", "source", "mode"),
[("request", "INPUT", "pre_call"), ("response", "OUTPUT", "post_call")],
)
async def test_image_is_scanned_in_the_requested_direction_and_its_verdict_recorded(
input_type: Literal["request", "response"], source: str, mode: str
) -> None:
bedrock: Final = _Bedrock(_EVALUATED)
request_data: Final[dict[str, object]] = {}
await scan_images(_apply_guardrail_api(bedrock), (_PNG,), request_data, input_type)
assert [json.loads(request.content) for request in bedrock.requests] == [
{"source": source, "content": [{"image": {"format": "png", "source": {"bytes": _PNG_BASE64}}}]}
]
assert [
(record["guardrail_status"], record["guardrail_mode"]) for record in request_data["metadata"][_RECORDS_KEY]
] == [("success", mode)]
@pytest.mark.asyncio
async def test_blocked_image_raises_the_block_and_records_the_intervention() -> None:
request_data: Final[dict[str, object]] = {}
with pytest.raises(HTTPException) as blocked:
await scan_images(_apply_guardrail_api(_Bedrock(_BLOCKED)), (_PNG,), request_data, "request")
assert blocked.value.status_code == 400
assert [record["guardrail_status"] for record in request_data["metadata"][_RECORDS_KEY]] == ["guardrail_intervened"]
@pytest.mark.asyncio
@pytest.mark.parametrize(
"image",
[
"https://example.com/cat.png",
_PNG_BASE64,
f"data:image/webp;base64,{_PNG_BASE64}",
"data:image/png;base64,bm90IGFuIGltYWdl",
"data:image/png;base64,@@@@",
],
ids=["remote-url", "bare-base64", "webp", "not-image-bytes", "invalid-base64"],
)
async def test_unreadable_image_is_refused_without_a_scan_or_a_recorded_block(image: str) -> None:
bedrock: Final = _Bedrock(_EVALUATED)
request_data: Final[dict[str, object]] = {}
with pytest.raises(HTTPException) as refused:
await scan_images(_apply_guardrail_api(bedrock), (image,), request_data, "request")
assert refused.value.status_code == 422
assert "base64 PNG or JPEG data URL" in refused.value.detail
assert bedrock.requests == []
assert request_data == {}
@pytest.mark.asyncio
@pytest.mark.parametrize("guardrail", [_guardrail_checks_api, _another_provider, _subclass_with_its_own_bedrock_call])
async def test_guardrail_that_cannot_scan_images_refuses_them(
guardrail: Callable[[_Bedrock], CustomGuardrail],
) -> None:
bedrock: Final = _Bedrock(_EVALUATED)
with pytest.raises(HTTPException) as refused:
await scan_images(guardrail(bedrock), (_PNG,), {}, "request")
assert refused.value.status_code == 422
assert bedrock.requests == []
@pytest.mark.asyncio
@pytest.mark.parametrize(
("answer", "status_code", "reason", "recorded_status"),
[
(_NOT_EVALUATED, 422, "Image modality", "not_run"),
({"action": "NONE", "outputs": [], "assessments": []}, 422, "Image modality", "not_run"),
({"Output": {"__type": "ServiceException"}}, 502, "ServiceException", "guardrail_failed_to_respond"),
],
ids=["reported-unguarded", "no-coverage-reported", "error-inside-a-200-body"],
)
async def test_image_bedrock_did_not_confirm_evaluating_is_not_reported_as_passed(
answer: Mapping[str, object], status_code: int, reason: str, recorded_status: str
) -> None:
request_data: Final[dict[str, object]] = {}
with pytest.raises(HTTPException) as refused:
await scan_images(_apply_guardrail_api(_Bedrock(answer)), (_PNG,), request_data, "request")
assert refused.value.status_code == status_code
assert reason in refused.value.detail
assert [record["guardrail_status"] for record in request_data["metadata"][_RECORDS_KEY]] == [recorded_status]
@pytest.mark.asyncio
@pytest.mark.parametrize(("bedrock_status", "status_code"), [(400, 422), (503, 503)])
async def test_image_bedrock_rejects_answers_unscanned_while_its_outages_pass_through(
bedrock_status: int, status_code: int
) -> None:
bedrock: Final = _Bedrock({"message": "The images contained in the request are not supported"}, bedrock_status)
with pytest.raises(HTTPException) as refused:
await scan_images(_apply_guardrail_api(bedrock), (_PNG,), {}, "request")
assert refused.value.status_code == status_code
assert "The images contained in the request are not supported" in refused.value.detail