mirror of
https://github.com/BerriAI/litellm.git
synced 2026-11-29 01:03:17 +00:00
* fix(bedrock): match Python's Claude Platform Messages call in the Rust adapter The Rust Claude Platform adapter never saw the workspace or the unsupported-params override, because the bridge only projects the kwargs LitellmParams names. They are now a typed group on LitellmParams, so every Claude Platform call reaches Rust with them. The adapter now follows Python's order. An API key goes out as x-api-key unless the caller forwarded one, and the caller's Authorization stays beside it. Without a key the Bedrock bearer token authenticates the call, as on Invoke and Mantle, then SigV4. A configured workspace always replaces the caller's header, and a header alone is no workspace. litellm.api_base is honoured before the env bases. The model keeps its claude_platform/ route until it is sent, so the call is billed on the bedrock/claude_platform rows instead of logging a zero cost. The bridge no longer runs Invoke's tool shaping on Claude Platform calls, which stripped a tool's cache_control ttl from the wire. A missing workspace or region raises AuthenticationError with what is missing, an invalid region the bare ValueError, and a region refusal logs the resolved call as Python does. Credential failures map from the fixed class list Mantle uses instead of replaying Python's signing. Signing over a forwarded Authorization stays a difference from Python, which re-adds the caller's header over its own signature. The Mantle routes on Rust do the same. * feat(messages): serve Claude Platform on Rust only and route Bedrock Messages by provider bedrock/claude_platform/ /v1/messages calls now run on Rust only, as Bedrock Invoke and Mantle do. With all three Bedrock Messages routes on Rust, a bedrock or bedrock_mantle call that has a native Messages config always runs on Rust, so the per-route targets go away. BEDROCK_INVOKE, BEDROCK_MANTLE and the class-to-target map are removed, and bedrock and bedrock_mantle join the provider rule anthropic and azure_ai already use. Converse and non-Claude Bedrock models still get no Messages config and keep going through Python's completion adaptation. The Rust Claude Platform tests check the wire request against what Python's config sent, captured once in a JSON fixture, plus billing on the bedrock/claude_platform rows and the exception class and status of each refusal. * refactor(bedrock): drop the Python Claude Platform Messages handler code Rust sends every Claude Platform /v1/messages call, so the Python config loses the environment validation and request transform only Python's Messages handler called, along with their unit tests. The config stays for provider lookups, the error class and the URL the Rust host names in errors. The chat route keeps its own transformation. * test(bedrock): type the Claude Platform billing and failure assertions * test(bedrock): check the Rust Bedrock Invoke Messages route against captured Python output The Invoke tests no longer run Python's Messages handler beside Rust, which litellm/rust/AGENTS.md rules out. What Python's Invoke config sent, billed, streamed, logged and warned is captured once in a JSON fixture and each test checks Rust against it. Exception tests check the class and status only, and every served call asserts it was served by Rust. The Claude Platform tests assert the same. * refactor(bedrock): drop the Python Bedrock Invoke Messages handler code Rust sends every Bedrock Invoke /v1/messages call, so the Python config loses what only Python's Messages handler called: the environment validation, the native-output retry pair, the event-stream iterator and decoder, and the SSE wrapper. The request transform stays because count_tokens and the Mantle configs read it. The Python unit tests that drove Invoke Messages through Python's handler go with it. Converse and Invoke chat keep their tests. * test(bedrock): drop the Python Invoke Messages leg from the cache breakpoint hook test Bedrock Invoke Messages runs on Rust only, so the hook test keeps its completion and acompletion legs, which reach Bedrock through Converse. * fix(bedrock): close the Claude Platform differences the A/B fuzz found Differential fuzzing against the Mantle tip found three places where Rust's Claude Platform route still differed from Python's. SigV4 now signs in us-west-2 when no region is named anywhere, as botocore does, instead of refusing the call. A missing region for the default endpoint raises AuthenticationError naming no model, as Python's config raises it. Rust now logs Python's warnings when it drops params the endpoint rejects, when it ignores a claude_platform_unsupported_params that is not a list, and when it drops a disabled thinking on an always-thinking model. For that last warning the request model is sent without its claude_platform/ route again, and the logged model carries the route so billing stays on the claude_platform rows. * fix(messages): require Rust only for a native Messages target The provider rule that makes anthropic, azure_ai, bedrock and bedrock_mantle Rust-only had no target filter. When computing a call's target raises, dispatch serves the call on Python and _checked_target hands the refusal check target None, which matched the rule, so a non-Claude Bedrock call that only Python can serve was refused as Rust-only. The rule now matches only Target.MESSAGES, which a call gets exactly when its provider has a native Messages config, so the Claude Bedrock routes stay Rust-only and a call with no computed target falls back to Python as dispatch intends.
491 lines
22 KiB
Python
491 lines
22 KiB
Python
import asyncio
|
|
import json
|
|
from collections.abc import Callable, Mapping
|
|
from typing import Final
|
|
|
|
import pytest
|
|
from pydantic import TypeAdapter
|
|
|
|
import litellm
|
|
from litellm.llms.bedrock.base_aws_llm import BaseAWSLLM
|
|
from litellm.llms.bedrock.chat.converse_transformation import AmazonConverseConfig
|
|
from litellm.llms.bedrock.chat.invoke_transformations.amazon_openai_transformation import (
|
|
AmazonBedrockOpenAIConfig,
|
|
)
|
|
from litellm.llms.bedrock.chat.invoke_transformations.base_invoke_transformation import (
|
|
AmazonInvokeConfig,
|
|
)
|
|
from litellm.llms.bedrock.request_metadata import (
|
|
BEDROCK_REQUEST_METADATA_HEADER,
|
|
BEDROCK_REQUEST_METADATA_HEADER_MAX_CHARS,
|
|
BEDROCK_REQUEST_METADATA_MAX_PAIRS,
|
|
resolve_bedrock_request_metadata,
|
|
)
|
|
|
|
MODEL = "anthropic.claude-3-5-sonnet-20240620-v1:0"
|
|
MESSAGES = [{"role": "user", "content": "hi"}]
|
|
ALL_FIELDS = [
|
|
"user_api_key_alias",
|
|
"user_api_key_team_alias",
|
|
"user_api_key_user_email",
|
|
"spend_logs_metadata",
|
|
]
|
|
IDENTITY = {"user_api_key_alias": "prod-key", "user_api_key_team_alias": "platform"}
|
|
|
|
|
|
def litellm_params(metadata_key, **metadata):
|
|
return {metadata_key: dict(metadata)}
|
|
|
|
|
|
def converse_body(litellm_params_value, optional_params=None):
|
|
return AmazonConverseConfig()._transform_request(
|
|
model=MODEL,
|
|
messages=MESSAGES,
|
|
optional_params=dict(optional_params or {}),
|
|
litellm_params=dict(litellm_params_value),
|
|
)
|
|
|
|
|
|
def converse_body_async(litellm_params_value, optional_params=None):
|
|
"""The proxy serves completions through the async transform, so every rule asserted against
|
|
the sync body has to be asserted against this one too or half the product is untested."""
|
|
return asyncio.run(
|
|
AmazonConverseConfig()._async_transform_request(
|
|
model=MODEL,
|
|
messages=MESSAGES,
|
|
optional_params=dict(optional_params or {}),
|
|
litellm_params=dict(litellm_params_value),
|
|
)
|
|
)
|
|
|
|
|
|
CONVERSE_DRIVERS = [converse_body, converse_body_async]
|
|
|
|
|
|
@pytest.mark.parametrize("setting", [None, []])
|
|
def test_feature_off_by_default_leaves_body_and_headers_untouched(setting, monkeypatch: pytest.MonkeyPatch):
|
|
monkeypatch.setattr(litellm, "bedrock_request_metadata_fields", setting)
|
|
params = litellm_params("metadata", spend_logs_metadata={"team": "x"}, **IDENTITY)
|
|
|
|
assert "requestMetadata" not in converse_body(params)
|
|
assert BEDROCK_REQUEST_METADATA_HEADER not in AmazonInvokeConfig().validate_environment(
|
|
headers={}, model=MODEL, messages=MESSAGES, optional_params={}, litellm_params=dict(params)
|
|
)
|
|
|
|
|
|
@pytest.mark.parametrize("metadata_key", ["metadata", "litellm_metadata"])
|
|
def test_resolver_reads_both_metadata_variable_names(metadata_key, monkeypatch: pytest.MonkeyPatch):
|
|
"""`/v1/chat/completions` populates `metadata`; the LITELLM_METADATA_ROUTES populate
|
|
`litellm_metadata`. Reading only one silently forwards nothing on the other route."""
|
|
monkeypatch.setattr(litellm, "bedrock_request_metadata_fields", ALL_FIELDS)
|
|
params = litellm_params(metadata_key, spend_logs_metadata={"cost_center": "cc-1"}, **IDENTITY)
|
|
|
|
assert converse_body(params)["requestMetadata"] == {**IDENTITY, "cost_center": "cc-1"}
|
|
|
|
|
|
@pytest.mark.parametrize("reverse_client_keys", [False, True])
|
|
@pytest.mark.parametrize("field_order", [ALL_FIELDS, list(reversed(ALL_FIELDS))])
|
|
@pytest.mark.parametrize("client_source", ["spend_logs_metadata", "requestMetadata"])
|
|
def test_identity_survives_a_caller_filling_every_slot(
|
|
reverse_client_keys,
|
|
field_order,
|
|
client_source,
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
):
|
|
"""A caller sending 16 keys of its own must not evict the identity the feature exists to
|
|
produce. Driven over every input ordering so the invariant is not an accident of one."""
|
|
monkeypatch.setattr(litellm, "bedrock_request_metadata_fields", field_order)
|
|
client_keys = [f"client_{index:02d}" for index in range(BEDROCK_REQUEST_METADATA_MAX_PAIRS)]
|
|
client_pairs = {key: "v" for key in (reversed(client_keys) if reverse_client_keys else client_keys)}
|
|
if client_source == "spend_logs_metadata":
|
|
params, optional_params = litellm_params("metadata", spend_logs_metadata=client_pairs, **IDENTITY), {}
|
|
else:
|
|
params, optional_params = litellm_params("metadata", **IDENTITY), {"requestMetadata": client_pairs}
|
|
|
|
resolved = converse_body(params, optional_params)["requestMetadata"]
|
|
|
|
assert len(resolved) == BEDROCK_REQUEST_METADATA_MAX_PAIRS
|
|
for key, value in IDENTITY.items():
|
|
assert resolved[key] == value
|
|
assert len([key for key in resolved if key.startswith("client_")]) == (
|
|
BEDROCK_REQUEST_METADATA_MAX_PAIRS - len(IDENTITY)
|
|
)
|
|
|
|
|
|
def test_a_key_sent_twice_keeps_the_caller_value_and_uses_one_slot(monkeypatch: pytest.MonkeyPatch) -> None:
|
|
monkeypatch.setattr(litellm, "bedrock_request_metadata_fields", ALL_FIELDS)
|
|
caller: Final = {
|
|
f"client_{index:02d}": "caller" for index in range(BEDROCK_REQUEST_METADATA_MAX_PAIRS - len(IDENTITY) - 1)
|
|
}
|
|
spend_logs: Final = {**{key: "spend" for key in caller}, "extra": "spend"}
|
|
|
|
resolved: Final = resolve_bedrock_request_metadata(
|
|
litellm_params("metadata", spend_logs_metadata=spend_logs, **IDENTITY), caller_metadata=caller
|
|
)
|
|
|
|
assert resolved == {**IDENTITY, **caller, "extra": "spend"}
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"field_order",
|
|
[
|
|
["user_api_key_alias", "user_api_key_alias", "user_api_key_team_alias", "spend_logs_metadata"],
|
|
["user_api_key_alias", "user_api_key_team_alias", "user_api_key_alias", "spend_logs_metadata"],
|
|
["user_api_key_alias", "user_api_key_team_alias", "spend_logs_metadata", "user_api_key_team_alias"],
|
|
],
|
|
)
|
|
def test_a_field_repeated_in_the_allow_list_does_not_consume_a_client_slot(
|
|
field_order,
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
):
|
|
"""An operator repeating a field in YAML must not inflate the reserved count and shrink the
|
|
client budget. Asserts the client keys that should have fitted actually reach the wire, since
|
|
asserting only that identity survives passes with or without the deduplication."""
|
|
monkeypatch.setattr(litellm, "bedrock_request_metadata_fields", field_order)
|
|
client_keys = [f"client_{index:02d}" for index in range(BEDROCK_REQUEST_METADATA_MAX_PAIRS - 1)]
|
|
params = litellm_params("metadata", spend_logs_metadata={key: "v" for key in client_keys}, **IDENTITY)
|
|
|
|
resolved = converse_body(params)["requestMetadata"]
|
|
|
|
expected_client_slots = BEDROCK_REQUEST_METADATA_MAX_PAIRS - len(IDENTITY)
|
|
assert resolved == {**IDENTITY, **{key: "v" for key in client_keys[:expected_client_slots]}}
|
|
assert len(resolved) == BEDROCK_REQUEST_METADATA_MAX_PAIRS
|
|
assert client_keys[expected_client_slots - 1] in resolved
|
|
|
|
|
|
@pytest.mark.parametrize("client_source", ["spend_logs_metadata", "requestMetadata"])
|
|
@pytest.mark.parametrize(
|
|
"forged_key",
|
|
[
|
|
"user_api_key_team_alias",
|
|
"user_api_key_org_alias",
|
|
"user_api_key_hash",
|
|
"USER_API_KEY_TEAM_ALIAS",
|
|
"User_Api_Key_Hash",
|
|
" user_api_key_user_id",
|
|
],
|
|
)
|
|
def test_caller_cannot_forge_or_shadow_a_reserved_identity_key(
|
|
forged_key,
|
|
client_source,
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
):
|
|
"""`user_api_key_org_alias` and `user_api_key_hash` are names the proxy does not set here,
|
|
so an exact-key reservation would let the forged value through under a name that reads as
|
|
proxy-authoritative in the AWS billing record."""
|
|
monkeypatch.setattr(litellm, "bedrock_request_metadata_fields", ALL_FIELDS)
|
|
forged = {forged_key: "attacker-controlled"}
|
|
if client_source == "spend_logs_metadata":
|
|
params, optional_params = litellm_params("metadata", spend_logs_metadata=forged, **IDENTITY), {}
|
|
else:
|
|
params, optional_params = litellm_params("metadata", **IDENTITY), {"requestMetadata": forged}
|
|
|
|
resolved = converse_body(params, optional_params)["requestMetadata"]
|
|
|
|
assert resolved == IDENTITY
|
|
assert "attacker-controlled" not in resolved.values()
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"team_alias",
|
|
["O'Brien's team", "platform\u00a0team", "platform\u3000team", "x" * 256 + "\n"],
|
|
ids=["apostrophe", "no-break-space", "ideographic-space", "257-chars-ending-in-newline"],
|
|
)
|
|
def test_identity_violating_the_character_class_is_dropped_and_the_request_succeeds(
|
|
team_alias: str, monkeypatch: pytest.MonkeyPatch
|
|
) -> None:
|
|
"""A team alias with an apostrophe must not turn a working request into a 400 the moment
|
|
an operator flips the setting on. Bedrock also rejects non-ASCII whitespace (checked live 2026-10-16)."""
|
|
monkeypatch.setattr(litellm, "bedrock_request_metadata_fields", ALL_FIELDS)
|
|
params = litellm_params(
|
|
"metadata",
|
|
user_api_key_alias="prod-key",
|
|
user_api_key_team_alias=team_alias,
|
|
user_api_key_user_email="x" * 300,
|
|
)
|
|
|
|
body = converse_body(params)
|
|
|
|
assert body["requestMetadata"] == {"user_api_key_alias": "prod-key"}
|
|
assert body["messages"]
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"caller_metadata",
|
|
[{"team": "O'Brien's team"}, {"k" * 256 + "\n": "v"}, {"team": "v" * 256 + "\n"}],
|
|
ids=["bad-character", "257-char-key-ending-in-newline", "257-char-value-ending-in-newline"],
|
|
)
|
|
def test_caller_supplied_violation_still_raises_bad_request(
|
|
caller_metadata: Mapping[str, str], monkeypatch: pytest.MonkeyPatch
|
|
) -> None:
|
|
monkeypatch.setattr(litellm, "bedrock_request_metadata_fields", ALL_FIELDS)
|
|
|
|
with pytest.raises(litellm.exceptions.BadRequestError):
|
|
converse_body(litellm_params("metadata", **IDENTITY), {"requestMetadata": caller_metadata})
|
|
|
|
|
|
@pytest.mark.parametrize("driver", CONVERSE_DRIVERS)
|
|
@pytest.mark.parametrize("drop_globally", [True, False])
|
|
@pytest.mark.parametrize(("fields", "forwarded_identity"), [(ALL_FIELDS, IDENTITY), (None, {})])
|
|
def test_caller_violations_are_dropped_like_the_passthrough_routes_when_params_are_dropped(
|
|
driver: Callable[[Mapping[str, object], Mapping[str, object]], Mapping[str, object]],
|
|
drop_globally: bool,
|
|
fields: list[str] | None,
|
|
forwarded_identity: Mapping[str, str],
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
) -> None:
|
|
monkeypatch.setattr(litellm, "bedrock_request_metadata_fields", fields)
|
|
monkeypatch.setattr(litellm, "drop_params", drop_globally)
|
|
params: Final = {**litellm_params("metadata", **IDENTITY), **({} if drop_globally else {"drop_params": True})}
|
|
|
|
body: Final = driver(params, {"requestMetadata": {"team": "O'Brien's team", "ticket": "T-42"}})
|
|
|
|
assert body["requestMetadata"] == {**forwarded_identity, "ticket": "T-42"}
|
|
|
|
|
|
@pytest.mark.parametrize("fields", [ALL_FIELDS, None])
|
|
def test_mapped_caller_violations_are_dropped_when_params_are_dropped(
|
|
fields: list[str] | None, monkeypatch: pytest.MonkeyPatch
|
|
) -> None:
|
|
monkeypatch.setattr(litellm, "bedrock_request_metadata_fields", fields)
|
|
caller: Final = {"team": "O'Brien's team", "ticket": "T-42"}
|
|
|
|
mapped: Final = AmazonConverseConfig().map_openai_params(
|
|
non_default_params={"requestMetadata": caller}, optional_params={}, model=MODEL, drop_params=True
|
|
)
|
|
|
|
assert mapped["requestMetadata"] == caller
|
|
with pytest.raises(litellm.exceptions.BadRequestError):
|
|
AmazonConverseConfig().map_openai_params(
|
|
non_default_params={"requestMetadata": caller}, optional_params={}, model=MODEL, drop_params=False
|
|
)
|
|
|
|
|
|
def test_non_string_and_absent_identity_values_are_dropped(monkeypatch: pytest.MonkeyPatch):
|
|
monkeypatch.setattr(litellm, "bedrock_request_metadata_fields", ALL_FIELDS + ["user_api_key_spend"])
|
|
params = litellm_params("metadata", user_api_key_alias="prod-key", user_api_key_spend=1.25)
|
|
|
|
assert converse_body(params)["requestMetadata"] == {"user_api_key_alias": "prod-key"}
|
|
|
|
|
|
def test_email_is_separately_opt_in(monkeypatch: pytest.MonkeyPatch):
|
|
"""PII crossing into CloudTrail only when the operator names the field."""
|
|
identity_with_email = {**IDENTITY, "user_api_key_user_email": "owner@example.com"}
|
|
monkeypatch.setattr(litellm, "bedrock_request_metadata_fields", ["user_api_key_alias", "user_api_key_team_alias"])
|
|
assert (
|
|
"user_api_key_user_email"
|
|
not in converse_body(litellm_params("metadata", **identity_with_email))["requestMetadata"]
|
|
)
|
|
|
|
monkeypatch.setattr(litellm, "bedrock_request_metadata_fields", ALL_FIELDS)
|
|
assert converse_body(litellm_params("metadata", **identity_with_email))["requestMetadata"] == identity_with_email
|
|
|
|
|
|
def test_resolver_returns_none_when_nothing_survives(monkeypatch: pytest.MonkeyPatch):
|
|
monkeypatch.setattr(litellm, "bedrock_request_metadata_fields", ALL_FIELDS)
|
|
assert resolve_bedrock_request_metadata(litellm_params=None) is None
|
|
assert resolve_bedrock_request_metadata(litellm_params={"metadata": {"unrelated": "x"}}) is None
|
|
|
|
|
|
def test_invoke_header_is_json_encoded_and_signed(monkeypatch: pytest.MonkeyPatch):
|
|
monkeypatch.setattr(litellm, "bedrock_request_metadata_fields", ALL_FIELDS)
|
|
params = litellm_params("metadata", spend_logs_metadata={"cost_center": "cc-1"}, **IDENTITY)
|
|
|
|
headers = AmazonInvokeConfig().validate_environment(
|
|
headers={"anthropic-version": "bedrock-2023-05-31"},
|
|
model=MODEL,
|
|
messages=MESSAGES,
|
|
optional_params={},
|
|
litellm_params=params,
|
|
)
|
|
|
|
assert json.loads(headers[BEDROCK_REQUEST_METADATA_HEADER]) == {**IDENTITY, "cost_center": "cc-1"}
|
|
signed = BaseAWSLLM()._filter_headers_for_aws_signature(headers)
|
|
assert BEDROCK_REQUEST_METADATA_HEADER in signed
|
|
assert "anthropic-version" not in signed
|
|
|
|
|
|
def test_a_caller_supplied_guardrail_header_still_wins(monkeypatch: pytest.MonkeyPatch):
|
|
"""The no-displace rule is deliberate for the guardrail headers and must survive the
|
|
request-metadata header becoming proxy-owned."""
|
|
monkeypatch.setattr(litellm, "bedrock_request_metadata_fields", ALL_FIELDS)
|
|
|
|
headers = AmazonInvokeConfig().validate_environment(
|
|
headers={"X-Amzn-Bedrock-GuardrailIdentifier": "caller-set"},
|
|
model=MODEL,
|
|
messages=MESSAGES,
|
|
optional_params={"guardrailConfig": {"guardrailIdentifier": "gid", "guardrailVersion": "DRAFT"}},
|
|
litellm_params=litellm_params("metadata", **IDENTITY),
|
|
)
|
|
|
|
assert headers["X-Amzn-Bedrock-GuardrailIdentifier"] == "caller-set"
|
|
assert headers["X-Amzn-Bedrock-GuardrailVersion"] == "DRAFT"
|
|
|
|
|
|
FORGED = '{"user_api_key_alias":"FORGED-KEY","user_api_key_team_alias":"FORGED-TEAM"}'
|
|
|
|
|
|
def invoke_headers(caller_headers, params, optional_params=None):
|
|
return AmazonInvokeConfig().validate_environment(
|
|
headers=dict(caller_headers),
|
|
model=MODEL,
|
|
messages=MESSAGES,
|
|
optional_params=dict(optional_params or {}),
|
|
litellm_params=dict(params),
|
|
)
|
|
|
|
|
|
def openai_invoke_headers(caller_headers, params):
|
|
return AmazonBedrockOpenAIConfig().validate_environment(
|
|
headers=dict(caller_headers),
|
|
model=MODEL,
|
|
messages=MESSAGES,
|
|
optional_params={},
|
|
litellm_params=dict(params),
|
|
)
|
|
|
|
|
|
def converse_headers(caller_headers, params):
|
|
return AmazonConverseConfig().validate_environment(
|
|
headers=dict(caller_headers),
|
|
model=MODEL,
|
|
messages=MESSAGES,
|
|
optional_params={},
|
|
litellm_params=dict(params),
|
|
)
|
|
|
|
|
|
HEADER_DRIVERS = [invoke_headers, openai_invoke_headers, converse_headers]
|
|
|
|
|
|
def metadata_header_values(headers):
|
|
return [value for name, value in headers.items() if name.lower() == BEDROCK_REQUEST_METADATA_HEADER.lower()]
|
|
|
|
|
|
@pytest.mark.parametrize("driver", HEADER_DRIVERS)
|
|
def test_the_metadata_header_keeps_the_leading_pairs_that_fit_bedrocks_header_limit(
|
|
driver: Callable[[Mapping[str, str], Mapping[str, object]], Mapping[str, str]],
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
) -> None:
|
|
monkeypatch.setattr(litellm, "bedrock_request_metadata_fields", ALL_FIELDS)
|
|
long_pairs: Final = {f"{index:02d}".ljust(256, "k"): "\n" * 256 for index in range(12)}
|
|
params: Final = litellm_params("metadata", spend_logs_metadata=long_pairs, **IDENTITY)
|
|
resolved: Final = tuple((resolve_bedrock_request_metadata(params) or {}).items())
|
|
|
|
headers: Final = driver({}, params)
|
|
(header,) = (value for name, value in headers.items() if name.lower() == BEDROCK_REQUEST_METADATA_HEADER.lower())
|
|
sent: Final = TypeAdapter(dict[str, str]).validate_json(header)
|
|
one_more_pair: Final = json.dumps(dict(resolved[: len(sent) + 1]), separators=(",", ":"))
|
|
|
|
assert len(header) <= BEDROCK_REQUEST_METADATA_HEADER_MAX_CHARS
|
|
assert tuple(sent.items()) == resolved[: len(sent)]
|
|
assert IDENTITY.items() <= sent.items()
|
|
assert len(one_more_pair) > BEDROCK_REQUEST_METADATA_HEADER_MAX_CHARS
|
|
|
|
|
|
def test_converse_still_sets_the_bearer_authorization_header(monkeypatch: pytest.MonkeyPatch):
|
|
"""Converse owns the metadata header now, and that must not disturb the api_key path its
|
|
validate_environment existed for. Closing the forgery hole cannot break authentication."""
|
|
monkeypatch.setattr(litellm, "bedrock_request_metadata_fields", ALL_FIELDS)
|
|
|
|
headers = AmazonConverseConfig().validate_environment(
|
|
headers={},
|
|
model=MODEL,
|
|
messages=MESSAGES,
|
|
optional_params={},
|
|
litellm_params=dict(litellm_params("metadata", **IDENTITY)),
|
|
api_key="sk-converse-bearer",
|
|
)
|
|
|
|
assert headers["Authorization"] == "Bearer sk-converse-bearer"
|
|
assert metadata_header_values(headers) == [json.dumps(IDENTITY, separators=(",", ":"))]
|
|
|
|
|
|
@pytest.mark.parametrize("driver", HEADER_DRIVERS)
|
|
@pytest.mark.parametrize(
|
|
"caller_header_name",
|
|
[BEDROCK_REQUEST_METADATA_HEADER, BEDROCK_REQUEST_METADATA_HEADER.lower(), "x-AMZN-bedrock-Request-METADATA"],
|
|
)
|
|
def test_a_caller_cannot_forge_the_request_metadata_header(driver, caller_header_name, monkeypatch: pytest.MonkeyPatch):
|
|
"""`extra_headers` puts caller-supplied names into the same dict the proxy merges into, so a
|
|
deferring merge would sign the caller's forged identity into the AWS billing record. Every
|
|
spelling must lose, or a second variant is left for the transport to choose between."""
|
|
monkeypatch.setattr(litellm, "bedrock_request_metadata_fields", ALL_FIELDS)
|
|
|
|
headers = driver({caller_header_name: FORGED}, litellm_params("metadata", **IDENTITY))
|
|
|
|
values = metadata_header_values(headers)
|
|
assert values == [json.dumps(IDENTITY, separators=(",", ":"))]
|
|
assert "FORGED" not in json.dumps(headers)
|
|
|
|
|
|
@pytest.mark.parametrize("driver", HEADER_DRIVERS)
|
|
def test_a_caller_cannot_forge_the_header_when_the_resolver_yields_nothing(driver, monkeypatch: pytest.MonkeyPatch):
|
|
"""Forwarding enabled but nothing resolvable, which a caller can arrange by supplying values
|
|
that all fail Bedrock's rules. Owned-but-empty must mean no header on the wire, never a
|
|
fallback to the caller's."""
|
|
monkeypatch.setattr(litellm, "bedrock_request_metadata_fields", ALL_FIELDS)
|
|
unresolvable = litellm_params("metadata", user_api_key_alias="O'Brien's key", user_api_key_team_alias="x" * 300)
|
|
|
|
headers = driver({BEDROCK_REQUEST_METADATA_HEADER: FORGED}, unresolvable)
|
|
|
|
assert metadata_header_values(headers) == []
|
|
assert "FORGED" not in json.dumps(headers)
|
|
|
|
|
|
@pytest.mark.parametrize("driver", CONVERSE_DRIVERS)
|
|
@pytest.mark.parametrize(
|
|
"forged_key",
|
|
["user_api_key_team_alias", "user_api_key_org_alias", "user_api_key_hash"],
|
|
)
|
|
def test_a_caller_cannot_keep_reserved_body_keys_when_the_resolver_yields_nothing(
|
|
forged_key,
|
|
driver,
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
):
|
|
"""The Converse body has the same fail-open shape as the header: with forwarding on and
|
|
nothing resolvable, leaving the caller's `requestMetadata` in place would keep their
|
|
reserved-prefix keys on the wire. Owned-but-empty must remove the field outright."""
|
|
monkeypatch.setattr(litellm, "bedrock_request_metadata_fields", ALL_FIELDS)
|
|
|
|
body = driver(litellm_params("metadata"), {"requestMetadata": {forged_key: "FORGED"}})
|
|
|
|
assert "requestMetadata" not in body
|
|
assert "FORGED" not in json.dumps(body)
|
|
|
|
|
|
@pytest.mark.parametrize("driver", CONVERSE_DRIVERS)
|
|
def test_benign_caller_body_metadata_still_survives_when_no_identity_resolves(driver, monkeypatch: pytest.MonkeyPatch):
|
|
"""Removing the field must be scoped to the reserved keys being the only thing left, not a
|
|
blanket drop of the caller's own attribution pairs."""
|
|
monkeypatch.setattr(litellm, "bedrock_request_metadata_fields", ALL_FIELDS)
|
|
|
|
body = driver(
|
|
litellm_params("metadata"),
|
|
{"requestMetadata": {"cost_center": "cc-9", "user_api_key_team_alias": "FORGED"}},
|
|
)
|
|
|
|
assert body["requestMetadata"] == {"cost_center": "cc-9"}
|
|
|
|
|
|
@pytest.mark.parametrize("driver", CONVERSE_DRIVERS)
|
|
def test_caller_body_metadata_is_left_alone_when_forwarding_is_off(driver, monkeypatch: pytest.MonkeyPatch):
|
|
"""With the feature off the proxy does not own the field, so the pre-existing pass-through
|
|
behaviour for a caller-supplied `requestMetadata` must be unchanged."""
|
|
monkeypatch.setattr(litellm, "bedrock_request_metadata_fields", None)
|
|
caller_supplied = {"user_api_key_team_alias": "caller-set", "cost_center": "cc-9"}
|
|
|
|
body = driver(litellm_params("metadata", **IDENTITY), {"requestMetadata": caller_supplied})
|
|
|
|
assert body["requestMetadata"] == caller_supplied
|
|
|
|
|
|
@pytest.mark.parametrize("driver", HEADER_DRIVERS)
|
|
def test_a_caller_header_is_left_alone_when_forwarding_is_off(driver, monkeypatch: pytest.MonkeyPatch):
|
|
"""The proxy only claims the name when the operator turned forwarding on; with the feature
|
|
off this is an ordinary passthrough header and stripping it would be a regression."""
|
|
monkeypatch.setattr(litellm, "bedrock_request_metadata_fields", None)
|
|
|
|
headers = driver({BEDROCK_REQUEST_METADATA_HEADER: FORGED}, litellm_params("metadata", **IDENTITY))
|
|
|
|
assert metadata_header_values(headers) == [FORGED]
|