Skip to content

armgit / laya

Public Imported from GitHub
0

Non-autoregressive System 1 decision engine. Typed choice, score and yes/no decisions over any text in a single forward pass, in 100+ languages, with a router that picks the right checkpoint per request.

fix(serve): return 400 on a malformed JSON request body (#268)

Jiahao Chenafb8444fec38
diff --git a/laya/serve.py b/laya/serve.py
index 87bdf301..b9e673bd 100644
--- a/laya/serve.py
+++ b/laya/serve.py
@@ -156,7 +156,14 @@ def create_app(router: Optional[Any] = None):
async def systemone(request: Request, authorization: Optional[str] = Header(default=None)):
nonlocal gate
_check_auth(authorization)
- body = await request.json()
+ try:
+ # Every parse failure a client can cause is a ValueError: JSONDecodeError for
+ # malformed/empty/truncated bodies, UnicodeDecodeError for invalid UTF-8. A
+ # broader catch would also swallow ClientDisconnect and Starlette's own
+ # stream errors, reporting a transport or server fault as the client's.
+ body = await request.json()
+ except ValueError:
+ raise HTTPException(status_code=400, detail="request body must be valid JSON")
if not isinstance(body, dict) or "questions" not in body:
raise HTTPException(status_code=400, detail="request body must be an object with a 'questions' field")
state = body.get("state")
diff --git a/tests/test_serve.py b/tests/test_serve.py
index bba6a431..66db5c43 100644
--- a/tests/test_serve.py
+++ b/tests/test_serve.py
@@ -84,6 +84,33 @@ def test_missing_questions_is_400(monkeypatch):
assert r.status_code == 400
[email protected]("payload", [
+ b"not json",
+ b"", # empty body
+ b"\xff\xfe\x00bad", # invalid UTF-8
+ b'{"questions": ', # truncated
+])
+def test_malformed_json_body_is_400(monkeypatch, payload):
+ """A body that isn't valid JSON must not fall through to an unstyled 500."""
+ client, _ = _client(monkeypatch)
+ r = client.post("/v1/systemone", content=payload,
+ headers={"content-type": "application/json"})
+ assert r.status_code == 400
+ # pin which 400: the other branch below also answers 400, so the status alone
+ # would not notice the parse guard disappearing.
+ assert r.json()["detail"] == "request body must be valid JSON"
+
+
[email protected]("payload", [b"[1,2,3]", b'"hello"', b"null"])
+def test_json_that_is_not_an_object_is_400(monkeypatch, payload):
+ """Valid JSON that isn't an object is the other 400, not a parse failure."""
+ client, _ = _client(monkeypatch)
+ r = client.post("/v1/systemone", content=payload,
+ headers={"content-type": "application/json"})
+ assert r.status_code == 400
+ assert "questions" in r.json()["detail"]
+
+
def test_auth_required_when_key_set(monkeypatch):
client, _ = _client(monkeypatch, api_key="s3cret")
assert client.post("/v1/systemone", json=REQ).status_code == 401