Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

fix(wecom,parsing): bound the reply-frame cache; harden img_path anchoring

Bingxi Zhao (Frank)9d285f107842
diff --git a/deeptutor/partners/channels/wecom.py b/deeptutor/partners/channels/wecom.py
index 8aabbdf95..2ba9ad288 100644
--- a/deeptutor/partners/channels/wecom.py
+++ b/deeptutor/partners/channels/wecom.py
@@ -61,10 +61,9 @@ class WecomChannel(BaseChannel):
self.config: WecomConfig = config
self._client: Any = None
self._processed_message_ids: OrderedDict[str, None] = OrderedDict()
- self._loop: asyncio.AbstractEventLoop | None = None
self._generate_req_id = None
- # Store frame headers for each chat to enable replies
- self._chat_frames: dict[str, Any] = {}
+ # Store frame headers for each chat to enable replies (LRU-bounded)
+ self._chat_frames: OrderedDict[str, Any] = OrderedDict()
async def start(self) -> None:
"""Start the WeCom bot with WebSocket long connection."""
@@ -79,7 +78,6 @@ class WecomChannel(BaseChannel):
from wecom_aibot_sdk import WSClient, generate_req_id
self._running = True
- self._loop = asyncio.get_running_loop()
self._generate_req_id = generate_req_id
# Create WebSocket client
@@ -157,18 +155,25 @@ class WecomChannel(BaseChannel):
"""Handle mixed content message."""
await self._process_message(frame, "mixed")
+ @staticmethod
+ def _frame_body(frame: Any) -> dict[str, Any]:
+ """Extract the body dict from a WsFrame dataclass or dict frame."""
+ if hasattr(frame, "body"):
+ body = frame.body or {}
+ elif isinstance(frame, dict):
+ body = frame.get("body", frame)
+ else:
+ body = {}
+ if not isinstance(body, dict):
+ logger.warning("Invalid body type: {}", type(body))
+ return {}
+ return body
+
async def _on_enter_chat(self, frame: Any) -> None:
"""Handle enter_chat event (user opens chat with bot)."""
try:
- # Extract body from WsFrame dataclass or dict
- if hasattr(frame, "body"):
- body = frame.body or {}
- elif isinstance(frame, dict):
- body = frame.get("body", frame)
- else:
- body = {}
-
- chat_id = body.get("chatid", "") if isinstance(body, dict) else ""
+ body = self._frame_body(frame)
+ chat_id = body.get("chatid", "")
if chat_id and self.config.welcome_message:
await self._client.reply_welcome(
@@ -184,17 +189,8 @@ class WecomChannel(BaseChannel):
async def _process_message(self, frame: Any, msg_type: str) -> None:
"""Process incoming message and forward to bus."""
try:
- # Extract body from WsFrame dataclass or dict
- if hasattr(frame, "body"):
- body = frame.body or {}
- elif isinstance(frame, dict):
- body = frame.get("body", frame)
- else:
- body = {}
-
- # Ensure body is a dict
- if not isinstance(body, dict):
- logger.warning("Invalid body type: {}", type(body))
+ body = self._frame_body(frame)
+ if not body:
return
# Extract message info
@@ -292,6 +288,11 @@ class WecomChannel(BaseChannel):
# Store frame for this chat to enable replies
self._chat_frames[chat_id] = frame
+ self._chat_frames.move_to_end(chat_id)
+
+ # Trim cache
+ while len(self._chat_frames) > 1000:
+ self._chat_frames.popitem(last=False)
# Forward to message bus
# Note: media paths are included in content for broader model compatibility
diff --git a/deeptutor/services/parsing/cache.py b/deeptutor/services/parsing/cache.py
index b573e74cb..eda764a39 100644
--- a/deeptutor/services/parsing/cache.py
+++ b/deeptutor/services/parsing/cache.py
@@ -136,8 +136,15 @@ def _absolutize_img_paths(blocks: list[dict], content_dir: Path) -> list[dict]:
if not isinstance(block, dict):
continue
img_path = block.get("img_path")
- if img_path and not Path(img_path).is_absolute():
- block["img_path"] = str(content_dir / img_path)
+ if not isinstance(img_path, str) or not img_path:
+ continue
+ p = Path(img_path)
+ if p.is_absolute():
+ continue
+ if ".." in p.parts:
+ logger.warning("Skipping traversal img_path in content_list: %s", img_path)
+ continue
+ block["img_path"] = str(content_dir / img_path)
return blocks
diff --git a/tests/services/parsing/test_cache.py b/tests/services/parsing/test_cache.py
index 8cc5f1e3f..00650c521 100644
--- a/tests/services/parsing/test_cache.py
+++ b/tests/services/parsing/test_cache.py
@@ -66,6 +66,8 @@ def test_load_ir_absolutizes_relative_img_paths(tmp_path: Path) -> None:
{"type": "table", "img_path": "images/tbl1.png"},
{"type": "image", "img_path": "/abs/already.png"},
{"type": "image", "img_path": ""},
+ {"type": "image", "img_path": "../../etc/x.png"},
+ {"type": "image", "img_path": 42},
{"type": "text", "text": "t"},
]
),
@@ -79,7 +81,11 @@ def test_load_ir_absolutizes_relative_img_paths(tmp_path: Path) -> None:
assert blocks[1]["img_path"] == str(workdir / "images" / "tbl1.png")
assert blocks[2]["img_path"] == "/abs/already.png"
assert blocks[3]["img_path"] == ""
- assert blocks[4] == {"type": "text", "text": "t"}
+ # Traversal paths are never anchored into the cache dir.
+ assert blocks[4]["img_path"] == "../../etc/x.png"
+ # Non-str entries are skipped instead of exploding the whole list.
+ assert blocks[5]["img_path"] == 42
+ assert blocks[6] == {"type": "text", "text": "t"}
def test_load_ir_markdown_only(tmp_path: Path) -> None: