Console: no route in an inline handler; roster for moderators; text work off the loop

- frontend/app.js: the document pager put esc(routeHash(route)) inside
  onclick="location.hash='...'". esc() is HTML escaping and the browser decodes
  ' back to ' before the handler runs; the route comes from the URL hash and
  encodeURIComponent keeps ' ( ) - ., so a crafted #/doc/eu/<celex>/<segment> link
  ran script on a click of the pager arrows. The pager is now plain links, and
  routeApi accepts exactly the segments each kind has (act 4, eu 2, judgment 3).
- GET /users takes require_moderator. On the platform list_users reads the shared
  app_user, so any Insider user could list every account. The console fetches the
  roster only on the Administration screen.
- services/legal.py: html_to_text (pure-Python HTMLParser, live EU texts up to
  MAX_TEXT_BYTES) and _text_answer (chunk + outline of a whole text) run in
  asyncio.to_thread instead of on the event loop.
- docker-compose.managed-db.yml: the OCR worker gets the same credential blanks as
  the backend (no migrator URL, no superuser password); deploy_check checks it.

Tests: test_console (routeApi extra segments, no route in an inline handler),
test_integration (GET /users is 403 for a user), test_event_loop (AST guard).
Not run here.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Piotr Chojnacki
2026-11-26 20:42:59 +01:00
co-authored by Claude Opus 5.5
parent ed8a65ead5
commit 2d50403423
8 changed files with 87 additions and 16 deletions
+5 -3
View File
@@ -60,9 +60,11 @@ def _identity_is_ours() -> None:
@router.get("/users", response_model=list[UserOut])
def list_users(db: Session = Depends(get_db),
_: AppUser = Depends(get_current_user)) -> list[dict]:
"""Every signed-in user may list users: the console needs names to render "assigned to"
pickers, and an email address inside the instance is not the secret worth hiding here."""
_: AppUser = Depends(require_moderator)) -> list[dict]:
"""The roster is this module's administration screen, so it takes `require_moderator`. On the
platform `list_users` reads the SHARED `app_user`: every account on the platform, including
people who may not open this module, with their e-mail and tier. Insider has no "assigned to"
picker that would need it for an ordinary user."""
# One query for the whole page's tier column, not one per row: `moderator_ids` returns this
# module's roster as a set, and standalone it returns an empty set without touching the database.
moderators = moderation_service.moderator_ids(db)
+7 -6
View File
@@ -534,7 +534,7 @@ class Legal:
async def act_text(self, eli: str, *, part: int = 1, max_chars: int = 20000) -> dict:
doc, rec, extra = await self._act_text_record(eli)
return {**_text_answer(doc, rec, part, max_chars), **extra}
return {**await asyncio.to_thread(_text_answer, doc, rec, part, max_chars), **extra}
async def _act_text_record(self, eli: str) -> tuple[LegalDoc, TextRecord | None, dict]:
"""The act and its text record — what `act_text` chunks and outlines, and what `resolve`
@@ -551,7 +551,8 @@ class Legal:
async def fetch() -> dict:
if doc.extra.get("has_html"):
text = html_to_text(await adapter.text_html(doc.extra["eli"]))
text = await asyncio.to_thread(html_to_text,
await adapter.text_html(doc.extra["eli"]))
if text:
await self.texts.put(TextRecord(doc.id, version, "ready", text, "html", "pl"))
return {"status": "ready"}
@@ -600,7 +601,7 @@ class Legal:
if large is not None:
return await asyncio.to_thread(self._large_text_answer, *large, part, max_chars)
doc, rec, extra = await self._eu_text_record(celex)
return {**_text_answer(doc, rec, part, max_chars), **extra}
return {**await asyncio.to_thread(_text_answer, doc, rec, part, max_chars), **extra}
async def _cellar_large(self, celex: str):
"""(document, part sizes) when the local CELLAR index holds this text and it is too
@@ -683,7 +684,7 @@ class Legal:
# and remembered, so the next view does not download it again
await self.texts.put(TextRecord(doc.id, "1", "failed", error=TOO_LARGE))
return {"status": "failed"}
text = html_to_text(html)
text = await asyncio.to_thread(html_to_text, html) # up to MAX_TEXT_BYTES
await self.texts.put(TextRecord(doc.id, "1", "ready" if text else "failed",
text or None, "html", lang,
error=None if text else "empty text"))
@@ -716,7 +717,7 @@ class Legal:
async def fetch() -> dict:
doc, html = await adapter.fetch_full(jid)
# SAOS text lives ONLY in this TTL entry (7 d) — never in doc_text.
return {"doc": doc.to_dict(), "text": html_to_text(html)}
return {"doc": doc.to_dict(), "text": await asyncio.to_thread(html_to_text, html)}
return await self._cached(f"judgment:saos:{int(jid)}", TTL_JUDGMENT, fetch)
async def get_judgment(self, source: str, jid: str) -> dict:
@@ -738,7 +739,7 @@ class Legal:
doc = LegalDoc.from_dict(entry["doc"])
rec = TextRecord(doc.id, "ttl", "ready" if entry["text"] else "failed",
entry["text"] or None, "html", "pl")
return _text_answer(doc, rec, part, max_chars)
return await asyncio.to_thread(_text_answer, doc, rec, part, max_chars)
if source == "eurlex":
return await self.eu_text(jid, part=part, max_chars=max_chars)
raise NotFoundError(f"Unknown judgment source '{source}'.")
+3
View File
@@ -219,6 +219,9 @@ check(f"target: {CA_TARGET}" in override and "create_host_path: false" in overri
check('MIGRATION_DATABASE_URL: ""' in service_block("backend"),
"docker-compose.managed-db.yml leaves the migrator's URL in the long-running backend",
"the managed-db override keeps migrator credentials out of the backend")
check('MIGRATION_DATABASE_URL: ""' in service_block("ocr-worker"),
"docker-compose.managed-db.yml leaves the migrator's URL in the long-running OCR worker",
"the managed-db override keeps migrator credentials out of the OCR worker")
def env_settings(text: str) -> dict[str, str]:
+11
View File
@@ -80,6 +80,8 @@ vm.runInContext(fs.readFileSync(process.argv[2], 'utf8') + `
routes: [docRoute({id:'eli:DU/1997/939', kind:'act'}), docRoute({id:'saos:554187', kind:'judgment'}),
docRoute({id:'eurlex:62018CJ0311', kind:'judgment'}), docRoute({id:'eurlex:32016R0679', kind:'act'})],
apis: [routeApi(['act','DU','1997','939']), routeApi(['eu','32016R0679']), routeApi(['judgment','saos','1'])],
apisExtra: [routeApi(['eu','32016R0679',"'-alert(1)-'"]), routeApi(['judgment','saos','1','x']),
routeApi(['act','DU','1997','939','x']), routeApi(['eu'])],
hash: routeHash(['judgment','saos','1']),
hl: hl('<b>Kredyt</b> frankowy & bank', 'kredyt <b>'),
cite: [citationOf({source:'eli', title:'Ustawa - Prawo bankowe', extra:{eli:'DU/1997/939'}}),
@@ -129,6 +131,8 @@ def test_console_helpers_in_node(tmp_path):
assert out["routes"] == [["act", "DU", "1997", "939"], ["judgment", "saos", "554187"],
["judgment", "eurlex", "62018CJ0311"], ["eu", "32016R0679"]]
assert out["apis"] == ["/acts/DU/1997/939", "/acts/eu/32016R0679", "/judgments/saos/1"]
# a segment the API would ignore is refused: it would ride along in every link built from it
assert out["apisExtra"] == [None, None, None, None]
assert out["hash"] == "#/doc/judgment/saos/1"
assert "<b>" not in out["hl"] and "&lt;b&gt;" in out["hl"] and "<mark>Kredyt</mark>" in out["hl"]
assert out["cite"] == ["Ustawa - Prawo bankowe (Dz. U. z 1997 r. poz. 939)",
@@ -166,6 +170,13 @@ def test_console_helpers_in_node(tmp_path):
{"name": "saos", "status": "ok", "total": 3}]
def test_no_inline_handler_carries_a_route():
"""esc() is HTML escaping: inside onclick="…" the browser decodes &#39; back to ' before the
JavaScript runs, so a hash-derived route there is script injection (the document pager was)."""
for handler in re.findall(r'\bon[a-z]+="([^"]*)"', APP):
assert "routeHash" not in handler and "location.hash" not in handler, handler
def test_progressive_search_is_wired():
assert "p.set('progressive', 'true')" in APP
assert "/search/pending?ticket=" in APP and "encodeURIComponent(p.ticket)" in APP
+34
View File
@@ -0,0 +1,34 @@
"""The facade never parses or chunks a whole text on the event loop.
`html_to_text` is a pure-Python HTMLParser and a live EU text may be up to `MAX_TEXT_BYTES`; run on the
loop it froze every other request (REST, MCP, the console) for as long as it took. `_text_answer`
chunks and outlines a whole stored text. Inside an `async def` both go through `asyncio.to_thread`.
"""
from __future__ import annotations
import ast
import pathlib
LEGAL = pathlib.Path(__file__).resolve().parents[1] / "app" / "services" / "legal.py"
HEAVY = {"html_to_text", "_text_answer"}
def _direct_calls(fn: ast.AsyncFunctionDef) -> list[str]:
found = []
for node in ast.walk(fn):
if isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id in HEAVY:
found.append(f"{fn.name}:{node.lineno}")
return found
def test_heavy_text_work_never_runs_on_the_event_loop():
tree = ast.parse(LEGAL.read_text(encoding="utf-8"))
offenders = [hit for node in ast.walk(tree) if isinstance(node, ast.AsyncFunctionDef)
for hit in _direct_calls(node)]
assert offenders == [], offenders
def test_the_guard_sees_the_calls_it_is_about():
src = LEGAL.read_text(encoding="utf-8")
assert src.count("asyncio.to_thread(html_to_text") >= 3
assert src.count("asyncio.to_thread(_text_answer") >= 3
+2 -1
View File
@@ -53,8 +53,9 @@ def test_anonymous_requests_are_refused():
def test_the_admin_boundary(admin_client, make_user):
bob = make_user("bob")
h = bearer(bob["token"])
# GET /users is the roster: on the platform every account there is, not only this module's
for method, path in [("GET", "/api/v1/admin/audit"), ("GET", "/api/v1/admin/settings"),
("PUT", "/api/v1/admin/settings")]:
("PUT", "/api/v1/admin/settings"), ("GET", "/api/v1/users")]:
r = admin_client.request(method, path, headers=h, json={"values": {"instance_name": "x"}})
assert r.status_code == 403, (path, r.status_code)
r = admin_client.post("/api/v1/users", headers=h, json={
+12
View File
@@ -68,3 +68,15 @@ services:
DB_POOL_SIZE: ${DB_POOL_SIZE:-5}
DB_MAX_OVERFLOW: ${DB_MAX_OVERFLOW:-10}
volumes: *managed_db_ca
ocr-worker:
# The optional OCR worker (profile `ocr`) is long-running too, and it is the process that feeds
# PDFs to native parsers (pdfium, Paddle/OpenCV, Tesseract): the same blanks as the backend, so a
# compromised worker cannot log in as insider_migrator or as the local superuser. It needs only
# DATABASE_URL (ocr_job, doc_text) and ELI.
environment:
MIGRATION_DATABASE_URL: ""
DB_MIGRATOR_PASSWORD: ""
DB_APP_PASSWORD: ""
POSTGRES_PASSWORD: ""
DB_APP_ROLE: ${DB_APP_ROLE:?set DB_APP_ROLE in .env to the runtime role, insider_app in the shared database}
volumes: *managed_db_ca
+13 -6
View File
@@ -584,7 +584,6 @@ async function afterLogin() {
b.textContent = LANG.toUpperCase();
});
$('aUser').textContent = initials(state.user.full_name || state.user.email);
try { state.users = await api('GET', '/users'); } catch { state.users = []; }
try { state.config = await api('GET', '/config'); } catch { state.config = {}; }
if (!location.hash || location.hash === '#') location.hash = '#/';
await router();
@@ -683,11 +682,13 @@ function docRoute(d) {
return null;
}
function routeHash(r) { return '#/doc/' + r.map(encodeURIComponent).join('/'); }
/* Exactly the segments each kind has: a route comes from the URL's hash, and a segment the API
call ignores would still be carried into every link built from the route. */
function routeApi(r) {
const e = r.map(encodeURIComponent);
if (r[0] === 'act') return '/acts/' + e.slice(1).join('/');
if (r[0] === 'eu') return '/acts/eu/' + e[1];
if (r[0] === 'judgment') return '/judgments/' + e[1] + '/' + e[2];
if (r[0] === 'act' && r.length === 4) return '/acts/' + e.slice(1).join('/');
if (r[0] === 'eu' && r.length === 2) return '/acts/eu/' + e[1];
if (r[0] === 'judgment' && r.length === 3) return '/judgments/' + e[1] + '/' + e[2];
return null;
}
@@ -1193,10 +1194,14 @@ async function viewDocument(C, route, q) {
/* a Markdown heading line is shown as a heading, its "#####" dropped */
const shown = (ln) => (/^\s*#{1,6}\s/.test(ln) ? `<span class="mdh">${esc(plainLine(ln))}</span>` : esc(ln));
const body = lines.map((ln, i) => (anchors.has(i) ? `<span class="anchor${i === artLine ? ' hit' : ''}" id="ln${i}">${shown(ln)}</span>` : shown(ln))).join('\n');
/* Plain links, never an inline handler: the route comes from the URL, and esc() is HTML
escaping — the browser decodes it again before a handler's JavaScript runs. */
const pageLink = (n, label, off) => (off ? `<button class="btn sm" disabled>${label}</button>`
: `<a class="btn sm" href="${esc(routeHash(route))}?part=${n}">${label}</a>`);
const pager = t.parts > 1 ? `<div class="row" style="gap:8px;margin:10px 0">
<button class="btn sm" ${t.part <= 1 ? 'disabled' : ''} onclick="location.hash='${esc(routeHash(route))}?part=${t.part - 1}'">←</button>
${pageLink(t.part - 1, '←', t.part <= 1)}
<span class="faint tiny"><span>Część</span> ${esc(String(t.part))}/${esc(String(t.parts))}</span>
<button class="btn sm" ${t.part >= t.parts ? 'disabled' : ''} onclick="location.hash='${esc(routeHash(route))}?part=${t.part + 1}'">→</button></div>` : '';
${pageLink(t.part + 1, '→', t.part >= t.parts)}</div>` : '';
let textBlock;
if (t.text_status === 'ready' && t.text) {
textBlock = `<div class="docgrid">
@@ -1552,6 +1557,8 @@ function confirmRevokeToken(id) {
/* ── administration ─────────────────────────────────────────────────────── */
async function viewAdmin(C) {
setCrumb([{ label: 'Administracja' }]);
/* the roster is a moderator's screen: fetched here, never at sign-in for everybody */
state.users = await api('GET', '/users').catch(() => []);
const audit = await api('GET', '/admin/audit?limit=50').catch(() => []);
const ai = (await api('GET', '/admin/settings').catch(() => [])).filter((x) => x.key.startsWith('ai_'));
const AI_LABEL = { ai_query_rewrite: 'Przepisywanie zapytań przez model', ai_answers: 'Odpowiedzi z cytatami',