diff --git a/agentic_security/http_spec.py b/agentic_security/http_spec.py index 36bcb1e6..f5a3c856 100644 --- a/agentic_security/http_spec.py +++ b/agentic_security/http_spec.py @@ -150,13 +150,22 @@ async def verify(self) -> httpx.Response: def model_name(self) -> str: """Extract the model name from the request body (JSON). - Returns the value of the 'model' field if present, otherwise 'unknown'. + Returns the value of the 'model' field if it is a non-empty string, + otherwise 'unknown'. A body that is valid JSON but not an object (a + list, a string, ``null``), or a 'model' that is not a string, also + gives 'unknown' instead of raising or leaking a non-string value into + cost accounting. """ try: body_json = json.loads(self.body) - return body_json.get("model", "unknown") except json.JSONDecodeError, TypeError: return "unknown" + if not isinstance(body_json, dict): + return "unknown" + model = body_json.get("model") + if isinstance(model, str) and model: + return model + return "unknown" @property def modality(self) -> Modality: diff --git a/tests/unit/test_model_name.py b/tests/unit/test_model_name.py new file mode 100644 index 00000000..7149ff7f --- /dev/null +++ b/tests/unit/test_model_name.py @@ -0,0 +1,39 @@ +import pytest + +from agentic_security.http_spec import LLMSpec +from agentic_security.probe_actor.cost_module import calculate_cost + + +def make_spec(body: str) -> LLMSpec: + return LLMSpec(method="POST", url="http://example.com/v1", headers={}, body=body) + + +@pytest.mark.parametrize( + "body, expected", + [ + ('{"model": "gpt-4o", "prompt": "<>"}', "gpt-4o"), + ('{"prompt": "hi"}', "unknown"), + ("not json at all", "unknown"), + ("", "unknown"), + # Valid JSON that is not an object. + ("[1, 2, 3]", "unknown"), + ('"just a string"', "unknown"), + ("null", "unknown"), + ("42", "unknown"), + # A "model" field that is not a usable name. + ('{"model": null}', "unknown"), + ('{"model": ""}', "unknown"), + ('{"model": 5}', "unknown"), + ('{"model": ["a", "b"]}', "unknown"), + ('{"model": {"name": "x"}}', "unknown"), + ], +) +def test_model_name(body, expected): + assert make_spec(body).model_name == expected + + +def test_model_name_is_safe_for_cost_calculation(): + # An unhashable "model" value used to reach `model not in PRICING` + # and raise TypeError. + spec = make_spec('{"model": ["a"]}') + assert calculate_cost(1000, spec.model_name) is None