~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.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
fix(export): PDF and ODT exports escape raw markup in report text, as the web view does (#7861)
LearningCircuit03b882f41eee
diff --git a/SECURITY.md b/SECURITY.mdindex 3e9c80f0e3..a65700ed7e 100644--- a/SECURITY.md+++ b/SECURITY.md@@ -149,7 +149,7 @@ By setting this, the operator acknowledges the residual risk above. To minimiseThe general HTTP fetch path (`safe_requests`, used for RAG sources and web scraping) resolves the hostname and connects to that **same** validated address: `security.dns_pinning` pins the resolved IP for the outbound connection (re-resolving and re-validating at connect time, and re-pinning at every redirect hop) so `requests`/`urllib3` cannot connect to a different address than the one the guard checked. The request keeps the original hostname, so TLS SNI and certificate verification are unchanged — only name resolution is pinned. The notification path above reuses this same shim (via `pinned_notification_send`, plus the block-private window for unpinned plugin-endpoint hosts) — but with redirect-following disabled outright rather than validated hop-by-hop, since a notification webhook has no legitimate need to follow redirects. It still does not apply to callers that hand a URL to an external client that re-resolves on its own with no in-thread `getaddrinfo` interception (LLM SDKs — see "LLM Provider URL Validation"); for those, egress restriction remains the primary defense. It also does not apply when `requests` is configured to use a forward proxy (`HTTP(S)_PROXY` / `trust_env`): `urllib3` then resolves the *proxy* host rather than the target, so target-IP selection is delegated to the proxy and the pin is a safe no-op (the pre-connection `validate_url` check still runs).-The PDF export resource fetcher (`_SafeUrlFetcher` in `web/services/pdf_service.py`) fetches the images, stylesheets and fonts a report references through WeasyPrint's urllib-based `URLFetcher`, with redirects disabled. Each fetch runs inside `dns_pinning.pinned_request` nested with `dns_pinning.block_private_resolution`, both with the policy its `validate_url` call applies (public addresses only; cloud-metadata always blocked). The connection therefore goes only to an address that passed the same policy at connect time. For an ASCII host name it is pinned to the validated address. An IP-literal host is not pinned, because there is no DNS to rebind; its lookup goes through the block window like any other unpinned lookup, such as a non-ASCII host that urllib looks up in a different form from the pin key. Each such lookup is checked against that policy on the answer actually used. urllib connects on the rendering thread, which is the thread the pin and window apply to, and keeps the hostname for TLS SNI and certificate verification. The fetch is refused if the `getaddrinfo` shim is not the active resolver, and resource URLs that carry userinfo (any `@` in the authority) are refused outright, because urllib would look up the whole `user@host` authority rather than the pinned host. If `HTTP(S)_PROXY` is set, urllib connects to the proxy and the proxy resolves the target, so the forward-proxy caveat above applies to the target. The proxy's own lookup is exempted from the public-only policy by exact host and port (taken from the fetcher's proxy configuration, via `dns_pinning.allow_resolution`), so a proxy on a private or loopback address keeps working; cloud-metadata and other link-local addresses are still refused for it, and every other lookup during the fetch keeps the public-only policy. Two proxy setups are not mirrored and fail closed, meaning a private proxy is refused rather than let through: a plain-http resource whose `HTTP_PROXY` has an `https://` scheme while `HTTPS_PROXY` is also set, where urllib tunnels through the `HTTPS_PROXY` host; and a Python without urllib's private `_parse_proxy` helper.+The PDF export resource fetcher (`_SafeUrlFetcher` in `web/services/pdf_service.py`) fetches every resource the render loads (the images a report's Markdown references, and any stylesheet, font or image those or a caller-supplied stylesheet reference in turn) through WeasyPrint's urllib-based `URLFetcher`, with redirects disabled. Raw HTML in report text is escaped before rendering, as in the on-screen report view, so report text itself references resources only through Markdown image syntax. Each fetch runs inside `dns_pinning.pinned_request` nested with `dns_pinning.block_private_resolution`, both with the policy its `validate_url` call applies (public addresses only; cloud-metadata always blocked). The connection therefore goes only to an address that passed the same policy at connect time. For an ASCII host name it is pinned to the validated address. An IP-literal host is not pinned, because there is no DNS to rebind; its lookup goes through the block window like any other unpinned lookup, such as a non-ASCII host that urllib looks up in a different form from the pin key. Each such lookup is checked against that policy on the answer actually used. urllib connects on the rendering thread, which is the thread the pin and window apply to, and keeps the hostname for TLS SNI and certificate verification. The fetch is refused if the `getaddrinfo` shim is not the active resolver, and resource URLs that carry userinfo (any `@` in the authority) are refused outright, because urllib would look up the whole `user@host` authority rather than the pinned host. If `HTTP(S)_PROXY` is set, urllib connects to the proxy and the proxy resolves the target, so the forward-proxy caveat above applies to the target. The proxy's own lookup is exempted from the public-only policy by exact host and port (taken from the fetcher's proxy configuration, via `dns_pinning.allow_resolution`), so a proxy on a private or loopback address keeps working; cloud-metadata and other link-local addresses are still refused for it, and every other lookup during the fetch keeps the public-only policy. Two proxy setups are not mirrored and fail closed, meaning a private proxy is refused rather than let through: a plain-http resource whose `HTTP_PROXY` has an `https://` scheme while `HTTPS_PROXY` is also set, where urllib tunnels through the `HTTPS_PROXY` host; and a Python without urllib's private `_parse_proxy` helper.### JS-Rendering Browser Redirect SSRFdiff --git a/changelog.d/+7821-odt-yaml-metadata-block.bugfix.md b/changelog.d/+7821-odt-yaml-metadata-block.bugfix.mdnew file mode 100644index 0000000000..616608df3e--- /dev/null+++ b/changelog.d/+7821-odt-yaml-metadata-block.bugfix.md@@ -0,0 +1 @@+ODT export no longer fails with "Error parsing YAML metadata" when a report contains a horizontal rule (`---`) directly followed by text, such as a `## Sources` heading. Pandoc no longer reads report text as a YAML metadata block, so such text also no longer sets document properties or disappears from the document. The document title is still set from the export's title. Fixes #7821.diff --git a/changelog.d/+export-escape-raw-markup.security.md b/changelog.d/+export-escape-raw-markup.security.mdnew file mode 100644index 0000000000..be90f784df--- /dev/null+++ b/changelog.d/+export-escape-raw-markup.security.md@@ -0,0 +1 @@+Server-side PDF export (Download PDF) and ODT export now escape raw markup in report text, consistent with the on-screen report view. In the PDF, raw HTML in the synthesized answer and in source titles is rendered as visible text rather than passed through to the renderer. In the ODT, Pandoc's raw-content syntax (raw OpenDocument, HTML and TeX) and `<div>` and `<span>` tags are read as ordinary text, so raw HTML or TeX in a report now appears as written instead of being dropped, and a `<div>` or `<span>` no longer sets styles or sections in the document. `<br>`, `<sup>`/`<sub>` and HTML comments written in report text now appear as text in both exports, as they do in the on-screen view. Ordinary Markdown (headings, lists, tables, code, footnotes, links, images and math) converts as before.diff --git a/changelog.d/6466.bugfix.md b/changelog.d/6466.bugfix.mdindex cb6aba4e4a..ad75db9675 100644--- a/changelog.d/6466.bugfix.md+++ b/changelog.d/6466.bugfix.md@@ -1 +1 @@-A report whose content carries a `@color-profile` at-rule pointing at a resource the SSRF guard refuses no longer fails PDF export with a generic 500. WeasyPrint skips a refused `@import` and completes the render, but lets the error from a refused `@color-profile` escape, so the export route answered 500 for a report that is otherwise fine. Report content is LLM- and web-derived, and raw HTML passes through the markdown step, so the at-rule is reachable. The render now retries once with unavailable resources skipped rather than raised, which restores for every at-rule the behaviour the others already had. The SSRF guard is unchanged: the retry still refuses the same URLs and still makes no request for one it refuses.+PDF export no longer fails with a generic 500 when a stylesheet in the rendered document carries a `@color-profile` at-rule pointing at a resource the SSRF guard refuses. WeasyPrint skips a refused `@import` and completes the render, but lets the error from a refused `@color-profile` escape, so the export route answered 500 for a report that was otherwise fine. The render now retries once with unavailable resources skipped rather than raised, which restores for every at-rule the behaviour the others already had. The SSRF guard is unchanged: the retry still refuses the same URLs and still makes no request for one it refuses.diff --git a/src/local_deep_research/exporters/odt_exporter.py b/src/local_deep_research/exporters/odt_exporter.pyindex ca1b5e0a2e..bb16eb138e 100644--- a/src/local_deep_research/exporters/odt_exporter.py+++ b/src/local_deep_research/exporters/odt_exporter.py@@ -53,6 +53,29 @@ class ODTExporter(BaseExporter):#: The bundled pandoc accepts GHC RTS heap limits. Other builds that#: reject RTS flags fail the conversion rather than running uncapped.DEFAULT_MAX_HEAP_MB = 1024+ #: Pandoc's markdown reader with raw passthrough switched off. Report+ #: text is LLM- and web-derived. With these extensions on (pandoc's+ #: default), a ``{=opendocument}`` raw block or inline is copied into+ #: the document as-is, while raw HTML and TeX are silently dropped from+ #: the ODT. ``<div>`` and ``<span>`` tags are read as document+ #: structure even with raw HTML off: a ``custom-style`` attribute+ #: becomes an ODT style name, a div's ``id`` a section, and a ``<div>``+ #: whose closing tag is on the same line stays open to the end of the+ #: document. A ``---`` line directly followed by text opens a YAML+ #: metadata block, which moves report text into document properties,+ #: or fails the export when that text is not YAML (#7821). With all of+ #: these off, report text reaches the document as text, consistent+ #: with the PDF export and the on-screen report view, which escape raw+ #: HTML. Ordinary markdown converts identically, and the title, author+ #: and date still come from the ``--metadata`` arguments. Pandoc+ #: rejects an extension name it does not know, so a future rename fails+ #: the export instead of quietly restoring passthrough; every name here+ #: exists in every pandoc that supports ``--sandbox`` (2.15+), which+ #: export requires.+ READER_FORMAT = (+ "markdown-raw_attribute-raw_html-raw_tex"+ "-native_divs-native_spans-yaml_metadata_block"+ )def __init__(self,@@ -189,7 +212,7 @@ class ODTExporter(BaseExporter):"-RTS","--sandbox",]- cmd.extend(["-f", "markdown", "-t", "odt", "-o", "-"])+ cmd.extend(["-f", self.READER_FORMAT, "-t", "odt", "-o", "-"])cmd.extend(extra_args)try:diff --git a/src/local_deep_research/web/services/pdf_service.py b/src/local_deep_research/web/services/pdf_service.pyindex 2812746c7f..df89f159e5 100644--- a/src/local_deep_research/web/services/pdf_service.py+++ b/src/local_deep_research/web/services/pdf_service.py@@ -167,8 +167,9 @@ _EMPTY_RESOURCE_MIME_TYPE = "application/octet-stream"# rest are counted. Every skipped URL also gets its own warning._SKIPPED_SUMMARY_LIMIT = 20-# Size limits for what WeasyPrint fetches while rendering an export: images,-# stylesheets, fonts and anything else a report references by URL. Applied by+# Size limits for what WeasyPrint fetches while rendering an export: the images+# report markdown references, and any stylesheet, font or image that those+# resources or a caller-supplied stylesheet reference in turn. Applied by# `_BoundedBodyProcessor` to what reading each body costs (`_FetchCost`): its# body bytes, its decoded bytes if it is gzip or deflate, and the work of# decoding it. A compressed body is therefore bounded by what it decodes to,@@ -1568,9 +1569,15 @@ class PDFService:`@color-profile` it cannot fetch is not, because the `fetch()` call in`weasyprint/css/__init__.py` sits outside the `try`, so the`URLFetchingError` escapes `CSS.__init__`, escapes this method, and the- export route answers a generic 500 (#6466). Report content is LLM- and- web-derived, so a `<style>` block carrying that at-rule is reachable and- python-markdown passes raw HTML straight through.+ export route answers a generic 500 (#6466).++ Report text does not reach the renderer as markup:+ `_markdown_to_html` escapes raw HTML, so a `<style>` element cannot+ come from report content, and the export route passes+ `custom_css=None` (a caller-supplied stylesheet is parsed in+ `markdown_to_pdf`, which drops it on the same failure). The retry is+ kept as defence in depth, for any stylesheet that does reach the+ document handed to this method.The retry restores the behaviour the other at-rules already have,rather than renaming the failure. Nothing about the SSRF guard moves:@@ -1647,6 +1654,9 @@ class PDFService:- Fenced code blocks- Table of contents- Footnotes++ Raw HTML in the report text is escaped rather than passed through, so+ it reaches the PDF as visible text, as in the on-screen report view."""# Parse markdown with extensionsmd = markdown.Markdown(@@ -1661,6 +1671,26 @@ class PDFService:])+ # Escape raw HTML in the report body, matching the on-screen report+ # view (``ui.renderMarkdown``, #7365). Report text is LLM- and+ # web-derived (the synthesized answer, and source titles the Sources+ # block interpolates as plain text), and Python-Markdown passes raw+ # HTML straight through by default. Deregistering its raw-HTML+ # handlers makes any tags in the body come out as escaped text+ # instead, so report content cannot add stylesheets, attachments,+ # metadata or other markup to the exported PDF. Ordinary markdown --+ # including the ```` images and ``[](url)`` links Markdown+ # itself generates -- is unaffected, and so is the pipeline's own+ # HTML (the ``<title>``, ``<meta>`` and footer assembled after+ # conversion below).+ #+ # ``strict=True`` (the default): if a future Markdown release renames+ # these handlers the export fails loudly here, rather than silently+ # reopening raw-HTML passthrough. Both names are stable across+ # Markdown 3.x.+ md.preprocessors.deregister("html_block")+ md.inlinePatterns.deregister("html")+html_body = md.convert(markdown_content)# Build complete HTML documentdiff --git a/tests/exporters/test_odt_exporter.py b/tests/exporters/test_odt_exporter.pyindex 12c9d1901d..765d7aaba3 100644--- a/tests/exporters/test_odt_exporter.py+++ b/tests/exporters/test_odt_exporter.py@@ -1,5 +1,7 @@"""Tests for ODTExporter using pypandoc."""+import re+import pytestfrom unittest.mock import patch@@ -530,3 +532,277 @@ class TestODTExporterFooter:# Verify footer text is present in the contentassert "Local Deep Research" in content_xmlassert "Open Source AI Research Assistant" in content_xml+++def _odt_members(odt_bytes: bytes) -> dict:+ """The ODT's archive members, by name."""+ import io+ import zipfile++ with zipfile.ZipFile(io.BytesIO(odt_bytes), "r") as zf:+ return {name: zf.read(name) for name in zf.namelist()}+++def _undated(meta_xml: bytes) -> bytes:+ """meta.xml without its creation and modification dates."""+ return re.sub(rb"<(meta:creation-date|dc:date)>[^<]*</\1>", b"", meta_xml)+++class TestODTExporterRawPassthroughIsOff:+ """Raw-content syntax in report text reaches the ODT as text.++ By default pandoc's markdown reader copies a ``{=opendocument}`` raw+ block or inline into content.xml as-is, drops raw HTML and TeX, and+ reads ``<div>`` and ``<span>`` tags as document structure. The+ exporter reads report text with all of these switched off+ (``ODTExporter.READER_FORMAT``), so it arrives as ordinary, escaped+ text, consistent with the PDF export. The probe is a benign style+ name: as markup it would appear as a ``text:style-name`` attribute,+ as text only in escaped form.+ """++ MARKER = "RawProbeMarker"++ ORDINARY = (+ "# Research Report\n\n"+ "## Summary\n\n"+ "Paragraph with **bold**, *italic*, `inline code` and a\n"+ "[link](https://example.org/page) plus <https://example.org>.\n\n"+ "- item one\n"+ "- item two\n"+ " 1. nested\n"+ " 2. nested two\n\n"+ "> A quoted line.\n\n"+ "| Column A | Column B |\n"+ "|----------|----------|\n"+ "| 1 | two |\n\n"+ "```python\n"+ "def f(x):\n"+ " return 1 < x < 5\n"+ "```\n\n"+ "Inline math $E = mc^2$ and display math:\n\n"+ "$$\n\\int_0^1 x^2 \\, dx = \\frac{1}{3}\n$$\n\n"+ "A claim with a footnote.[^1] Also 3 < 5 and a & b.\n\n"+ "\n\n"+ "[^1]: The footnote text.\n\n"+ "## Sources\n\n"+ "[1] Example Source Title (source nr: 1)\n"+ " URL: https://example.org/source\n"+ )++ @pytest.fixture+ def exporter(self):+ from local_deep_research.exporters.odt_exporter import ODTExporter++ return ODTExporter()++ @pytest.mark.parametrize(+ "markdown",+ [+ "# Report\n\nBefore.\n\n"+ "```{=opendocument}\n"+ '<text:p text:style-name="RawProbeMarker">probe</text:p>\n'+ "```\n\nAfter.\n",+ "# Report\n\nText "+ '`<text:span text:style-name="RawProbeMarker">probe</text:span>`'+ "{=opendocument} end.\n",+ ],+ ids=["block", "inline"],+ )+ def test_raw_opendocument_is_text_not_markup(self, exporter, markdown):+ content = _odt_members(exporter.export(markdown).content)[+ "content.xml"+ ].decode("utf-8")++ # Never markup ...+ assert f'text:style-name="{self.MARKER}"' not in content+ # ... but present, as escaped text.+ assert f"text:style-name="{self.MARKER}"" in content++ def test_raw_html_and_tex_are_text_not_dropped(self, exporter):+ content = _odt_members(+ exporter.export(+ "# Report\n\nText <b>html-probe</b> and \\textbf{tex-probe}.\n"+ ).content+ )["content.xml"].decode("utf-8")++ # Shown as written, rather than dropped as raw HTML and raw TeX.+ assert "<b>html-probe</b>" in content+ assert "\\textbf{tex-probe}" in content++ @pytest.mark.parametrize(+ ("tag", "markdown"),+ [+ (+ "span",+ "# Report\n\nText "+ '<span custom-style="RawProbeMarker">probe</span> end.\n',+ ),+ (+ "div",+ '# Report\n\n<div custom-style="RawProbeMarker">\n\n'+ "Inside.\n\n</div>\n\nAfter.\n",+ ),+ ],+ ids=["span", "div"],+ )+ def test_div_and_span_tags_are_text_not_markup(+ self, exporter, tag, markdown+ ):+ """With pandoc's ``native_spans`` and ``native_divs`` on, these tags+ are read as a Span or Div even with raw HTML off, and their+ ``custom-style`` attribute becomes the ODT style name."""+ content = _odt_members(exporter.export(markdown).content)[+ "content.xml"+ ].decode("utf-8")++ # Never markup ...+ assert f'text:style-name="{self.MARKER}"' not in content+ # ... but present, as escaped text. The quotes around the attribute+ # value are left out: pandoc's smart typography curls them.+ assert f"<{tag} custom-style=" in content+ assert self.MARKER in content+ assert f"</{tag}>" in content++ @pytest.mark.parametrize(+ "div",+ [+ '<div class="probe">One line</div>',+ '<div id="probe">One line</div>',+ ],+ ids=["class", "id"],+ )+ def test_one_line_div_leaves_the_rest_of_the_report_alone(+ self, exporter, div+ ):+ """With ``native_divs`` on, a ``<div>`` whose closing tag is on the+ same line stays open to the end of the document: the closing tag+ shows as text, and with an ``id`` the rest of the report, footer+ included, is wrapped in a ``text:section``. Read as text, the line+ is one paragraph and the paragraphs after it are exactly those of+ the same report with a plain line in its place."""++ def report(line):+ return (+ "# Report\n\nIntro.\n\n"+ f"{line}\n\n"+ "Later paragraph.\n\n## Later heading\n\nMore.\n"+ )++ def after_the_line(content):+ return content[+ content.index("</text:p>", content.index("One line")) :+ ]++ content = _odt_members(exporter.export(report(div)).content)[+ "content.xml"+ ].decode("utf-8")+ plain = _odt_members(exporter.export(report("One line")).content)[+ "content.xml"+ ].decode("utf-8")++ assert "<text:section" not in content+ # The whole tag line is one paragraph of text.+ assert re.search(+ r"<text:p [^>]*><div [^<]*>One line</div></text:p>",+ content,+ ), content+ # Everything after it, up to the end of the document, is unchanged.+ assert after_the_line(content) == after_the_line(plain)+ assert "Later paragraph." in after_the_line(content)++ def test_ordinary_markdown_converts_as_with_the_default_reader(+ self, exporter+ ):+ """Switching these extensions off changes nothing else: for+ ordinary markdown the ODT matches, member for member, the one+ pandoc's default markdown reader produces through the same+ exporter."""+ from local_deep_research.exporters.base import ExportOptions+ from local_deep_research.exporters.odt_exporter import ODTExporter++ options = ExportOptions(title="Report")+ hardened = _odt_members(exporter.export(self.ORDINARY, options).content)+ with patch.object(ODTExporter, "READER_FORMAT", "markdown"):+ default = _odt_members(+ exporter.export(self.ORDINARY, options).content+ )++ assert hardened.keys() == default.keys()+ for name in hardened:+ # meta.xml holds the title from the --metadata argument, the+ # generator and the creation dates. The dates are removed+ # before comparing, so a pandoc that stamps the current time+ # cannot make this flaky.+ if name == "meta.xml":+ assert _undated(hardened[name]) == _undated(default[name])+ else:+ assert hardened[name] == default[name], name+ assert b"<dc:title>Report</dc:title>" in hardened["meta.xml"]+ # Arrival: the markdown features are really in the document.+ content = hardened["content.xml"].decode("utf-8")+ assert "<table:table " in content+ assert "<text:list" in content+ assert "<text:note " in content+ assert 'xlink:href="https://example.org/page"' in content+ assert "Example Source Title" in content+ assert any(name.startswith("Formula-") for name in hardened)+++class TestODTExporterBodyMetadataIsText:+ """A ``---`` block in report text is text, not document metadata.++ By default pandoc's markdown reader treats a ``---`` line directly+ followed by text as the start of a YAML metadata block, closed by the+ next ``---`` line, which can be the footer's rule. A block that parses+ as YAML sets document properties and is removed from the body; one+ that does not fails the export (#7821). The exporter reads report text+ with ``yaml_metadata_block`` off, so neither happens, while the title,+ author and date still come from the ``--metadata`` arguments.+ """++ @pytest.fixture+ def exporter(self):+ from local_deep_research.exporters.odt_exporter import ODTExporter++ return ODTExporter()++ def test_body_yaml_block_is_text_not_document_metadata(self, exporter):+ from local_deep_research.exporters.base import ExportOptions++ members = _odt_members(+ exporter.export(+ "# Report\n\nIntro.\n\n---\nauthor: MarkerAuthor\n---\n\n"+ "After.\n",+ ExportOptions(title="Report", metadata={"date": "2026-01-02"}),+ ).content+ )+ meta = members["meta.xml"].decode("utf-8")+ content = members["content.xml"].decode("utf-8")++ # Not document metadata ...+ assert "MarkerAuthor" not in meta+ # ... but text, with the text around it kept. (As metadata the+ # author also appears in content.xml, in the title block, but+ # without the "author:" key.)+ assert "author: MarkerAuthor" in content+ assert "Intro." in content+ assert "After." in content+ # The arguments still set the document metadata.+ assert "<dc:title>Report</dc:title>" in meta+ assert "2026-01-02" in meta++ def test_rule_directly_followed_by_a_heading_exports(self, exporter):+ """The #7821 shape: a rule directly followed by a heading. Read as+ the start of a YAML block that the footer's rule closes, it made+ pandoc exit with "Error parsing YAML metadata"."""+ content = _odt_members(+ exporter.export(+ "Intro text.\n\n---\n## Sources\n\n[1] Example source\n"+ ).content+ )["content.xml"].decode("utf-8")++ assert "Intro text." in content+ assert "Sources" in content+ assert "[1] Example source" in content+ assert "Open Source AI Research Assistant" in contentdiff --git a/tests/security/test_identity_paths_and_host_effects.py b/tests/security/test_identity_paths_and_host_effects.pyindex b4f44c1204..eede664916 100644--- a/tests/security/test_identity_paths_and_host_effects.py+++ b/tests/security/test_identity_paths_and_host_effects.py@@ -153,7 +153,8 @@ def test_odt_metadata_cannot_add_pandoc_arguments("-RTS","--sandbox","-f",- "markdown",+ "markdown-raw_attribute-raw_html-raw_tex"+ "-native_divs-native_spans-yaml_metadata_block","-t","odt","-o",diff --git a/tests/security/test_pdf_render_parser_posture.py b/tests/security/test_pdf_render_parser_posture.pyindex da6190d499..4b6bedafc8 100644--- a/tests/security/test_pdf_render_parser_posture.py+++ b/tests/security/test_pdf_render_parser_posture.py@@ -9,12 +9,18 @@ architecture, and nothing in the test tree pins them:``MAX_IMAGE_PIXELS``. The classic operational "fix" for a user'soversized-image complaint — ``Image.MAX_IMAGE_PIXELS = None`` — wouldsilently reopen decode bombs; no test would notice.-2. **Inline XML DTDs in report bodies are inert.** Python-Markdown- passes raw HTML blocks through, so a report body can carry an SVG- with a DOCTYPE and entity declarations. The HTML5 parsing pipeline- never processes XML DTDs, so entities neither expand (billion- laughs) nor resolve (local-file read). A pipeline swap to an- XML-based renderer would resurrect both classes silently.+2. **Inline XML DTDs in report bodies are inert.** A report body can+ carry an SVG with a DOCTYPE and entity declarations. Two layers keep+ them inert, and each is pinned by its own test. The markdown-to-HTML+ step escapes raw HTML in report text, so such a block is handed to+ the renderer as text, not markup. Beneath that, the HTML5 parsing+ pipeline does not process XML DTDs, so a block that does reach it as+ markup neither expands its entities nor resolves an external one;+ that test injects the block at the HTML layer, past the escaping, so+ it exercises the parser whatever the markdown step does. Removing the+ escaping fails ``test_the_hostile_block_is_escaped_not_passed_through``;+ a swap to an XML-based renderer that honoured the DTD would fail+ ``test_dtd_entities_neither_expand_nor_read_files``.These contracts pin today's posture so either regression goes red."""@@ -26,6 +32,7 @@ import reimport structimport zlibfrom pathlib import Path+from unittest.mock import patchimport pytest@@ -106,13 +113,27 @@ Normal report body text with the ARRIVAL-CONTROL marker."""def test_dtd_entities_neither_expand_nor_read_files(self, tmp_path):+ """The parser layer on its own. Report markdown escapes this block,+ so it is injected at the HTML layer instead (by stubbing+ ``_markdown_to_html``) and reaches WeasyPrint's HTML5 parser as+ markup, independent of the markdown step."""sentinel = tmp_path / "sentinel.txt"sentinel.write_text("SENTINEL-FILE-CONTENT-9QW", encoding="utf-8")- markdown = self.HOSTILE_BODY.format(sentinel_path=sentinel)- pdf_bytes = pdf_service.get_pdf_service().markdown_to_pdf(- markdown, title="Posture probe"+ # The block placed in the body verbatim, as markup.+ html_doc = (+ "<!DOCTYPE html><html><head><meta charset='utf-8'></head><body>"+ + self.HOSTILE_BODY.format(sentinel_path=sentinel)+ + "</body></html>")+ with patch.object(+ pdf_service.PDFService,+ "_markdown_to_html",+ lambda self, content, title=None, metadata=None: html_doc,+ ):+ pdf_bytes = pdf_service.get_pdf_service().markdown_to_pdf(+ "# Posture probe\n", title="Posture probe"+ )assert pdf_bytes, "render must complete on a DTD-bearing body"@@ -120,6 +141,9 @@ Normal report body text with the ARRIVAL-CONTROL marker.# Arrival control: the benign marker made it into the render,# so the absence assertions below are not vacuous.assert "ARRIVAL-CONTROL" in text, text[:400]+ # And the declarations reached the parser as markup: as escaped text+ # they would render, "<!ENTITY" lines and all.+ assert "ENTITY" not in text, text[:400]# No billion-laughs expansion (declaration text contains# "&leaf;", never the literal "Z0Z0Z0").assert "Z0Z0Z0" not in text, "internal entity expanded in render"@@ -128,15 +152,21 @@ Normal report body text with the ARRIVAL-CONTROL marker."external entity resolved during render")- def test_the_hostile_block_actually_reaches_the_renderer(self, tmp_path):- """Guard against the payload being dropped before render: the- markdown-to-HTML conversion passes the SVG block through."""+ def test_the_hostile_block_is_escaped_not_passed_through(self, tmp_path):+ """The escaping layer on its own: the markdown-to-HTML step escapes+ the raw SVG/DTD block, so it is handed to the renderer as text rather+ than markup. The benign text after the block is checked too, so the+ conversion is known to have produced the body."""sentinel = tmp_path / "sentinel.txt"sentinel.write_text("x", encoding="utf-8")html = pdf_service.get_pdf_service()._markdown_to_html(self.HOSTILE_BODY.format(sentinel_path=sentinel),- title="Pass-through probe",+ title="Escaping probe",)- assert "<svg" in html, "SVG block no longer passes through markdown"+ # Escaped, not passed through as markup.+ assert "<svg" not in html, "raw SVG markup must not reach the renderer"+ assert "<svg" in html, "the SVG block must arrive as escaped text"+ # The benign report text still renders.+ assert "ARRIVAL-CONTROL" in htmldiff --git a/tests/web/services/test_export_generation_contracts.py b/tests/web/services/test_export_generation_contracts.pyindex 56381a9abc..1a7a9df51c 100644--- a/tests/web/services/test_export_generation_contracts.py+++ b/tests/web/services/test_export_generation_contracts.py@@ -871,7 +871,12 @@ class TestODTPandocInvocation:assert cmd[0] == "/usr/bin/pandoc"assert cmd[cmd.index("-o") + 1] == "-"- assert cmd[cmd.index("-f") + 1] == "markdown"+ # Raw passthrough, native divs and spans, and body metadata off:+ # report text reaches the ODT as text.+ assert cmd[cmd.index("-f") + 1] == (+ "markdown-raw_attribute-raw_html-raw_tex"+ "-native_divs-native_spans-yaml_metadata_block"+ )assert cmd[cmd.index("-t") + 1] == "odt"assert result.content == b"PK\x03\x04odt-bytes"diff --git a/tests/web/services/test_pdf_resource_size_limits.py b/tests/web/services/test_pdf_resource_size_limits.pyindex 6c0f495469..e880dc42fa 100644--- a/tests/web/services/test_pdf_resource_size_limits.py+++ b/tests/web/services/test_pdf_resource_size_limits.py@@ -620,18 +620,33 @@ class TestExportsLeaveOutOnlyTheOversizedResource:):# The one at-rule whose failed fetch aborts a render: the export# must still complete, through the retry in _render_pdf.+ #+ # Report markdown now escapes raw HTML, so a `<style>` can no longer+ # arrive from report text; the stylesheet is injected at the HTML+ # layer instead (by stubbing `_markdown_to_html`), which is exactly+ # where WeasyPrint parses it at render time and where `_render_pdf`'s+ # retry lives. This keeps the retry under test independent of the+ # markdown-escaping step (covered separately).origin.add("/profile.icc",gzip.compress(b"\0" * OVERSIZED),headers={"Content-Encoding": "gzip"},)- markdown = (+ html_doc = (+ "<!DOCTYPE html><html><head><meta charset='utf-8'>""<style>@color-profile --p { "- f"src: url('{ORIGIN}/profile.icc'); components: 3; }}</style>\n\n"- "# Report\n\nBody text.\n"+ f"src: url('{ORIGIN}/profile.icc'); components: 3; }}</style>"+ "</head><body><h1>Report</h1><p>Body text.</p></body></html>")- pdf = pdf_service.PDFService().markdown_to_pdf(markdown, title="t")+ with patch.object(+ pdf_service.PDFService,+ "_markdown_to_html",+ lambda self, content, title=None, metadata=None: html_doc,+ ):+ pdf = pdf_service.PDFService().markdown_to_pdf(+ "# Report\n\nBody text.\n", title="t"+ )assert pdf.startswith(b"%PDF")# Refused on the first pass, which it aborted, and again on thediff --git a/tests/web/services/test_pdf_service.py b/tests/web/services/test_pdf_service.pyindex b98d09f8e7..c6a7a312dd 100644--- a/tests/web/services/test_pdf_service.py+++ b/tests/web/services/test_pdf_service.py@@ -9,6 +9,7 @@ Tests cover:- Singleton pattern"""+import ioimport reimport warnings@@ -218,6 +219,243 @@ def hello():assert "Local Deep Research" in html or "LDR" in html+class TestRawHtmlInReportTextIsEscaped:+ """Raw HTML in report text is escaped, matching the on-screen view (#7365).++ The report body (the synthesized answer, and the Sources block whose+ titles come from search-result metadata) is LLM- and web-derived. The+ on-screen report view escapes raw author HTML; PDF export now does the+ same, so tags in report text reach the exported PDF as visible text+ rather than as markup. They must come out escaped in the HTML handed to+ WeasyPrint, while the markdown WeasyPrint should still render keeps+ working.+ """++ # (name, raw-HTML snippet, substrings that must appear ESCAPED in output)+ RAW_TAGS = [+ (+ "style",+ "<style>body::after{content:'style-marker'}</style>",+ "<style>",+ ),+ ("base", '<base href="https://example.invalid/">', "<base"),+ (+ "link_attachment",+ '<link rel="attachment" href="https://example.invalid/linked.txt">',+ "<link",+ ),+ (+ "a_attachment",+ '<a rel="attachment" download="notes.txt" '+ 'href="https://example.invalid/anchor.txt">x</a>',+ "<a rel=",+ ),+ (+ "meta_author",+ '<meta name="author" content="Marker Author">',+ '<meta name="author"',+ ),+ (+ "object",+ '<object data="object.txt" type="text/plain">o</object>',+ "<object",+ ),+ ]++ def _service(self):+ from local_deep_research.web.services.pdf_service import PDFService++ return PDFService()++ @pytest.mark.parametrize(+ "name,snippet,escaped",+ RAW_TAGS,+ ids=[t[0] for t in RAW_TAGS],+ )+ def test_raw_tag_in_answer_is_escaped(self, name, snippet, escaped):+ html = self._service()._markdown_to_html(+ f"# Report\n\nIntro paragraph. {snippet} End.\n"+ )++ # The raw tag never survives; it is present only as escaped text.+ assert snippet not in html+ assert escaped in html++ @pytest.mark.parametrize(+ "name,snippet,escaped",+ RAW_TAGS,+ ids=[t[0] for t in RAW_TAGS],+ )+ def test_raw_tag_in_source_title_is_escaped(self, name, snippet, escaped):+ # Source titles are interpolated as plain text into the Sources+ # block, which flows through the same conversion as the answer.+ markdown = (+ "# Report\n\nBody.\n\n## Sources\n\n"+ f"[1] Title {snippet} (source nr: 1)\n"+ " URL: https://example.org/page\n"+ )++ html = self._service()._markdown_to_html(markdown)++ assert snippet not in html+ assert escaped in html++ def test_style_cannot_add_a_stylesheet_element(self):+ html = self._service()._markdown_to_html(+ "# Report\n\n<style>p{color:red}</style>\n"+ )++ # No real <style> element reaches WeasyPrint from report text.+ assert "<style>" not in html+ assert "<style>" in html++ def test_meta_author_does_not_become_a_meta_element(self):+ html = self._service()._markdown_to_html(+ '# Report\n\n<meta name="author" content="Marker">\n'+ )++ # The only <meta> element is the pipeline's own charset tag.+ assert '<meta name="author" content="Marker">' not in html+ assert html.count("<meta ") == 1+ assert '<meta charset="utf-8">' in html++ def test_svg_block_is_escaped_not_passed_through(self):+ html = self._service()._markdown_to_html(+ '# Report\n\n<svg xmlns="http://www.w3.org/2000/svg">'+ "<rect/></svg>\n"+ )++ assert "<svg" not in html+ assert "<svg" in html++ @pytest.mark.parametrize(+ "block,raw_open,escaped_open",+ [+ (+ '<div class="raw-block-marker">\n'+ "Text inside a raw block.\n"+ "</div>",+ '<div class="raw-block-marker">',+ '<div class="raw-block-marker">',+ ),+ (+ '<table class="raw-table-marker">\n'+ "<tr><td>raw cell</td></tr>\n"+ "</table>",+ '<table class="raw-table-marker">',+ '<table class="raw-table-marker">',+ ),+ ],+ ids=["div", "table"],+ )+ def test_block_level_raw_element_is_escaped(+ self, block, raw_open, escaped_open+ ):+ """A block-level element on lines of its own is handled by+ Python-Markdown's ``html_block`` preprocessor, which passes it through+ whole. This pins that handler's deregistration directly, with+ block-level elements other than ``<style>``."""+ html = self._service()._markdown_to_html(+ f"# Report\n\n{block}\n\nAfter.\n"+ )++ assert raw_open not in html+ assert escaped_open in html+ # The markdown after the block still renders as markdown.+ assert "<p>After.</p>" in html++ def test_ordinary_markdown_still_renders(self):+ markdown = (+ "# Heading\n\n"+ "[TOC]\n\n"+ "## Subheading\n\n"+ "Paragraph with **bold**, *italic* and a "+ "[link](https://example.org).\n\n"+ "\n\n"+ "| A | B |\n|---|---|\n| 1 | 2 |\n\n"+ "```python\nx = 1\n```\n\n"+ "A claim.[^1]\n\n[^1]: A footnote.\n"+ )++ html = self._service()._markdown_to_html(markdown)++ # Headings + toc+ assert 'id="heading"' in html+ assert 'id="subheading"' in html+ assert 'class="toc"' in html+ # Emphasis+ assert "<strong>bold</strong>" in html+ assert "<em>italic</em>" in html+ # Markdown-generated link and image survive (Markdown emits these,+ # they are not raw author HTML).+ assert '<a href="https://example.org">link</a>' in html+ assert '<img alt="alt" src="https://example.org/image.png"' in html+ # Table+ assert "<table>" in html+ assert "<td>1</td>" in html+ # Fenced code+ assert "language-python" in html+ # Footnote+ assert 'class="footnote-ref"' in html++ def test_export_with_raw_tags_fetches_and_embeds_nothing(self):+ """End to end: a body full of raw tags still produces a PDF, and none+ of the tags acts on it. The render's url_fetcher is replaced by a spy+ that would serve any URL, so a tag passed through as markup would+ show up both as a fetch and in the PDF: a document author from the+ ``<meta>``, an embedded file from the attachment links."""+ from pypdf import PdfReader++ from local_deep_research.web.services import pdf_service++ # Settle the lazy import, so the response type below is populated.+ pdf_service._ensure_weasyprint()+ response_type = pdf_service.URLFetcherResponse+ fetched: list[str] = []++ class _ServesAnything:+ _fail_on_errors = False++ def __call__(self, url):+ fetched.append(url)+ body = b"served body"+ if response_type is not None:+ return response_type(+ url, body=body, headers={"Content-Type": "text/plain"}+ )+ return {"string": body, "mime_type": "text/plain"}++ markdown = "# Report\n\n" + "\n\n".join(+ snippet for _, snippet, _ in self.RAW_TAGS+ )++ with patch.object(pdf_service, "_safe_url_fetcher", _ServesAnything()):+ pdf_bytes = pdf_service.PDFService().markdown_to_pdf(+ markdown, title="t"+ )++ assert pdf_bytes[:4] == b"%PDF"+ # No tag made the renderer fetch anything.+ assert fetched == [], fetched+ reader = PdfReader(io.BytesIO(pdf_bytes))+ # No document author from the <meta> tag ...+ assert (reader.metadata or {}).get("/Author") != "Marker Author"+ # ... and no embedded file, in the name tree or as an annotation.+ assert not reader.attachments+ file_annotations = [+ annotation+ for page in reader.pages+ for annotation in (+ ref.get_object() for ref in page.get("/Annots") or []+ )+ if annotation.get("/Subtype") == "/FileAttachment"+ ]+ assert file_annotations == []+ # The tags were rendered, as visible text.+ text = "\n".join(page.extract_text() or "" for page in reader.pages)+ assert "Marker Author" in text, text[:400]++class TestMarkdownToPDF:"""Tests for markdown_to_pdf method."""@@ -667,28 +905,42 @@ class TestSafeUrlFetcher:assert "_fail_on_errors" in inspect.getsource(fetch)def test_render_succeeds_when_body_url_is_blocked(self):- """End-to-end: a malicious URL in the markdown body doesn't break rendering.-- Covers the full chain (markdown passthrough → WeasyPrint → fetcher →- ValueError → WeasyPrint skips resource → PDF still renders), which- is what the SSRF guard relies on. Would fail if a future WeasyPrint- upgrade changed the ValueError-as-skip contract, if Python-Markdown- started stripping raw HTML, or if the url_fetcher got unwired.+ """End-to-end: a blocked URL in the markdown body doesn't break rendering.++ Covers the chain the SSRF guard relies on: Markdown image ->+ WeasyPrint -> fetcher -> refusal (a ValueError) -> WeasyPrint skips+ the resource -> PDF still renders. A Markdown ```` image is+ used because it is what report text can still produce: raw HTML in+ report text is escaped to visible text, while the images Markdown+ itself emits reach the render-time fetcher. ``validate_url`` is+ wrapped, not replaced (the real guard still decides), to record that+ the render asked it about the image. Would fail if the url_fetcher+ got unwired. It would not catch a WeasyPrint upgrade that stopped+ skipping an image whose fetch is refused: ``_render_pdf`` would then+ retry with refusals skipped and the PDF would still render. That+ retry is covered by ``TestRefusedResourceDoesNotAbortTheExport`` in+ tests/web_services/test_pdf_service.py."""- from local_deep_research.web.services.pdf_service import PDFService+ from local_deep_research.web.services import pdf_service- service = PDFService()- markdown = (- "# Report\n\n"- "Body text.\n\n"- '<img src="http://169.254.169.254/latest/meta-data/" alt="x" />\n'- )+ blocked = "http://169.254.169.254/latest/meta-data/"+ asked: list[str] = []+ real_validate_url = pdf_service.validate_url- pdf_bytes = service.markdown_to_pdf(markdown)+ def recording_validate_url(url, *args, **kwargs):+ asked.append(url)+ return real_validate_url(url, *args, **kwargs)++ markdown = f"# Report\n\nBody text.\n\n\n"++ with patch.object(pdf_service, "validate_url", recording_validate_url):+ pdf_bytes = pdf_service.PDFService().markdown_to_pdf(markdown)assert isinstance(pdf_bytes, bytes)assert pdf_bytes[:4] == b"%PDF"assert len(pdf_bytes) > 100+ # The render consulted the guard about the image: the fetcher is wired.+ assert blocked in asked, askedclass TestSafeUrlFetcherDnsPin:diff --git a/tests/web_services/test_pdf_service.py b/tests/web_services/test_pdf_service.pyindex 5ed6f19f03..b19a8edb44 100644--- a/tests/web_services/test_pdf_service.py+++ b/tests/web_services/test_pdf_service.py@@ -409,47 +409,98 @@ class TestRefusedResourceDoesNotAbortTheExport:outside the `try`, so the `URLFetchingError` escapes `CSS.__init__` andthen `markdown_to_pdf`, and the export route answers a generic 500.- Report content is LLM- and web-derived and python-markdown passes raw HTML- straight through, so a `<style>` block carrying that at-rule reaches the- renderer. The URL used below is the cloud metadata address the SSRF guard+ Raw HTML in report text is escaped by `_markdown_to_html`, so a `<style>`+ element cannot come from report markdown, and the export route passes no+ custom stylesheet; the retry in `_render_pdf` is defence in depth for a+ stylesheet that does reach the document. These tests therefore inject the+ `<style>` at the HTML layer (by stubbing `_markdown_to_html`), which is+ where WeasyPrint parses it at render time. `validate_url` and `HTML` are+ wrapped, not replaced: the real guard still decides, and the wrappers+ record which URLs it was asked about and which fetcher each render pass+ used. The URLs used below are the cloud metadata address the SSRF guardalways blocks, so the refusal comes from this service's own fetcher."""BLOCKED = "http://169.254.169.254/q.icc"+ BLOCKED_IMPORT = "http://169.254.169.254/x.css"- def _report(self, head: str) -> str:- return f"{head}\n\n# Report\n\nBody text.\n"+ def _export(self, stylesheet: str):+ """Export a report whose document carries ``stylesheet`` in a+ ``<style>`` element; return the PDF, the URLs the guard was asked+ about, and the url_fetcher of each render pass."""+ from local_deep_research.web.services import pdf_service++ # Settle the lazy import first, or its first run would replace the+ # `HTML` wrapper patched in below with WeasyPrint's own class.+ pdf_service._ensure_weasyprint()++ html_doc = (+ "<!DOCTYPE html><html><head><meta charset='utf-8'>"+ f"<style>{stylesheet}</style>"+ "</head><body><h1>Report</h1><p>Body text.</p></body></html>"+ )+ asked: list[str] = []+ real_validate_url = pdf_service.validate_url++ def recording_validate_url(url, *args, **kwargs):+ asked.append(url)+ return real_validate_url(url, *args, **kwargs)++ passes: list = []+ original_html = pdf_service.HTML++ def recording_html(*args, **kwargs):+ passes.append(kwargs.get("url_fetcher"))+ return original_html(*args, **kwargs)++ with (+ patch.object(pdf_service, "validate_url", recording_validate_url),+ patch.object(pdf_service, "HTML", recording_html),+ patch.object(+ pdf_service.PDFService,+ "_markdown_to_html",+ lambda self, content, title=None, metadata=None: html_doc,+ ),+ ):+ pdf = pdf_service.PDFService().markdown_to_pdf(+ "# Report\n\nBody text.\n", title="t"+ )+ return pdf, asked, passesdef test_a_refused_color_profile_still_exports(self):- from local_deep_research.web.services.pdf_service import PDFService+ """Without the retry the refused `@color-profile` aborts the render+ and `markdown_to_pdf` raises, so this fails if the retry is removed."""+ from local_deep_research.web.services import pdf_service- markdown = self._report(- "<style>@color-profile --q { src: url('"+ pdf, asked, passes = self._export(+ "@color-profile --q { src: url('"+ self.BLOCKED- + "'); components: 3; }</style>"+ + "'); components: 3; }")- assert (- PDFService()- .markdown_to_pdf(markdown, title="t")- .startswith(b"%PDF")- )+ assert pdf.startswith(b"%PDF")+ # The guard refused the profile on the first pass, which that refusal+ # aborted, and again on the retry, which skipped it.+ assert asked == [self.BLOCKED, self.BLOCKED], asked+ assert len(passes) == 2, passes+ assert passes[0] is pdf_service._safe_url_fetcher+ assert isinstance(passes[1], pdf_service._SkippingUrlFetcher)def test_a_refused_import_still_exports(self):"""The control, and the reason the report calls this an asymmetry: thisshape already worked, so a fix that made both fail would satisfy a- weaker test than this one."""- from local_deep_research.web.services.pdf_service import PDFService+ weaker test than this one. WeasyPrint skips the refused `@import`+ itself, so the export completes in one pass, without the retry."""+ from local_deep_research.web.services import pdf_service- markdown = self._report(- "<style>@import url('http://169.254.169.254/x.css');</style>"+ pdf, asked, passes = self._export(+ f"@import url('{self.BLOCKED_IMPORT}');")- assert (- PDFService()- .markdown_to_pdf(markdown, title="t")- .startswith(b"%PDF")- )+ assert pdf.startswith(b"%PDF")+ # The stylesheet reached the renderer and the guard refused the import.+ assert asked == [self.BLOCKED_IMPORT], asked+ assert passes == [pdf_service._safe_url_fetcher], passesdef test_the_ordinary_report_is_rendered_once(self):"""Second control. The retry must be reached only by the render that@@ -459,6 +510,12 @@ class TestRefusedResourceDoesNotAbortTheExport:"""from local_deep_research.web.services import pdf_service+ # Settle the lazy import first, as `_export` does: captured before+ # it, `original` would be None, the import inside the call would+ # replace the wrapper, and leaving the patch would restore None for+ # every later test in this worker.+ pdf_service._ensure_weasyprint()+calls = []original = pdf_service.HTML@@ -729,6 +786,12 @@ class TestRetriedRenderEndToEnd:at-rule whose fetch failure aborts the render). `_URL_FETCHER` isreplaced by a spy, so nothing leaves the process: the assertions are onwhat the spy was *asked* to fetch.++ Report markdown now escapes raw HTML, so the stylesheet can no longer+ arrive from report text; it is injected at the HTML layer (by stubbing+ `_markdown_to_html`), which is where WeasyPrint parses it at render time+ and where `_render_pdf`'s retry lives. The retry and the SSRF guard are+ thus exercised independently of the markdown-escaping step."""CREDENTIALED_BLOCKED = (@@ -779,7 +842,8 @@ class TestRetriedRenderEndToEnd:# The hostile resource comes first, so it is what aborts the first# pass; the refused one is then reached only by the retry.- markdown = (+ html_doc = (+ "<!DOCTYPE html><html><head><meta charset='utf-8'>""<style>""@color-profile --a { src: url('"+ self.HOSTILE@@ -787,7 +851,8 @@ class TestRetriedRenderEndToEnd:"@color-profile --b { src: url('"+ self.CREDENTIALED_BLOCKED+ "'); components: 3; }"- "</style>\n\n# Report\n\nBody text.\n"+ "</style>"+ "</head><body><h1>Report</h1><p>Body text.</p></body></html>")html_calls: list = []original_html = pdf_service.HTML@@ -807,9 +872,14 @@ class TestRetriedRenderEndToEnd:patch.object(pdf_service, "validate_url", fake_validate_url),patch.object(dns_pinning, "_real_getaddrinfo", public_resolver),patch.object(pdf_service, "HTML", recording_html),+ patch.object(+ pdf_service.PDFService,+ "_markdown_to_html",+ lambda self, content, title=None, metadata=None: html_doc,+ ),):pdf = pdf_service.PDFService().markdown_to_pdf(- markdown, title="t"+ "# Report\n\nBody text.\n", title="t")finally:loguru_logger.disable("local_deep_research")