Skip to content
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions buckaroo/server/websocket_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,11 +42,27 @@ def on_message(self, message):
self.write_message(json.dumps({"type": "error", "error_code": "invalid_json", "message": "Invalid JSON"}))
return

# Reject non-object JSON (null, arrays, scalars) explicitly.
# Without this guard, ``msg.get(...)`` below raises ``AttributeError``
# on ``None`` etc., Tornado swallows it, and the WS closes
# permanently. See #805.
if not isinstance(msg, dict):
self.write_message(json.dumps({"type": "error",
"error_code": "invalid_message_shape",
"message": f"WS messages must be JSON objects; got {type(msg).__name__}"}))
return

msg_type = msg.get("type")
if msg_type == "infinite_request":
self._handle_infinite_request(msg.get("payload_args", {}))
elif msg_type == "buckaroo_state_change":
self._handle_buckaroo_state_change(msg.get("new_state") or {})
else:
# Pre-#805 unknown / missing ``type`` was silently dropped —
# clients had no way to debug. Tell them what they sent.
self.write_message(json.dumps({"type": "error",
"error_code": "unknown_message_type",
"message": f"Unknown WS message type: {msg_type!r}"}))

def _handle_buckaroo_state_change(self, new_state):
sessions = self.application.settings["sessions"]
Expand Down
48 changes: 48 additions & 0 deletions tests/unit/server/test_load_expr.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,54 @@ async def test_ws_search_pushdown(self):
finally:
shutil.rmtree(builds_root, ignore_errors=True)

@tornado.testing.gen_test
async def test_ws_message_robustness(self):
"""Regression for #805: ``on_message`` did ``msg.get(...)`` on
whatever ``json.loads`` returned, which is unsafe when the JSON
is not an object (``null``, bare arrays, scalars). ``null`` in
particular killed the WS — ``None.get`` raises ``AttributeError``,
Tornado swallows it, the stream closes.

Adjacent: unknown message types (``{"type": 42}``, missing
``type``, empty ``{}``) were silently dropped. Clients couldn't
debug because no response came.

This test sends each malformed shape and asserts the server
returns a structured error frame, NOT a silent drop or a
crashed WS.
"""
import asyncio
await _post(self.get_http_port(), "/load",
{"session": "ws-guard",
"path": "/tmp/restaurant-complaints-pandas.parquet",
"mode": "buckaroo", "no_browser": True})

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Remove external file dependency from WS robustness test

This test depends on /tmp/restaurant-complaints-pandas.parquet, but it never creates that file or checks the /load response before proceeding. In environments where that path is absent (e.g., clean CI workers), /load returns 404, no initial WS state is sent, and await ws.read_message() times out for reasons unrelated to the regression being tested. This makes the test nondeterministic and can fail the pipeline even when websocket handling is correct.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Valid P1 — and this is exactly why CI is red on 3.11/3.12/3.13. The test calls /load against a path that doesn't exist on the runner, gets 404, then ws.read_message() blocks forever. Fix: write the parquet in the test setup (tmp_path fixture), or skip the load and exercise the WS guards on an unloaded session. Either works; I'll go with the tmp_path approach so the test still exercises the loaded-session message path.

ws = await tornado.websocket.websocket_connect(
f"ws://localhost:{self.get_http_port()}/ws/ws-guard")
await ws.read_message() # discard initial_state

# Each entry: (label, raw_ws_message). Server must respond
# to each with a structured error frame within 2s.
cases = [
("bare_null", "null"),
("bare_array", "[1,2,3]"),
("bare_scalar", "42"),
("empty_object", "{}"),
("missing_type", json.dumps({"payload": "x"})),
("type_as_int", json.dumps({"type": 42, "payload": "x"})),
("unknown_type",
json.dumps({"type": "buckaroo_invented_command"})),
]
for label, raw in cases:
ws.write_message(raw)
frame = await asyncio.wait_for(ws.read_message(), timeout=3.0)
self.assertIsNotNone(frame, f"{label}: no response (silent drop)")
d = json.loads(frame)
self.assertEqual(d.get("type"), "error",
f"{label}: expected error frame, got {d.get('type')!r}")
self.assertIn("error_code", d,
f"{label}: error frame missing error_code")
ws.close()

@tornado.testing.gen_test
async def test_session_reuse_xorq_then_pandas(self):
"""A client that POSTs /load_expr and then POSTs /load with the
Expand Down
Loading