{"id":"CVE-2026-111059","kind":"vulnerability","aliases":["CVE-2026-111059","GHSA-2658-85cv-9wwq"],"related":[],"title":"Mercury: Stored / DOM Cross-Site Scripting (XSS): mr.Markdown renders untrusted content as raw, unsanitized HTML","description":"## Summary\n\nMercury turns Jupyter notebooks into shared web apps/dashboards. The `mr.Markdown`\nwidget converts its input to HTML with **python-markdown and no sanitization\nstep**. `MarkdownWidget` is an `ipywidgets.HTML` widget, whose value is written to\nthe page as **raw HTML (via `innerHTML`) with no sanitization**, so the result\nreaches the DOM verbatim. When an app passes **untrusted data** (database rows,\nuser submissions, uploaded file contents, or an external/LLM API response) to\n`mr.Markdown`, HTML/JS in that data executes in the browser of **whoever views the\napp** — a data-driven stored/DOM-based XSS.\n\nThis is a library-provided rendering sink that fails to neutralize output; it is\ntriggered by ordinary, reasonable application code, not by an author mistake.\n\n## Root cause\n\n`mercury/md.py` — `MarkdownWidget._to_html()` (verified at v3.2.6, lines ~57–65):\n\n```python\ndef _to_html(self, text: str) -> str:\n    if md_lib is not None:\n        body = md_lib.markdown(text)          # python-markdown: passes raw HTML through\n    else:\n        body = f\"<pre>{escape(text)}</pre>\"   # escape() is ONLY the md-lib-absent fallback\n    return self._apply_inline_theme(body)     # regex styling — adds style=, removes nothing\n```\n\nTwo neutralization failures compound:\n\n1. **Markdown → HTML is unsanitized.** `python-markdown` passes raw HTML through by\n   default: `<img src=x onerror=…>`, `<svg onload=…>`, and `javascript:` links\n   survive verbatim. There is no `bleach`/`nh3` allowlist anywhere in the package.\n   `_apply_inline_theme()` only injects inline `style=` attributes via regex; it is\n   not a sanitizer and removes nothing. `escape()` runs only in the\n   md-lib-absent fallback.\n\n2. **The rendering sink is unsanitized `innerHTML`.** `MarkdownWidget`\n   (`mercury/md.py:21`) subclasses `ipywidgets.HTML`. The ipywidgets HTML widget\n   renders its `value` into the DOM as raw HTML via `innerHTML`, with no\n   sanitization (this is the widget's design). Event-handler payloads such as\n   `<img src=x onerror=…>` therefore execute when the widget is displayed.\n\n**On the \"sanitize\" that exists:** `mercury_app/notebook_sanitize.py`\n(`sanitize_notebook_for_mercury_runtime`) and `packages/lab/src/mercury/save.ts`\n(`sanitizeMercuryNotebookContent`) strip *runtime metadata* and clear *code-cell\nsaved outputs*. They do **not** neutralize HTML/JS, and they do not touch widget\nvalues or markdown source. \"Sanitize\" here is notebook hygiene, not XSS defense.\n\n## Threat model (attacker → victim, not self-inflicted)\n\nThe CVE-relevant framing is **data-driven**: the app author writes ordinary code,\nand the *data* is attacker-controlled.\n\n```python\nimport mercury as mr\n# `row` comes from a DB / user submission / uploaded file / external API —\n# i.e. NOT authored by the app developer:\nmr.Markdown(row[\"comment\"])\n```\n\nThe attacker supplies the untrusted value (posts the comment, uploads the file,\npoisons the API/RAG source). A **different** user — another app user, a reviewer,\nan admin — then opens the app, and the payload executes in *their* browser. The\nvulnerable component (Mercury's server-side widget rendering) and the impacted\ncomponent (the victim's browser session in the app origin) differ, which is the\nclassic stored-XSS attacker/victim separation.\n\n**Amplifier — session sharing (`--keep-session`).** Mercury can serve one shared\nkernel session to all viewers (`mercury run … --keep-session`, README \"Arguments\":\n\"share the same session between multiple users … others will see this\"). It is\n**opt-in and defaults to off** (`keepSession=False` in `mercury_app/handlers.py`),\nso it is *not required* for the base case — any app that renders one user's\nuntrusted data to another user is already vulnerable. When enabled, content one\nviewer submits is rendered into the session other viewers see, extending this to\ncross-user delivery. Authentication is **opt-in and off by default**: a free\npassword gate exists (`mercury run … --pass=…`, README), while user-based\nauthentication is a paid add-on. Because auth is off unless the operator enables\nit, unauthenticated public deployments — where the attacker needs no account — are\na realistic default.\n\n## Proof of Concept\n\n```python\nimport mercury as mr\n\n# Value that would realistically arrive from untrusted data (DB row, form field,\n# uploaded file, API/LLM response):\nuntrusted = '<img src=x onerror=alert(String.fromCharCode(88,83,83))>'\n\nmr.Markdown(untrusted)   # rendered to raw HTML, unsanitized, into the app DOM\n```\n\nThe generated widget HTML contains the payload verbatim; when the widget is\ndisplayed, the `onerror` handler runs.\n\n### What was confirmed (and how)\n\n- **Confirmed by execution in a real browser (sink level):** driving the *actual\n  `python-markdown` output* into the same `ipywidgets.HTML` `value` sink the widget\n  uses causes the payload to execute in headless Chromium. Execution was captured\n  via Playwright's `dialog` event (which fires only on a genuine `alert()`, so the\n  mere presence of the string in the HTML cannot cause a false positive). A benign\n  control (`**hello**`) produced **zero** dialogs, confirming the harness reports\n  only real execution. `python-markdown` passes `<img src=x onerror=…>` through\n  verbatim by default (behavior is not version-specific).\n- **Reasoned from source (not executed end-to-end):** the full path from a\n  `mr.Markdown(...)` call in a *served Mercury app* to a viewer's DOM was not run\n  end-to-end, because no isolated container/VM was available in the reporting\n  environment. Because `MarkdownWidget` *is* the `ipywidgets.HTML` sink above and\n  Mercury's frontend applies no sanitizer to widget HTML values (the only frontend\n  sanitizer strips notebook metadata at save time), the served-app path is expected\n  to behave identically. Reproduce end-to-end before publishing if you want the\n  advisory to state full-path browser confirmation.\n\n## Impact\n\nMercury shares notebooks as web apps/dashboards, often for non-technical audiences.\nWhen an app renders untrusted data through `mr.Markdown`, the generated page carries\nattacker-controlled script that runs in the browser of any other viewer, in the\napp origin — enabling session/cookie/token theft, UI spoofing and forced actions as\nthe victim, and pivoting within the hosting origin. With `--keep-session`, this\nextends to cross-user delivery within a shared session.\n\n## Severity rationale (CVSS 3.1 per-metric)\n\nBase score reflects the realistic default: an unauthenticated deployment whose app\nrenders untrusted data via `mr.Markdown`.\n\n| Metric | Value | Reason |\n|---|---|---|\n| **AV** Attack Vector | **Network (N)** | App is served over HTTP to remote users. |\n| **AC** Attack Complexity | **Low (L)** | No special conditions or race; supply data that reaches an `mr.Markdown` call. |\n| **PR** Privileges Required | **None (N)** | Baseline: the injection channel (public form/upload/API) needs no account; auth is optional/paid. See variant below. |\n| **UI** User Interaction | **Required (R)** | A victim must open/view the app page for the stored payload to run. |\n| **S** Scope | **Changed (C)** | The vulnerable component (server-side widget render) injects script that executes in a different security authority — the victim's browser session/origin. (This is the canonical XSS scoping in the CVSS 3.1 spec.) |\n| **C** Confidentiality | **Low (L)** | Script can read data/session material available to the app origin; scored L (not H) for a generic app without asserting full account takeover. |\n| **I** Integrity | **Low (L)** | Script can alter the page and act as the victim within the app; scored L generically. |\n| **A** Availability | **None (N)** | No direct availability impact. |\n\nResult: **`CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N` = 6.1 (Medium)**.\n\nDeployment-dependent variants (state your environment's when filing):\n- Injection channel requires an authenticated low-privilege user → **PR:L** →\n  `…/PR:L/UI:R/S:C/C:L/I:L/A:N` = **5.4**.\n- App origin exposes high-value auth material such that XSS yields full\n  session/account takeover → **C:H/I:H** raises the score; justify per deployment\n  rather than claiming it universally.\n\n## Remediation\n\nPrimary — **sanitize by default in `mr.Markdown`, with an explicit opt-out for the\ndeliberate raw-HTML use case** (backward-compatible, non-breaking):\n\n```python\n# mercury/md.py\ndef _to_html(self, text: str, unsafe_allow_html: bool = False) -> str:\n    if md_lib is not None:\n        body = md_lib.markdown(text)\n    else:\n        body = f\"<pre>{escape(text)}</pre>\"\n    if not unsafe_allow_html:\n        # allowlist tags/attributes; strip javascript:/data: schemes and event handlers\n        body = nh3.clean(body)            # or bleach.clean(..., strip=True)\n    return self._apply_inline_theme(body)\n```\n\nExpose `unsafe_allow_html=False` on `mr.Markdown(...)` so authors who deliberately\nembed trusted raw HTML can opt in, while the default is safe. This mirrors the\nconvention used by comparable tools (e.g. Streamlit's `unsafe_allow_html`).\n\nDefense-in-depth: since widget HTML values are written via `innerHTML` without\nsanitization, consider sanitizing widget HTML values at the frontend before they\nreach the DOM, and/or serving a Content-Security-Policy that forbids inline event\nhandlers, so a single missed sink is not immediately exploitable.\n\n## Additional hardening (secondary — not the reported vulnerability)\n\nSeveral widget ESMs write the **label** with `innerHTML`, e.g. `mercury/text.py`\n`topLabel.innerHTML = model.get(\"label\") || …` (same shape in `number.py`,\n`time.py`, `date`/`datetime`/`daterange`/`select`/`json`/`file`, and\n`indicator.py`'s `_card_html`). **This is not an attacker→victim XSS path**: labels\nare static strings set by the app author in Python; URL/`url_params` overrides\naffect only widget `value` (assigned via the safe `input.value` property), never\n`label`, so there is no end-user/URL route into a label. It is a defense-in-depth /\nauthor footgun only. Recommended regardless: render UI strings with `textContent`,\nor `html.escape` labels, so output encoding is applied uniformly.","summary":"The mr.Markdown widget in the Mercury Python package converts text to HTML without sanitizing it, so raw HTML and JavaScript in the input reach the page. An attacker who can get untrusted data (a comment, upload, or API response) into a Mercury app can run script in the browser of anyone who views that app, enabling session or token theft and actions as the victim.","severity":"medium","cvss":6.1,"epss":0.002839999971911311,"exploited":false,"exploited_at":null,"products":[{"name":"mercury","fixed":["3.2.11"],"affected":">= 3.0.0, < 3.2.11","ecosystem":"pypi"}],"ecosystems":["pypi"],"tags":["cwe-116","cwe-79","mercury","notebook-apps","package","python","self-hosted"],"not_affected_if":["managed-hosting-with-unknown-patch-status","markdown-only-from-trusted-author-text","version-3.2.11-or-later"],"how_to_check":"Run pip show mercury and check whether the version is >= 3.0.0 and < 3.2.11.\nSearch app notebooks for mr.Markdown( calls whose argument comes from a database, form, upload, or API.","fix":"Upgrade the mercury package to 3.2.11 or later.\nUntil upgraded, do not pass untrusted data to mr.Markdown.","status":"open","published_at":"2026-10-19T17:01:20+00:00","first_seen_at":"2026-10-23T19:11:32+00:00","triaged_at":"2026-10-23T19:57:57+00:00","updated_at":"2026-10-23T21:57:18+00:00","category":"package","confidence":0.8,"triage":{"at":"2026-10-23T19:57:57Z","model":"claude-haiku-5-5","output":{"fix":"Upgrade the mercury package to 3.2.11 or later.\nUntil upgraded, do not pass untrusted data to mr.Markdown.","summary":"The mr.Markdown widget in the Mercury Python package converts text to HTML without sanitizing it, so raw HTML and JavaScript in the input reach the page. An attacker who can get untrusted data (a comment, upload, or API response) into a Mercury app can run script in the browser of anyone who views that app, enabling session or token theft and actions as the victim.","category":"package","who_cares":["python","mercury","self-hosted","notebook-apps"],"confidence":0.8,"analyst_note":"","how_to_check":"Run pip show mercury and check whether the version is >= 3.0.0 and < 3.2.11.\nSearch app notebooks for mr.Markdown( calls whose argument comes from a database, form, upload, or API.\nunknown for any other exposure check.","needs_analyst":false,"not_affected_if":["version-3.2.11-or-later","markdown-only-from-trusted-author-text","managed-hosting-with-unknown-patch-status"],"severity_if_unknown":"unknown"},"cost_usd":0.000788,"input_tokens":5868,"output_tokens":402,"severity_before":"medium"},"analyst_status":null,"analyst_note":null,"search":"'-111059':19A,28A '-116':31B '-2026':18A,27A '-2658':21A '-79':33B '-85':22A '1':286C '2':349C '21':358C '57':233C '65':234C '9wwq':25A 'absent':271C,347C 'action':104B 'add':278C 'admin':531C 'allowlist':316C 'alreadi':646C 'amplifi':576C 'anoth':525C,643C 'anyon':93B 'anywher':317C 'api':80B,176C,495C 'api/rag':520C 'app':37B,85B,97B,162C,192C,468C,501C,526C,535C,564C,634C 'app/handlers.py':623C 'app/notebook_sanitize.py':408C 'appli':321C 'applic':218C 'apps/dashboards':116C 'argument':598C 'attack':70B,452C,478C,507C 'attacker-control':477C 'attacker/victim':574C 'attribut':328C 'authent':669C 'author':223C,469C,498C 'ba':690C 'base':631C 'bleach':314C 'bodi':249C,260C,275C 'browser':91B,187C,542C,560C 'case':632C 'caus':226C 'cell':424C 'classic':570C 'clear':421C 'code':219C,423C,472C 'code-cel':422C 'come':486C 'comment':77B,505C,514C 'compon':545C,556C 'compound':285C 'content':12A,172C,650C 'control':479C 'convert':51B,120C 'cross':5A,666C 'cross-sit':4A 'cross-us':665C 'cv':24A 'cv-9wwq':23A 'cve':17A,26A,460C 'cve-relev':459C 'cwe':30B,32B 'data':75B,165C,183C,195C,465C,475C,641C 'data-driven':194C,464C 'databas':166C 'db':489C 'def':236C 'default':299C,616C,677C 'defens':449C 'deliveri':668C 'design':384C 'develop':502C 'differ':523C,566C 'display':401C 'dom':3A,158C,370C 'driven':196C,466C 'els':259C 'enabl':98B,649C 'escap':262C,264C,339C 'event':386C 'event-handl':385C 'execut':184C,396C,539C 'exist':406C,682C 'extend':662C 'extern':494C 'external/llm':175C 'f':261C 'fail':208C 'failur':284C 'fallback':272C,348C 'fals':620C 'file':171C,493C,517C 'frame':462C 'free':679C 'gate':681C 'get':73B 'ghsa':20A 'handler':387C 'host':42B 'html':16A,54B,60B,124C,147C,238C,257C,288C,296C,363C,373C 'html/js':180C,431C 'hygien':446C 'i.e':496C 'img':300C,391C 'impact':555C 'import':481C 'inflict':457C 'inject':325C 'inlin':322C,326C 'innerhtml':149C,355C,375C 'input':65B,122C 'ipywidget':362C 'ipywidgets.html':136C,360C 'javascript':62B,307C 'jupyt':111C 'keep':580C,595C 'keep-sess':579C,594C 'keepsess':619C 'kernel':587C 'lib':245C,270C,346C 'librari':203C 'library-provid':202C 'line':232C 'link':308C 'markdown':128C,254C,287C,293C,440C 'markdownwidget':133C,356C 'markdownwidget._to_html':228C 'md':244C,269C,345C 'md-lib-abs':268C,344C 'md_lib.markdown':250C 'mercuri':1A,34B,48B,84B,109C,407C,412C,482C,546C,582C,592C,622C,683C 'mercury':29A 'mercury/md.py':227C,357C 'metadata':419C 'mistak':224C 'model':451C 'mr':484C 'mr.markdown':9A,44B,118C,179C,503C 'multipl':604C 'neutral':210C,283C,430C 'nh3':315C 'none':248C 'notebook':36B,112C,410C,445C 'notebook-app':35B 'noth':281C,338C 'one':585C,637C,651C 'onerror':303C,394C 'onload':305C 'open':533C 'opt':613C,672C 'opt-in':612C,671C 'ordinari':216C,471C 'origin':565C 'other':606C 'output':211C,426C 'packag':38B,50B,320C 'packages/lab/src/mercury/save.ts':415C 'page':68B,144C 'pass':163C,255C,294C,685C 'password':680C 'payload':388C,538C 'poison':518C 'post':512C 'provid':204C 'python':39B,49B,127C,235C,253C,292C,480C 'python-markdown':126C,252C,291C 'raw':14A,59B,146C,256C,295C,372C 'reach':66B,156C 'readm':597C,686C 'reason':217C 'regex':276C,330C 'relev':461C 'remov':280C,337C 'render':10A,205C,351C,365C,552C,636C,655C 'requir':628C 'respons':81B,177C 'result':155C 'return':273C 'review':529C 'root':225C 'row':167C,485C,504C 'run':87B,340C,593C,684C 'runtim':413C,418C 'sanit':56B,131C,152C,335C,378C,404C,409C,442C 'sanitizemercurynotebookcont':416C 'save':425C 'script':7A,88B 'see':608C,661C 'self':41B,239C,456C 'self-host':40B 'self-inflict':455C 'self._apply_inline_theme':274C 'separ':575C 'serv':584C 'server':549C 'server-sid':548C 'session':99B,561C,577C,581C,588C,596C,602C,658C 'share':114C,578C,586C,599C 'side':550C 'sink':206C,352C 'site':6A 'sourc':441C,521C 'src':301C,392C 'step':132C 'store':2A,572C 'stored-xss':571C 'stored/dom-based':197C 'str':241C,242C 'strip':417C 'style':277C,279C,327C 'subclass':359C 'submiss':169C,491C 'submit':653C 'summari':108C 'suppli':508C 'surviv':309C 'svg':304C 'text':52B,240C,251C,263C 'theft':102B 'theme':323C 'therefor':395C 'threat':450C 'token':101B 'touch':436C 'trigger':214C 'turn':110C 'two':282C 'unsanit':15A,290C,354C 'untrust':11A,74B,164C,510C,640C 'upload':78B,170C,492C,515C 'user':168C,490C,524C,527C,605C,638C,644C,667C,689C 'user-ba':688C 'v3.2.6':231C 'valu':139C,367C,438C,511C 'verbatim':159C,310C 'verifi':229C 'via':148C,329C,374C 'victim':107B,453C,558C 'view':95B,190C 'viewer':591C,652C,660C 'vulner':544C,647C 'web':115C 'whoever':189C 'whose':138C 'widget':45B,119C,137C,364C,382C,399C,437C,551C 'without':55B 'write':470C 'written':141C 'x':302C,393C 'xss':8A,198C,448C,573C","nicknames":[],"mitigations":[],"who_affected":null,"tier":"C","verified":{},"analyst_revisit_at":null,"first_public_at":"2026-10-19T17:01:20+00:00","kev":null,"cvss_vector":"CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N","cvss_by":"GitHub","poc_count":0,"sources":[{"source":"ghsa","external_id":"GHSA-2658-85cv-9wwq","url":"https://github.com/advisories/GHSA-2658-85cv-9wwq","severity":"medium","published_at":"2026-10-19T17:01:20+00:00","modified_at":"2026-10-19T17:01:22+00:00","first_seen_at":"2026-10-23T19:11:32+00:00","fetched_at":"2026-10-23T19:11:32+00:00","note":null},{"source":"nvd","external_id":"CVE-2026-111059","url":"https://nvd.nist.gov/vuln/detail/CVE-2026-111059","severity":null,"published_at":"2026-10-19T17:17:02+00:00","modified_at":"2026-10-20T17:17:29+00:00","first_seen_at":"2026-10-23T21:57:18+00:00","fetched_at":"2026-10-23T22:28:57+00:00","note":null}],"documents":[],"notice":"Free to read at a human pace. An API with keys and an MCP server are in preparation; early access: hello@infrastack.ai"}