Skip to content

fix(wiki-v2#626): bound untrusted HTML/Markdown conversion off the event loop - #62

Merged
PMQ9 merged 5 commits into
wiki-v2from
fix/626-untrusted-parse-cost
Sep 27, 2026
Merged

PMQ9 merged 5 commits into
wiki-v2from
fix/626-untrusted-parse-cost

Conversation

@PMQ9

@PMQ9 PMQ9 commented Sep 27, 2026

Copy link
Copy Markdown

TL;DR

Untrusted HTML/Markdown is now converted in one bounded worker thread instead of on the engine's event loop. Before this change, one write could block the engine for seconds to minutes or crash it out of memory. The parse is also inert (no <iframe srcdoc> child windows), and the O(n²) unique-id pass is now linear.

Context

wiki-v2 issue 626 (a follow-up of issue 621) reported happy-dom building a child window for every <iframe srcdoc>. Measuring showed that is one symptom of a general problem:

Input Before
280 KB of <iframe srcdoc> 3.0 s in happy-dom alone
160 KB of <p>x</p> 12 s (O(n²) unique-id pass)
180 KB table row process out of memory
1 MiB of block markup 8–130 s, or >1 GB heap
10 MiB Markdown import 7.6 s in marked

The design record is wiki-v2 ADR 0031. Caps alone were rejected: bounding the stall would reject real pages.

Related issues

  • Relates to wiki-v2 issue 626 (closed by the super PR). Follow-ups: wiki-v2 issues 642–646.

What changed

  • generateJSON.ts: parses into a detached <html> root. It is output-identical (76 real files + 10,000 fuzz docs), but nothing is connected, so srcdoc builds nothing.
  • editor-compat/unique-ids.ts: the same result as upstream addUniqueIdsToDoc, in one pass.
  • editor-compat/content-parse/: one warm worker thread.
    • Bounds: 10 s deadline (terminate()), 1 GiB heap, 1 MB stack, 100k nodes → 422 content_too_complex.
    • Admission: one conversion per principal (CLS actor) within 5 s → 503 engine_busy.
    • It fails closed.
  • Wired: PageService.parseProsemirrorContent; the importers (processMarkdown/processHTML, plus a passthrough of the refusals); zip-import Markdown. Validate-content maps the refusals to too_large / parse_budget_exceeded.
  • OpSemaphore.acquire: an optional per-call wait.
  • Guards:
    • content-parse.fitness.spec.ts (no direct conversion outside the worker);
    • SEAM_ALLOWLIST gains page.service.ts, import.service.ts and file-import-task.service.ts, documented in UPSTREAM_MODIFICATIONS §121/§147/§176.

How this was tested

  • New specs:
    • no child frame, with a control; this reds on the old code;
    • parity against the old document parse;
    • unique-id equivalence and scale;
    • pool bounds with fixture workers (hang, OOM, crash, never-ready, throw-on-load, fairness; the fairness spec reds without the gate);
    • the real worker (parity, srcdoc, node cap, depth, event-loop probe with an in-process control);
    • fitness.
  • CI jest set (src/authz src/service-bridge src/editor-compat src/common/helpers/prosemirror): 131 suites, 1,627 passed.
  • Full non-pg run: 1,759 passed. 11 fail identically on the base commit (upstream DI scaffolds and lib0 ESM).
  • nest build: dist/editor-compat/content-parse/content-parse.worker.js is emitted, loads, converts, and the process exits cleanly.
  • Fresh local stack: content-smoke 237/237.
  • /v1 abuse probe:
    • engine /api/health worst ≤6 ms throughout;
    • 1 MiB floods → 422 at 10 s;
    • 20k-cell row 201 (it crashed before);
    • deep quotes → 422 at once;
    • a second user served while the first holds the worker.

AWS / infra apply

N/A. No infra change. The warm worker adds about 180 MB RSS: the task has 8 GB, and its 14-day peak was 7%.

Checklist

Scope

  • Complete and scoped to one logical concern — no unrelated drive-by changes (or follow-ups noted below).

Tests

  • New/changed behavior has appropriate tests — unit / integration / e2e / security / regression as applicable (or N/A, with why).
  • Existing tests pass, and any new tests pass.

Docs & contracts

  • Docs added/updated where needed (README / docs/ / an ADR), or N/A.
  • Any API/contract, config, migration, permission, or deployment impact is called out in this PR, or N/A.
  • Any AWS/infra apply is described precisely, scoped (no mass-apply), and captured in a reviewable one-time script — see "AWS / infra apply" above, or N/A.

Safety (this is a security-first, deny-by-default platform)

  • Security, authorization, data integrity, failure paths, and backward compatibility considered, or N/A.
  • Upstream boundary respected — no undocumented edits to Docmost-owned files (see UPSTREAM_MODIFICATIONS.md); proprietary/authz logic stays out-of-process.

Housekeeping

  • Related issue(s) linked above.
  • Known limitations, follow-ups, or intentionally deferred work identified below.

Known limitations / follow-ups

  • Converter fairness beyond one per principal: wiki-v2 issue 642. During active abuse, roughly half of other users' HTML/Markdown writes get a retryable 503.
  • Zip import has no per-file cap, and the cheerio passes stay on the main thread: issue 643.
  • The unkeyed /pages/update applies metadata before converting content (upstream order): issue 645. Refusals therefore say "the content was not applied".
  • Behavior change: a page denser than ~1 MiB of markup gets 422 instead of freezing or crashing the engine, and deep nesting gets 422 instead of 500.
  • Not actioned: normalizeImportHtml interpolates an href into data-src unescaped. It injects only into the importer's own file, which then passes the schema.

🤖 Generated with Claude Code

PMQ9 and others added 5 commits September 26, 2026 19:01
…c child windows)

generateJSON parsed with DOMParser.parseFromString, where every connected
<iframe srcdoc> made happy-dom build a child window and document.write the
srcdoc into it (~0.3 ms of blocking CPU per iframe; no setting turns it off).
Parse into a detached <html> element instead: happy-dom runs the same
document-structure parser, so the ProseMirror output is identical (76 real
files + 10,000 fuzz documents, 0 differences; only malformed <template> soup
differs, where the old parse sometimes threw), but nothing is connected, so
no element runs its on-connect behavior at all. The docmost#621 network settings
stay as the second layer.

Spec: no child frame (spy on BrowserFrameFactory.createChildFrame, with a
DOMParser control that does build one — reds on the old code); a
differential parity check against the old document parse over a tricky
corpus, Markdown output and 300 seeded tag-soup documents.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
editor-ext's addUniqueIdsToDoc applies one tr.setNodeAttribute per node;
each step copies every ancestor's child array and the transaction keeps
every intermediate doc, so a parent with n id-taking children costs O(n^2)
time and memory: 160 KB of <p>x</p> took ~12 s, a 180 KB table row
exhausted a 4 GB heap (process crash).

Fork-owned editor-compat/unique-ids.ts rebuilds the tree once with the same
result: same types/attributeName/generateID, generateID({node, pos}) called
in the same document order at the same positions, existing ids kept. The
spec compares it to upstream with a deterministic generateID (node type,
position and call order) over a rich document; 50k siblings run fast.
htmlToJson calls it at the existing seam (UPSTREAM_MODIFICATIONS #61).

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
… thread

Every HTML/Markdown write was converted on the engine's one event loop with
no bound: 1 MiB of plain block markup blocked it for 8-130 s or exhausted the
heap (happy-dom: ~0.1-0.3 ms and ~5-8 KB per element), marked took 7.6 s on
10 MiB (the importers), deep nesting was a 500. A byte/element cap cannot fix
it without rejecting real pages (ADR 0031).

editor-compat/content-parse: one persistent, warm worker thread runs the same
conversion (markdownToHtml -> htmlToJson), bounded by a 10 s deadline
(terminate() stops even a synchronous parse), a 1 GiB heap, a 1 MB stack (the
main thread's; the 4 MB default let deep nesting run past the deadline) and
100k nodes -> 422 content_too_complex. Admission: one conversion at a time and
at most one per principal (CLS actor) within 5 s -> 503 engine_busy. Fails
closed; never falls back to the event loop.

Wired: PageService.parseProsemirrorContent (every content write + the fork's
conditional/idempotent routes + validate-content), ImportService
processMarkdown/processHTML (and a passthrough of the refusals), the zip
import's Markdown. validate-content maps too-complex -> too_large and busy ->
parse_budget_exceeded (bridge enum unchanged). OpSemaphore.acquire takes an
optional per-call wait (one admission budget across both gates).

Seams: UPSTREAM_MODIFICATIONS docmost#121, docmost#147, new docmost#176; SEAM_ALLOWLIST updated.
content-parse.fitness.spec.ts reds on any direct htmlToJson/markdownToHtml/
generateJSON use outside the worker. Specs: fixture workers (hang, OOM,
crash, never-ready, throw-on-load, fairness), the real worker (parity with
in-process conversion, srcdoc bomb, node cap, depth, event-loop probe with an
in-process control).

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
… zip import, eager worker replacement

- Security (blocking): the node cap did not bound bytes. One long string repeated in many nodes (a Markdown
  reference definition, an <a href> around many blocks) turned ~200 KiB of input into a 286 MiB result and
  1–5 GB on the main thread, and a 300 KiB .md import crashed the process. The worker now counts every string
  in the result (and the HTML of markdown-to-html) against maxChars = 8 Mi → 422 content_too_complex; V8's
  "Invalid string length" maps to the same.
- Architecture/Performance: the zip import (one transaction, no retry) queued under the shared 'background'
  key with the interactive 5 s wait, so one busy answer failed the whole import. It now names its own queue,
  batchConversion(`file-task:<id>`), with a 60 s wait (processHTML takes the optional queue).
- A worker killed by a job is replaced at once instead of on the next request's clock.
- Testing: specs for recovery after a failed start and after an idle worker's death (mutation-checked), the
  eager replacement, the batch wait, and the character cap on the real worker (the three reported inputs).
- The fitness spec counts imports, re-exports, property access and destructuring, so an alias cannot hide a use.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@PMQ9
PMQ9 merged commit 8f14156 into wiki-v2 Sep 27, 2026
@PMQ9
PMQ9 deleted the fix/626-untrusted-parse-cost branch September 27, 2026 13:40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant