Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

fix(chat): post-merge audit follow-ups — API validation, DRY, logging, a11y, tests (#3891) (#4427)

LearningCircuitc7d86a5b69c5
diff --git a/changelog.d/4427.bugfix.md b/changelog.d/4427.bugfix.md
new file mode 100644
index 0000000000..c44c02b919
--- /dev/null
+++ b/changelog.d/4427.bugfix.md
@@ -0,0 +1 @@
+Chat Mode post-merge audit follow-ups (#3891). The send-message API now rejects a non-boolean ``trigger_research`` with HTTP 400 instead of silently coercing a truthy value (e.g. ``"false"``) to ``True`` and launching unwanted research. Chat-session deletion now records the (truncated) username alongside the session id in the audit log, so a stolen-token bulk delete leaves a forensic trail. The frontend now logs (instead of silently swallowing) a failed background title-generation request, and the Markdown chat export documents that its output is a human-readable archive that is not safe to feed back into a Markdown/HTML renderer without escaping. The "Clear History" confirmation now warns that it also permanently deletes all chat sessions and their conversations (it always did, but the dialog only mentioned research history). Accessibility: the chat input gains ``aria-required`` and the welcome suggestion buttons gain descriptive ``aria-label``s. Internal cleanup: the duplicated atomic ``UPDATE … RETURNING`` counter logic in ``ChatService`` is extracted into a shared ``_atomic_increment`` helper. New tests cover the 100+-message pagination cap, render-time Jinja2 autoescaping, and the stricter ``trigger_research`` contract.
diff --git a/src/local_deep_research/chat/routes.py b/src/local_deep_research/chat/routes.py
index b0db665432..5ad04943f2 100644
--- a/src/local_deep_research/chat/routes.py
+++ b/src/local_deep_research/chat/routes.py
@@ -799,8 +799,20 @@ def send_message(session_id):
}
), 400
+ # trigger_research is a strict boolean. Reject non-bool values with a
+ # 400 instead of silently coercing them to True: a client sending
+ # {"trigger_research": "no"} or {"trigger_research": 0} intends to
+ # SUPPRESS research, and coercing the truthy-string to True would
+ # launch an unwanted (paid) research run against their intent.
raw = data.get("trigger_research", True)
- trigger_research = raw if isinstance(raw, bool) else True
+ if not isinstance(raw, bool):
+ return jsonify(
+ {
+ "success": False,
+ "error": "trigger_research must be a boolean",
+ }
+ ), 400
+ trigger_research = raw
service = ChatService(username)
diff --git a/src/local_deep_research/chat/service.py b/src/local_deep_research/chat/service.py
index 1f2402a021..73151fb610 100644
--- a/src/local_deep_research/chat/service.py
+++ b/src/local_deep_research/chat/service.py
@@ -84,6 +84,33 @@ class ChatService:
"""
self.username = username
+ @staticmethod
+ def _atomic_increment(db, counter_col, where_clause):
+ """Atomically increment an integer counter column by one and return
+ its new value.
+
+ Emits a single ``UPDATE <table> SET col = col + 1 WHERE <clause>
+ RETURNING col`` so the next sequence number is allocated without a
+ read-modify-write race between concurrent writers. ``counter_col`` is
+ a mapped column attribute (e.g. ``ChatSession.message_count``); the
+ target table and column name are derived from it.
+
+ Returns the post-increment value, or ``None`` when no row matched
+ ``where_clause`` — the caller decides whether a miss is a 404/ValueError.
+ Extracted from the previously-duplicated counter logic in
+ ``insert_message_in_db`` (message_count) and ``add_progress_step``
+ (step_count).
+ """
+ # Key the values() dict by the column object (not its string name)
+ # so the table/column are both derived straight from counter_col.
+ stmt = (
+ update(counter_col.class_)
+ .where(where_clause)
+ .values({counter_col: counter_col + 1})
+ .returning(counter_col)
+ )
+ return db.execute(stmt).scalar_one_or_none()
+
def create_session(
self,
initial_query: Optional[str] = None,
@@ -302,13 +329,9 @@ class ChatService:
ChatSession.status == ChatSessionStatus.ACTIVE.value
)
not_found_msg = f"Chat session {session_id} not found or not active"
- stmt = (
- update(ChatSession)
- .where(where_clause)
- .values(message_count=ChatSession.message_count + 1)
- .returning(ChatSession.message_count)
+ sequence = self._atomic_increment(
+ db, ChatSession.message_count, where_clause
)
- sequence = db.execute(stmt).scalar_one_or_none()
if sequence is None:
raise ValueError(not_found_msg)
@@ -360,13 +383,11 @@ class ChatService:
with get_user_db_session(self.username) as db:
# Atomic increment-and-return on research_history.step_count.
- stmt = (
- update(ResearchHistory)
- .where(ResearchHistory.id == research_id)
- .values(step_count=ResearchHistory.step_count + 1)
- .returning(ResearchHistory.step_count)
+ sequence = self._atomic_increment(
+ db,
+ ResearchHistory.step_count,
+ ResearchHistory.id == research_id,
)
- sequence = db.execute(stmt).scalar_one_or_none()
if sequence is None:
raise ValueError( # noqa: TRY301
f"Research {research_id} not found"
@@ -854,7 +875,13 @@ class ChatService:
db.commit()
for (rid,) in in_flight:
set_termination_flag(rid)
- logger.info(f"Deleted chat: {session_id[:8]}...")
+ # Include the (truncated) username so a stolen-token bulk
+ # delete leaves a forensic trail tying each deletion to an
+ # account, not just an opaque session id (L_SEC1).
+ logger.info(
+ f"Deleted chat: user={self.username[:8]}... "
+ f"session={session_id[:8]}..."
+ )
return True
except DB_EXCEPTIONS:
diff --git a/src/local_deep_research/web/static/js/components/chat.js b/src/local_deep_research/web/static/js/components/chat.js
index 7317a50619..3134fd3112 100644
--- a/src/local_deep_research/web/static/js/components/chat.js
+++ b/src/local_deep_research/web/static/js/components/chat.js
@@ -543,8 +543,11 @@
updateTitle(resp.title);
}
})
- .catch(() => {
+ .catch((e) => {
// Network/LLM failure leaves the fallback title in place.
+ // Log it so the swallowed failure is visible in the
+ // browser console during debugging instead of vanishing.
+ _log.warn('Chat: title generation request failed', e);
});
}
@@ -2163,6 +2166,14 @@
}
markdown += `\n\n`;
if (msg.content) {
+ // NOTE: message content is written verbatim. Assistant
+ // turns are themselves Markdown, so escaping here would
+ // corrupt legitimate formatting — but that means a
+ // user-authored "You" turn can carry arbitrary Markdown
+ // (headings, links, raw HTML) into the .md file. This
+ // export is a human-readable archive only; the output is
+ // NOT safe to feed back into a Markdown renderer or HTML
+ // pipeline without escaping/sanitising first.
markdown += msg.content;
} else if (msg.research_id) {
// Preserve the research link so the export is
diff --git a/src/local_deep_research/web/static/js/components/history.js b/src/local_deep_research/web/static/js/components/history.js
index 7b85346e18..58646f35b7 100644
--- a/src/local_deep_research/web/static/js/components/history.js
+++ b/src/local_deep_research/web/static/js/components/history.js
@@ -1097,7 +1097,12 @@
* Handle clear history
*/
async function handleClearHistory() {
- if (!confirm('Are you sure you want to clear all research history? This action cannot be undone.')) {
+ // Warn that this also wipes chat sessions: handleClearHistory deletes
+ // every chat session below (not just ResearchHistory rows), so a user
+ // who reads only "research history" would lose their chat
+ // conversations — and any chat "view research" links — unexpectedly
+ // (M_INTEG1).
+ if (!confirm('Are you sure you want to clear all research history?\n\nThis also permanently deletes ALL your chat sessions and their conversations. This action cannot be undone.')) {
return;
}
diff --git a/src/local_deep_research/web/templates/pages/chat.html b/src/local_deep_research/web/templates/pages/chat.html
index 22fa301222..7ecf5f3709 100644
--- a/src/local_deep_research/web/templates/pages/chat.html
+++ b/src/local_deep_research/web/templates/pages/chat.html
@@ -41,16 +41,16 @@
<h2>What would you like to research?</h2>
<p>Ask anything. Follow up to dig deeper. Every answer is grounded in sources.</p>
<div class="ldr-chat-suggestions">
- <button type="button" class="ldr-chat-suggestion" data-query="What are the latest developments in AI research?">
+ <button type="button" class="ldr-chat-suggestion" data-query="What are the latest developments in AI research?" aria-label="Ask: What are the latest developments in AI research?">
Latest AI developments
</button>
- <button type="button" class="ldr-chat-suggestion" data-query="Compare renewable energy sources for home use">
+ <button type="button" class="ldr-chat-suggestion" data-query="Compare renewable energy sources for home use" aria-label="Ask: Compare renewable energy sources for home use">
Compare energy sources
</button>
- <button type="button" class="ldr-chat-suggestion" data-query="What are effective strategies for improving sleep quality?">
+ <button type="button" class="ldr-chat-suggestion" data-query="What are effective strategies for improving sleep quality?" aria-label="Ask: What are effective strategies for improving sleep quality?">
Improve sleep quality
</button>
- <button type="button" class="ldr-chat-suggestion" data-query="Explain quantum computing in simple terms">
+ <button type="button" class="ldr-chat-suggestion" data-query="Explain quantum computing in simple terms" aria-label="Ask: Explain quantum computing in simple terms">
Explain quantum computing
</button>
</div>
@@ -92,6 +92,7 @@
rows="1"
maxlength="10000"
aria-label="Chat message"
+ aria-required="true"
></textarea>
<div class="ldr-chat-input-actions">
<button type="button" class="ldr-chat-send-btn" id="send-btn" disabled title="Send message" aria-label="Send message">
diff --git a/tests/chat/test_chat_input_validation.py b/tests/chat/test_chat_input_validation.py
index 3b8084ba11..f8e4433ad7 100644
--- a/tests/chat/test_chat_input_validation.py
+++ b/tests/chat/test_chat_input_validation.py
@@ -285,7 +285,12 @@ class TestTriggerResearchParameter:
assert data.get("research_id") is None
def test_trigger_research_non_boolean(self, authenticated_client):
- """Test handling of non-boolean trigger_research value."""
+ """Non-boolean trigger_research is rejected with 400 (L_API1).
+
+ Previously a truthy string like "false" was silently coerced to True,
+ launching research against the caller's intent to suppress it. The
+ route now requires a strict boolean.
+ """
# Create session
create_resp = authenticated_client.post(
"/api/chat/sessions",
@@ -294,14 +299,46 @@ class TestTriggerResearchParameter:
)
session_id = json.loads(create_resp.data)["session_id"]
- # Send with string value
+ # Send with a non-boolean value
response = authenticated_client.post(
f"/api/chat/sessions/{session_id}/messages",
json={"content": "Test", "trigger_research": "false"},
content_type="application/json",
)
- # Should handle gracefully (truthy string might trigger research)
+ assert response.status_code == 400
+ data = json.loads(response.data)
+ assert data["success"] is False
+ assert "trigger_research" in data["error"]
+
+ def test_trigger_research_bool_and_default_accepted(
+ self, authenticated_client
+ ):
+ """A real boolean (or an omitted value) is accepted."""
+ create_resp = authenticated_client.post(
+ "/api/chat/sessions",
+ json={"initial_query": "Test"},
+ content_type="application/json",
+ )
+ session_id = json.loads(create_resp.data)["session_id"]
+
+ # Explicit boolean False suppresses research and succeeds.
+ response = authenticated_client.post(
+ f"/api/chat/sessions/{session_id}/messages",
+ json={"content": "Test no research", "trigger_research": False},
+ content_type="application/json",
+ )
assert response.status_code == 200
+ assert json.loads(response.data)["research_mode"] == "none"
+
+ # Omitting trigger_research defaults to True (research attempted).
+ response = authenticated_client.post(
+ f"/api/chat/sessions/{session_id}/messages",
+ json={"content": "Test default"},
+ content_type="application/json",
+ )
+ # 200 (research started) or 429 (rate limited) — both prove the
+ # default boolean path is accepted rather than 400-rejected.
+ assert response.status_code in (200, 429)
class TestGetMessagesValidation:
diff --git a/tests/chat/test_chat_large_data.py b/tests/chat/test_chat_large_data.py
index f884655478..02414ded40 100644
--- a/tests/chat/test_chat_large_data.py
+++ b/tests/chat/test_chat_large_data.py
@@ -165,9 +165,12 @@ class TestLargeDataHandling:
query_string={"limit": 500},
)
assert response.status_code == 200
- # The limit should be capped at max (100)
- # We can't directly test the limit was capped without having 100+ messages,
- # but the request should succeed
+ # The limit should be capped at max (100). The cap is proven against a
+ # real 100+ message corpus in
+ # tests/chat/test_chat_pagination_cap.py (it must disable the
+ # send-route rate limiter to seed that many rows, so it lives in its
+ # own non-black-box file); this case only checks that an oversized
+ # limit doesn't error out.
def test_large_initial_query_title_truncation(self, authenticated_client):
"""Test that long initial queries are truncated for title."""
diff --git a/tests/chat/test_chat_pagination_cap.py b/tests/chat/test_chat_pagination_cap.py
new file mode 100644
index 0000000000..13ba23e025
--- /dev/null
+++ b/tests/chat/test_chat_pagination_cap.py
@@ -0,0 +1,85 @@
+"""Integration test for the GET /messages server-side pagination cap (H_TEST3).
+
+The sibling black-box test ``test_chat_large_data.test_pagination_limits_enforced``
+notes inline that it "can't directly test the limit was capped without having
+100+ messages". This module closes that gap by seeding 100+ real messages for
+an authenticated user and asserting the route clamps an oversized ``limit`` to
+the 100-row maximum while reporting ``has_more``.
+
+Seeding 100+ messages must go through the real send route (the per-user
+encrypted chat DB only exists behind the authenticated client), but that route
+is rate limited to 10/min. We therefore disable the shared limiter for the
+seeding loop only and restore its prior state afterwards — which is why this
+test lives in its own file rather than the ``no-sut-import`` black-box module.
+"""
+
+import json
+
+import pytest
+
+# NB: import via the non-``src`` package path — that is the module instance
+# the running app (local_deep_research.web.app_factory) binds its routes to.
+# The package is importable under both ``local_deep_research`` and
+# ``src.local_deep_research``, which are DISTINCT module objects with separate
+# ``limiter`` singletons; toggling the wrong one is a no-op against the app.
+from local_deep_research.security.rate_limiter import limiter
+
+
+def _limiter_disabled():
+ """Disable the global rate limiter for the duration of a test, restoring
+ its previous ``enabled`` state afterwards."""
+ previous = limiter.enabled
+ limiter.enabled = False
+ try:
+ yield
+ finally:
+ limiter.enabled = previous
+
+
+def test_pagination_cap_fires_with_over_100_messages(
+ authenticated_client, _limiter_disabled
+):
+ """With >100 messages present, GET /messages clamps ``limit`` to 100 and
+ sets ``has_more``; an in-range ``limit`` is honoured exactly."""
+ create_response = authenticated_client.post(
+ "/api/chat/sessions",
+ json={"initial_query": "Pagination cap test"},
+ content_type="application/json",
+ )
+ session_id = json.loads(create_response.data)["session_id"]
+
+ # Seed 105 messages (> the 100 cap). trigger_research=False keeps each
+ # send to a single message INSERT (no research/LLM work).
+ for i in range(105):
+ resp = authenticated_client.post(
+ f"/api/chat/sessions/{session_id}/messages",
+ json={"content": f"Message {i}", "trigger_research": False},
+ content_type="application/json",
+ )
+ assert resp.status_code == 200, (
+ f"seed send {i} returned {resp.status_code}: {resp.data[:200]!r}"
+ )
+
+ # Ask for far more than the cap: the route must clamp the page to 100 and
+ # tell the client more rows exist.
+ resp = authenticated_client.get(
+ f"/api/chat/sessions/{session_id}/messages",
+ query_string={"limit": 500},
+ )
+ assert resp.status_code == 200
+ data = json.loads(resp.data)
+ assert data["success"] is True
+ assert len(data["messages"]) == 100, (
+ f"limit=500 should be capped to 100, got {len(data['messages'])}"
+ )
+ assert data["has_more"] is True
+
+ # A smaller in-range limit is honoured exactly, also with has_more.
+ resp = authenticated_client.get(
+ f"/api/chat/sessions/{session_id}/messages",
+ query_string={"limit": 50},
+ )
+ data = json.loads(resp.data)
+ assert len(data["messages"]) == 50
+ assert data["has_more"] is True
diff --git a/tests/chat/test_chat_xss_prevention.py b/tests/chat/test_chat_xss_prevention.py
index f92438f857..eb62f838fc 100644
--- a/tests/chat/test_chat_xss_prevention.py
+++ b/tests/chat/test_chat_xss_prevention.py
@@ -373,3 +373,68 @@ class TestInputLengthLimits:
assert response.status_code == 400
data = json.loads(response.data)
assert "too long" in data["error"].lower()
+
+
+# =============================================================================
+# Render-time escaping (H_TEST2)
+# =============================================================================
+
+
+class TestRenderTimeEscaping:
+ """Verify the *display* layer escapes/sanitises stored payloads.
+
+ The other tests in this module prove XSS payloads are stored verbatim
+ (the API deliberately does not reject them). That alone is only safe if
+ the render layer escapes them. These tests assert the two render legs:
+
+ 1. Server-side Jinja2 autoescape — guards the regression the audit
+ flagged: "if autoescape were ever disabled it would land silently".
+ 2. Client-side render path — guards that chat message content keeps
+ flowing through the DOMPurify-backed ``renderMarkdown`` (or a
+ ``textContent`` fallback) and is never assigned raw to ``innerHTML``.
+
+ The live in-browser DOMPurify behaviour itself needs Puppeteer coverage
+ (tracked alongside P2_UITEST1); this static guard catches the common
+ regression of swapping the sanitised path for a raw ``innerHTML``.
+ """
+
+ @pytest.mark.parametrize(
+ "payload",
+ [
+ "<script>alert('XSS')</script>",
+ "<img src=x onerror=alert('XSS')>",
+ "<a href='javascript:alert(1)'>x</a>",
+ ],
+ )
+ def test_jinja2_autoescape_escapes_payload(self, app, payload):
+ """A script/HTML payload rendered through the app's Jinja2 env is
+ HTML-escaped, not emitted raw."""
+ from flask import render_template_string
+
+ with app.test_request_context():
+ rendered = render_template_string("{{ value }}", value=payload)
+
+ # The raw tag must not survive; the escaped form must be present.
+ assert "<script>" not in rendered
+ assert "<img" not in rendered
+ assert "&lt;" in rendered
+ # Autoescape must be active app-wide (the silent-disable guard).
+ assert app.jinja_env.autoescape is not False
+
+ def test_chat_render_path_stays_sanitised(self):
+ """The chat message renderer must route content through the
+ DOMPurify-backed ``renderMarkdown`` with a ``textContent`` fallback,
+ and never assign message content raw to ``innerHTML``."""
+ from pathlib import Path
+
+ chat_js = (
+ Path(__file__).resolve().parents[2]
+ / "src/local_deep_research/web/static/js/components/chat.js"
+ )
+ source = chat_js.read_text(encoding="utf-8")
+
+ # Sanitised render + safe fallback are both wired in.
+ assert "window.ui.renderMarkdown(content)" in source
+ assert "textEl.textContent = content" in source
+ # No raw, unsanitised assignment of message content to innerHTML.
+ assert "innerHTML = content" not in source