Skip to content

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

59.4 KB
Raw Blame
"""Client-side XSS sinks and rendered research output.

Companion to ``test_injection_and_template_safety.py``, which stops at
the server boundary: it pins the ``|safe`` census, ``|tojson`` contexts,
SQL/path injection, and the *existence* of an audit note on every
``no-unsanitized`` suppression. It deliberately does not check whether
those audit notes are **true**. This module does.

Three questions, all decided from source because they are properties of
the code, not of one response:

1. **Do the ~114 ``-- audited`` suppressions hold?** Nearly all of them
   reduce to "every interpolation goes through ``escapeHtml``/``esc``".
   That claim has two failure modes the note itself cannot show:
   the *name* ``escapeHtml`` may be bound to something that does not
   escape what the surrounding context needs, and the *context* may be
   an HTML attribute where an escaper that only covers ``& < >`` is not
   enough. ESLint cannot see either: ``no-unsanitized`` is configured
   with a **name-based** ``escape.methods`` allow-list, so any callee
   spelled ``esc`` or ``escapeHtml`` silences the rule regardless of
   what it does.

2. **Is LLM-generated report text sanitised before display, and are its
   links given ``rel="noopener"``?** Report/note bodies are rendered as
   Markdown. LLM output is attacker-influenceable through a poisoned
   page the researcher fetched, so it is untrusted input.

3. **Can a user-controlled filename come back with an HTML-ish
   ``Content-Type``?** (Stored XSS via the download path.)

Every scanner here ships with a pair of self-tests proving it flags a
deliberately-unsafe synthetic source and stays quiet on a safe one,
plus a floor assertion on how many real sites it reached — a census
scanner that silently matches nothing is the failure this file is most
exposed to.
"""

# allow: no-sut-import — a static census over the production SOURCE of
# the JavaScript bundle, the Jinja templates and the routers: what is
# under test is which escaper a name is bound to and which HTML context
# it is used in, neither of which is observable by importing a module.

from __future__ import annotations

import ast
import re
from pathlib import Path

import pytest

REPO_ROOT = Path(__file__).resolve().parents[2]
SRC = REPO_ROOT / "src" / "local_deep_research"
STATIC_JS = SRC / "web" / "static" / "js"
TEMPLATES = SRC / "web" / "templates"
ROUTERS = SRC / "web" / "routers"
ESLINT_CONFIG = REPO_ROOT / "eslint.config.js"

# Attack payloads live in named constants (never inline) so the repo's
# payload hooks and reviewers can see them at a glance.
ATTR_BREAKOUT = '" onmouseover=alert(1) x="'
TAG_BREAKOUT = "<img src=x onerror=alert(1)>"

# The exact character sequences an escaper must produce. Kept as
# constants so no test spells a bare entity next to a bare metacharacter
# (the double-escaping hook reads those as a mistake).
QUOT_ENTITY = "&" + "quot;"
LT_ENTITY = "&" + "lt;"


def _js_sources():
    """Yield ``(posix_relative_path, source_text)`` for every JS file."""
    for path in sorted(STATIC_JS.rglob("*.js")):
        yield (
            path.relative_to(STATIC_JS).as_posix(),
            path.read_text(encoding="utf-8", errors="replace"),
        )


# ---------------------------------------------------------------------
# Template-literal parsing
#
# Everything below needs to know which ``${...}`` sits where inside a
# JS template literal. A regex cannot do it: template literals nest,
# and ``${}`` bodies contain braces and further literals.
# ---------------------------------------------------------------------


def template_literal_bodies(text: str) -> list[str]:
    """Return the body of every top-level template literal in ``text``.

    Substitution bodies are kept inline (so ``${...}`` offsets are the
    offsets a reader sees), but their braces are tracked so a ``}`` or
    a backtick inside a substitution does not end the literal early.
    """
    out: list[str] = []
    i, n = 0, len(text)
    while i < n:
        if text[i] != "`":
            i += 1
            continue
        j, depth = i + 1, 0
        while j < n:
            ch = text[j]
            if ch == "\\":
                j += 2
                continue
            if text[j : j + 2] == "${":
                depth += 1
                j += 2
                continue
            if ch == "}" and depth:
                depth -= 1
                j += 1
                continue
            if ch == "`" and depth == 0:
                break
            j += 1
        out.append(text[i + 1 : j])
        i = j + 1
    return out


def substitutions(body: str) -> list[tuple[int, str]]:
    """Return ``(offset, expression)`` for each ``${...}`` in ``body``."""
    out: list[tuple[int, str]] = []
    i = 0
    while True:
        start = body.find("${", i)
        if start < 0:
            return out
        depth, j = 1, start + 2
        while j < len(body) and depth:
            if body[j] == "{":
                depth += 1
            elif body[j] == "}":
                depth -= 1
            j += 1
        out.append((start, body[start + 2 : j - 1]))
        i = j


def in_double_quoted_attribute(body: str, offset: int) -> bool:
    """Is ``offset`` inside a ``attr="..."`` value of an open tag?

    True when the nearest ``<`` comes after the nearest ``>`` (we are
    inside a tag) and an odd number of double quotes separates that
    ``<`` from ``offset`` (we are inside an attribute value).
    """
    lt = body.rfind("<", 0, offset)
    gt = body.rfind(">", 0, offset)
    if lt < 0 or lt < gt:
        return False
    return body[lt:offset].count('"') % 2 == 1


def attribute_substitutions(text: str) -> list[str]:
    """Every ``${...}`` expression rendered into a quoted attribute."""
    out = []
    for body in template_literal_bodies(text):
        for offset, expr in substitutions(body):
            if in_double_quoted_attribute(body, offset):
                out.append(" ".join(expr.split()))
    return out


_SAFE_SYNTHETIC_JS = """
const row = `<td>${escapeHtml(item.name)}</td>`;
const link = `<a href="/x?q=${encodeURIComponent(q)}">go</a>`;
"""

_UNSAFE_SYNTHETIC_JS = """
const cell = `<td title="${escapeHtml(item.query)}">${n}</td>`;
"""


def test_attribute_scanner_flags_an_attribute_context_substitution():
    assert attribute_substitutions(_UNSAFE_SYNTHETIC_JS) == [
        "escapeHtml(item.query)"
    ]


def test_attribute_scanner_is_quiet_on_text_context_substitutions():
    """A ``>``-terminated tag ends attribute context; ``?q=`` is not one."""
    assert attribute_substitutions(_SAFE_SYNTHETIC_JS) == [
        "encodeURIComponent(q)"
    ]


def test_attribute_scanner_does_not_run_past_a_closed_tag():
    closed = '`<div class="a">${untrusted}</div>`'
    assert attribute_substitutions(closed) == []


def test_template_parser_survives_nested_literals():
    nested = "`<b>${cond ? `<i>${esc(x)}</i>` : ''}</b>`"
    bodies = template_literal_bodies(nested)
    assert len(bodies) == 1, bodies
    assert [e for _, e in substitutions(bodies[0])] == [
        "cond ? `<i>${esc(x)}</i>` : ''"
    ]


# ---------------------------------------------------------------------
# What the ``escapeHtml`` / ``esc`` names are actually bound to
#
# ESLint's ``no-unsanitized`` ``escape.methods`` list is matched on the
# callee *name*. A module-local binding of one of those names silences
# the rule no matter what the function does, so the names have to be
# audited by hand — which is what this section automates.
# ---------------------------------------------------------------------

_ESCAPER_NAMES = (
    "escapeHtml",
    "esc",
    "_escapeHtml",
    "escapeHtmlFallback",
    "escapeAttr",
    "escapeHtmlAttribute",
)
_DEF_RE = re.compile(
    r"^\s*(?:function\s+(" + "|".join(_ESCAPER_NAMES) + r")\s*\("
    r"|(?:const|let|var)\s+(" + "|".join(_ESCAPER_NAMES) + r")\s*=)"
)

#: Escapes ``"`` into an entity — safe in text *and* attribute context.
ENTITY = "ENTITY"
#: Text-node serialisation (``textContent`` in, ``innerHTML`` out).
#: Escapes ``& < >`` but NOT ``"`` — unsafe inside a quoted attribute.
TEXT_NODE_ONLY = "TEXT_NODE_ONLY"
#: Backslash-escapes for a *JavaScript string* literal. A backslash is
#: not an escape character to the HTML tokenizer, so ``\\"`` still ends
#: an attribute value.
JS_STRING = "JS_STRING"
#: ``window.escapeHtml || <other-binding>`` — inherits that binding.
ALIAS = "ALIAS"
#: Returns its argument (stringified) unchanged.
NO_OP = "NO_OP"


def classify_escaper(text: str, line_index: int) -> str:
    """Classify the escaper defined at ``line_index`` of ``text``."""
    lines = text.splitlines()
    body = "\n".join(lines[line_index : line_index + 16])
    head = lines[line_index]
    if "textContent" in body and "innerHTML" in body:
        return TEXT_NODE_ONLY
    if re.search(r'replace\(\s*/"/g\s*,\s*[\'"]\\\\', body):
        return JS_STRING
    char_class = re.search(r"replace\(\s*/\[([^]]*)]/g", body)
    if char_class and '"' in char_class.group(1):
        # The replacement is either an inline entity map or a lookup in
        # a module-level one; both must map ``"`` to the entity.
        if QUOT_ENTITY in body or QUOT_ENTITY in text:
            return ENTITY
    if re.search(
        r"replace\(\s*/\"/g\s*,\s*['\"]" + re.escape(QUOT_ENTITY), body
    ) and re.search(r"replace\(\s*/'/g\s*,\s*['\"]&#39;", body):
        # A chained quote-to-entity replace after a base call, e.g.
        # ``escapeHtml(text).replace(/"/g, '&quot;').replace(/'/g,
        # '&#39;')``. Still an entity escaper (assuming the base call
        # handles ``& < >``) -- just spelled without one bracketed
        # character class, which the check above looks for.
        return ENTITY
    if re.search(r"=\s*\w+(?:\.\w+)*\s*\|\|\s*[A-Za-z_$][\w$]*\s*;", head):
        return ALIAS
    return NO_OP


def escaper_definitions(text: str) -> list[tuple[int, str, str]]:
    """Return ``(line_number, name, classification)`` for each binding."""
    out = []
    for index, line in enumerate(text.splitlines()):
        match = _DEF_RE.match(line)
        if not match:
            continue
        name = match.group(1) or match.group(2)
        out.append((index + 1, name, classify_escaper(text, index)))
    return out


_ENTITY_MAP_JS = (
    "{'&':'&"
    + "amp;','<':'&"
    + "lt;','>':'&"
    + "gt;','\"':'&"
    + "quot;',\"'\":'&"
    + "#39;'}"
)
_SYNTHETIC_ENTITY = (
    "const esc = (s) => String(s).replace(/[&<>\"']/g, "
    "(m) => (" + _ENTITY_MAP_JS + ")[m]);\n"
)
_SYNTHETIC_TEXT_NODE = (
    "function escapeHtml(t) {\n"
    "  const div = document.createElement('div');\n"
    "  div.textContent = String(t);\n"
    "  return div.innerHTML;\n"
    "}\n"
)
_SYNTHETIC_NO_OP = "const esc = window.escapeHtml || (s => String(s || ''));\n"


_SYNTHETIC_CHAINED_ENTITY = _SYNTHETIC_TEXT_NODE + (
    "function escapeHtmlAttribute(text) {\n"
    "  return escapeHtml(text).replace(/\"/g, '&quot;').replace(/'/g, '&#39;');\n"
    "}\n"
)


def test_escaper_classifier_recognises_an_entity_escaper():
    found = escaper_definitions(_SYNTHETIC_ENTITY)
    assert found == [(1, "esc", ENTITY)], found


def test_escaper_classifier_recognises_a_chained_quote_replace_as_entity():
    """An entity escaper spelled as two ``.replace()`` calls, not one
    bracketed character class -- the shape ``escapeHtmlAttribute`` takes
    in components/context-overflow.js."""
    found = escaper_definitions(_SYNTHETIC_CHAINED_ENTITY)
    assert (6, "escapeHtmlAttribute", ENTITY) in found, found


def test_escaper_classifier_flags_a_text_node_only_escaper():
    found = escaper_definitions(_SYNTHETIC_TEXT_NODE)
    assert found == [(1, "escapeHtml", TEXT_NODE_ONLY)], found


def test_escaper_classifier_flags_an_identity_fallback():
    found = escaper_definitions(_SYNTHETIC_NO_OP)
    assert found == [(1, "esc", NO_OP)], found


def test_escaper_classifier_is_quiet_on_a_non_escaper():
    assert escaper_definitions("const total = counts.length;\n") == []


#: Every module-local binding of an ESLint-allow-listed escaper name
#: that is NOT a quote-escaping entity encoder, frozen after review.
#: Keyed by ``file::name`` so a rename or a new one shows up as a diff.
REVIEWED_NON_ENTITY_ESCAPERS = {
    # Text-node serialisation. Safe where it is used for element text;
    # NOT safe inside a quoted attribute (see the attribute census).
    "components/context-overflow.js::escapeHtml": TEXT_NODE_ONLY,
    "components/progress.js::escapeHtml": TEXT_NODE_ONLY,
    # Fixed: pages/news.js::escapeAttr (a JavaScript-string escaper used
    # inside HTML attributes -- see the misuse census below) was removed
    # entirely; ids/queries now travel in data-* attributes read back
    # through event delegation. See
    # test_news_no_longer_has_a_javascript_string_attribute_escaper.
    #
    # Identity fallback: when ``window.escapeHtml`` is absent this
    # escapes nothing at all, and ESLint accepts it because it is
    # spelled ``esc``.
    "components/settings.js::esc": NO_OP,
}


def test_every_escaper_binding_is_an_entity_encoder_or_reviewed():
    """The name-based lint allow-list must not be silently subverted."""
    bindings, non_entity = 0, {}
    for rel, text in _js_sources():
        for _, name, kind in escaper_definitions(text):
            bindings += 1
            if kind in (ENTITY, ALIAS):
                continue
            non_entity[f"{rel}::{name}"] = kind
    assert bindings >= 20, (
        f"expected the known escaper bindings, found {bindings} — "
        "the walk is not reaching the JS tree"
    )
    assert non_entity == REVIEWED_NON_ENTITY_ESCAPERS


def resolve_alias(text: str, line_no: int, depth: int = 4) -> str:
    """Follow ``a = window.x || b`` chains to the binding that escapes.

    Returns the classification of the first non-``ALIAS`` binding
    reached, or ``ALIAS`` if the chain leaves the module (the global
    ``window.escapeHtml``, which is the entity encoder in
    ``security/xss-protection.js``) or runs past ``depth``.
    """
    lines = text.splitlines()
    bindings = {name: (n, kind) for n, name, kind in escaper_definitions(text)}
    for _ in range(depth):
        target = lines[line_no - 1].split("||")[1].strip().rstrip(";").strip()
        if target not in bindings:
            return ALIAS
        line_no, kind = bindings[target]
        if kind != ALIAS:
            return kind
    raise AssertionError(f"alias chain longer than {depth} hops")


def test_alias_resolver_follows_a_two_hop_chain():
    chained = (
        _SYNTHETIC_ENTITY
        + "const escapeHtml = window.escapeHtml || esc;\n"
        + "const escapeAttr = window.escapeHtmlAttribute || escapeHtml;\n"
    )
    assert resolve_alias(chained, 3) == ENTITY


def test_alias_resolver_reports_an_unresolved_chain():
    external = "const esc = window.escapeHtml || somethingElse;\n"
    assert resolve_alias(external, 1) == ALIAS


def test_alias_bindings_resolve_to_an_entity_encoder():
    """``x || escapeHtmlFallback`` is only as good as the fallback."""
    aliases = 0
    for rel, text in _js_sources():
        for line_no, name, kind in escaper_definitions(text):
            if kind != ALIAS:
                continue
            aliases += 1
            resolved = resolve_alias(text, line_no)
            assert resolved in (ENTITY, ALIAS), (
                f"{rel}:{line_no} {name} resolves to {resolved}"
            )
    assert aliases >= 8, f"expected the known alias bindings, found {aliases}"


def test_eslint_escape_allow_list_is_name_based_and_pinned():
    """Pin the allow-list, because its entries are trusted by name."""
    config = ESLINT_CONFIG.read_text(encoding="utf-8")
    block = re.search(r"escape:\s*{\s*methods:\s*\[(.*?)]", config, re.S)
    assert block, "no-unsanitized escape.methods block not found"
    methods = set(re.findall(r'"([^"]+)"', block.group(1)))
    assert {"escapeHtml", "esc", "sanitizeHtml"} <= methods, methods
    # Any *new* name added here must be audited by the census above.
    assert methods == {
        "escapeHtml",
        "esc",
        "DOMPurify.sanitize",
        "window.DOMPurify.sanitize",
        "sanitizeHtml",
        "sanitizeHTML",
        "window.escapeHtml",
        "window.sanitizeHtml",
        "window.XSSProtection.escapeHtml",
        "window.LDRTemplateEvents.attributes",
    }


# ---------------------------------------------------------------------
# Attribute-context census: which sinks escape with the wrong escaper
# ---------------------------------------------------------------------

_ESCAPER_CALL = re.compile(r"\b(escapeHtml|esc|escapeAttr)\s*\(")


def attribute_escaper_misuses(rel: str, text: str) -> list[str]:
    """Attribute substitutions escaped by a non-quote-safe escaper."""
    local = {
        name: kind
        for _, name, kind in escaper_definitions(text)
        if kind not in (ALIAS,)
    }
    out = []
    for expr in attribute_substitutions(text):
        call = _ESCAPER_CALL.search(expr)
        if not call:
            continue
        kind = local.get(call.group(1))
        if kind in (TEXT_NODE_ONLY, JS_STRING, NO_OP):
            out.append(expr)
    return out


_SYNTHETIC_MISUSE = _SYNTHETIC_TEXT_NODE + (
    'const row = `<td title="${escapeHtml(req.query)}">x</td>`;\n'
)
_SYNTHETIC_CORRECT = _SYNTHETIC_TEXT_NODE + (
    "const row = `<td>${escapeHtml(req.query)}</td>`;\n"
)


def test_misuse_scanner_flags_a_text_escaper_in_attribute_context():
    assert attribute_escaper_misuses("x.js", _SYNTHETIC_MISUSE) == [
        "escapeHtml(req.query)"
    ]


def test_misuse_scanner_is_quiet_when_the_same_escaper_is_text_context():
    assert attribute_escaper_misuses("x.js", _SYNTHETIC_CORRECT) == []


#: Attribute-context substitutions escaped by something that does not
#: neutralise ``"``, frozen after review. Each entry is a real defect;
#: the fence exists so no *new* one is introduced silently.
#:
#: Both previously-pinned defects are fixed:
#:
#: * components/context-overflow.js's title attributes used the
#:   module-local text-node ``escapeHtml`` (``escapeHtml(req.model)`` etc);
#:   they now go through ``escapeHtmlAttribute`` (an entity escaper, see
#:   the census above), a distinct call the misuse scanner's
#:   ``_ESCAPER_CALL`` regex does not even match -- so it correctly finds
#:   nothing to flag at these sites any more.
#: * pages/news.js's ``escapeAttr`` (a JS-string escaper misused in HTML
#:   attributes) was removed entirely; see
#:   test_news_no_longer_has_a_javascript_string_attribute_escaper.
KNOWN_ATTRIBUTE_ESCAPER_MISUSES = {}


def test_attribute_escaper_misuses_are_exactly_the_reviewed_set():
    found, attribute_sites = {}, 0
    for rel, text in _js_sources():
        attribute_sites += len(attribute_substitutions(text))
        misuses = attribute_escaper_misuses(rel, text)
        if misuses:
            found[rel] = misuses
    assert attribute_sites >= 200, (
        "expected the known attribute-context substitutions, found "
        f"{attribute_sites} — the scanner is not reaching the JS tree"
    )
    assert found == KNOWN_ATTRIBUTE_ESCAPER_MISUSES


def test_news_action_values_do_not_enter_inline_javascript_handlers():
    """Pin the declarative replacement for the removed ``escapeAttr`` sinks."""
    text = (STATIC_JS / "pages" / "news.js").read_text(encoding="utf-8")
    assert "function escapeAttr(" not in text

    render_body = text.split("function renderNewsItems(", 1)[1]
    render_body = render_body.split("\nfunction ", 1)[0]
    recent_body = text.split("function displayRecentSearches(", 1)[1]
    recent_body = recent_body.split("\nfunction ", 1)[0]

    # Static handlers elsewhere in these functions are not an injection
    # boundary. What must not return is a template substitution inside one.
    for body in (render_body, recent_body):
        handlers = re.findall(r'\bon\w+\s*=\s*"([^"]*)"', body)
        assert all("${" not in handler for handler in handlers), handlers

    # Untrusted values are entity-escaped into declarative data attributes;
    # stable listeners read them back instead of evaluating JavaScript text.
    assert 'data-news-id="${escapeHtml(item.id)}"' in render_body
    assert 'data-news-action="toggle-read"' in render_body
    assert 'data-query="${escapeHtml(item.query)}"' in recent_body
    assert (
        "data-search-type=\"${escapeHtml(item.type || 'quick')}\""
        in recent_body
    )
    assert "event.target.closest('[data-news-action]')" in text
    assert "trustedNewsActionControls.get(actionTarget)" in text
    assert "actionCard.dataset.newsId" in text
    assert "e.target.closest('[data-news-page-action]')" in text


def test_news_html_is_rendered_through_dompurify_not_raw_innerhtml():
    """Pin DOMPurify as defense in depth for dynamic news markup."""
    text = (STATIC_JS / "pages" / "news.js").read_text(encoding="utf-8")
    helper = text.split("function safeRenderHTML(container, htmlString) {")
    assert len(helper) == 2, "safeRenderHTML was renamed or removed"
    body = helper[1].split("\nfunction ")[0]
    assert "window.DOMPurify.sanitize(" in body
    assert "RETURN_DOM_FRAGMENT: true" in body
    # The no-DOMPurify branch must degrade to text, never to markup.
    assert "container.textContent = htmlString;" in body
    # Negative half. Without this the test is all positive assertions: a
    # second, unguarded `container.innerHTML = htmlString;` added anywhere
    # in the function would leave every assertion above still true. This
    # also makes the exact end of the body window irrelevant -- a slice
    # that ends too early can only ever *hide* an innerHTML write, and a
    # slice that runs long cannot invent one, since the count is zero.
    assert body.count("container.innerHTML") == 0, (
        "safeRenderHTML writes innerHTML directly; the DOMPurify fragment "
        "path is no longer the only way markup reaches the container"
    )


def test_context_overflow_rows_reach_innerhtml_without_sanitisation():
    """Establishes that the misuse above is a live sink, not a draft."""
    text = (STATIC_JS / "components" / "context-overflow.js").read_text(
        encoding="utf-8"
    )
    assert "tbody.innerHTML = tableRows;" in text
    assert "DOMPurify" not in text, (
        "context-overflow.js now sanitises — re-review the census"
    )
    # The escaper it uses is the text-node one, defined in-file.
    assert ("escapeHtml", TEXT_NODE_ONLY) in [
        (name, kind) for _, name, kind in escaper_definitions(text)
    ]
    # And an attribute breakout is not neutralised by ``& < >`` alone.
    assert "<" not in ATTR_BREAKOUT and ">" not in ATTR_BREAKOUT


def test_inline_event_handlers_are_refused_by_the_csp():
    """Keep the attribute policy explicit alongside the sink census."""
    app = (SRC / "web" / "fastapi_app.py").read_text(encoding="utf-8")
    assert "script-src-attr 'none'; " in app
    assert "script-src 'self' 'unsafe-inline'" not in app


# ---------------------------------------------------------------------
# Markdown / report rendering
# ---------------------------------------------------------------------


def _ui_js() -> str:
    return (STATIC_JS / "services" / "ui.js").read_text(encoding="utf-8")


def test_report_markdown_is_dompurify_sanitised_before_display():
    """Pin the render path, then pin that sanitisation cannot be skipped.

    Fixed from a prior fail-OPEN (see the test below): the marked-based
    render path used to fall back to raw, unsanitized ``processedHtml``
    whenever DOMPurify was undefined. It now requires ``marked``,
    ``DOMPurify`` AND ``sanitizeStable`` to all be present before running
    at all -- any one missing falls through to the escaped-plaintext
    fallback, never to raw ``marked`` output.
    """
    body = _ui_js().split("function renderMarkdown(markdown) {")[1]
    body = body.split("\nfunction ")[0]
    assert "marked.parse(markdown, { renderer })" in body
    assert (
        "typeof marked !== 'undefined' && typeof DOMPurify !== 'undefined'"
        in body
    )
    assert "&& typeof sanitizeStable === 'function') {" in body
    assert "sanitizeStable(html, MARKDOWN_SANITIZE_CONFIG)" in body
    # The sanitised/hardened/reprocessed value, not the raw parsed one, is
    # what is returned.
    assert "${finalHtml}" in body


def test_markdown_sanitize_stable_is_a_dompurify_reparse_fixpoint():
    """``sanitizeStable`` (security/xss-protection.js) is the DOMPurify
    boundary ``renderMarkdown`` relies on above -- proves the claim is not
    just a name. It reparses to a fixpoint (mXSS hardening) but the
    sanitiser underneath every pass is still real ``DOMPurify.sanitize``.
    """
    text = (STATIC_JS / "security" / "xss-protection.js").read_text(
        encoding="utf-8"
    )
    body = text.split("function sanitizeStable(dirty, config) {")[1]
    body = body.split("\n    function ")[0]
    assert "DOMPurify.sanitize(current, config)" in body


def test_report_markdown_sanitisation_fails_closed_without_dompurify():
    """Pin the fail-closed shape, then pin what makes it reachable.

    ``renderMarkdown``'s marked-based render path (with it, the only path
    that produces ``sanitizeStable``-derived HTML) requires ``marked``,
    ``DOMPurify`` and ``sanitizeStable`` together; the eleven suppressions
    that read "renderMarkdown() sanitizes internally via DOMPurify"
    therefore hold only while ``marked`` and ``DOMPurify`` ship together.
    They do: one bundle entry point imports both and assigns both to
    ``window`` in the same module body. Break that pairing and the
    sanitiser disappears with no lint error -- but (unlike before) the
    render path disappears with it, rather than silently going raw.
    """
    body = _render_markdown_body(_strip_js_comments(_ui_js()))
    assert "typeof DOMPurify !== 'undefined'" in body
    assert "typeof sanitizeStable === 'function'" in body
    assert "DOMPurify?.isSupported === true" in body
    assert "return _escapedPlaintextFallback(markdown)" in body
    assert ": processedHtml" not in body
    assert "return processedHtml" not in body

    app_js = (STATIC_JS / "app.js").read_text(encoding="utf-8")
    for line in (
        "import { marked } from 'marked';",
        "import DOMPurify from 'dompurify';",
        "window.marked = marked;",
        "window.DOMPurify = DOMPurify;",
    ):
        assert line in app_js, f"{line!r} left the bundle entry point"

    # No other module may publish window.marked on its own.
    publishers = {
        rel
        for rel, text in _js_sources()
        if re.search(r"window\.marked\s*=", text)
    }
    assert publishers == {"app.js"}, publishers


def test_rendered_report_links_carry_noopener():
    """``marked``'s link renderer is wrapped to add rel + target."""
    body = _ui_js()
    assert 'rel="noopener noreferrer" ' in body
    assert "renderer.link = function(token)" in body
    # ...and the sanitizer's explicit attribute allowlist must include the
    # attributes the wrapper just added, or they would be stripped by the
    # sanitiser that immediately follows (sanitizeStable(html,
    # MARKDOWN_SANITIZE_CONFIG) above).
    body_attr = body.split("const MARKDOWN_ALLOWED_ATTR = [")[1]
    body_attr = body_attr.split("];")[0]
    assert "'target', 'rel'" in body_attr


def test_note_markdown_renderer_escapes_before_building_markup():
    """``basicMarkdownRender`` is a regex renderer: order is the defence."""
    text = (STATIC_JS / "services" / "formatting.js").read_text(
        encoding="utf-8"
    )
    body = text.split("function basicMarkdownRender(text) {")[1]
    body = body.split("\n/**")[0]
    escape_at = body.index("_escapeHtml(text)")
    first_tag = body.index("<h3>")
    assert escape_at < first_tag, "markup is built before escaping"
    # Anchors are gated on a parsed-URL scheme check and carry rel.
    assert "if (!_isSafeLinkUrl(trimmed))" in body
    assert 'target="_blank" rel="noopener noreferrer"' in body
    # And the shared escaper is the entity one, resolved at call time.
    assert ("_escapeHtml", ENTITY) in [
        (name, kind) for _, name, kind in escaper_definitions(text)
    ]


def test_fallback_markdown_renderer_emits_no_markup_from_input():
    """The no-``marked`` path must be plaintext, never partial markdown."""
    fallback = (STATIC_JS / "components" / "fallback" / "ui.js").read_text(
        encoding="utf-8"
    )
    body = fallback.split("function renderMarkdown(markdown) {")[1]
    body = body.split("\n    /**")[0]
    assert "(window.escapeHtml || escapeHtmlFallback)(markdown)" in body
    assert "${escaped}" in body
    assert "marked" not in body


# ---------------------------------------------------------------------
# Markdown hardening parse boundary (Bearer alerts 9655-9657)
#
# The three security-graded hunks pinned here are behaviour-neutral by
# design (the old-vs-new render matrix is byte-identical), so no
# behavioural test can separate the fixed source from the reverted one:
# the vitest cases in tests/js/security/markdown-render-xss.test.js pass
# under both parse paths. The pin therefore has to be structural, on the
# shape of the source. Following the mutation-rejection precedent of
# tests/theme_tests/test_accent_ink_contrast.py's
# test_authored_math_style_exception_rejects_unreviewed_writes: each
# pin runs over the shipped source AND over a copy of the shipped
# source with the exact Bearer revert spliced back in, which the pin
# must reject.
# ---------------------------------------------------------------------

_DOM_PARSE_CALL = "DOMParser().parseFromString("
_TEMPLATE_WRITE_RE = re.compile(r"template\w*\.innerHTML\s*\+?=")
_REPLACEWITH_CALL_RE = re.compile(r"\.replaceWith\s*\(")
#: One ``innerHTML`` WRITE per source line: reads (``return x.innerHTML``)
#: and ``==`` comparisons do not match; ``+=`` does.
_INNERHTML_WRITE_RE = re.compile(r"^[^\n]*\.innerHTML\s*\+?=[^=][^\n]*$", re.M)
_BLANK_WRITE_RE = re.compile(r"\.innerHTML\s*=\s*''\s*;")


def _function_body(text: str, name: str) -> str:
    """The body of top-level ``function name(``, up to its column-0 ``}``.

    Naive in the same way as ``_render_snippet_body`` below: it stops at
    the FIRST ``\\n}`` at column 0 after the function keyword. That is
    correct for the functions pinned here -- none holds a column-0 ``}``
    inside a template literal.
    """
    start = text.index(f"function {name}(")
    end = text.index("\n}", start)
    return text[start:end]


def markdown_parse_boundary_violations(text: str) -> list[str]:
    """Sink shapes the DOMParser/replaceChild rewrite removed.

    Empty on the shipped ui.js. Alerts 9655/9656 had the two markdown
    helpers writing their already-sanitized markup into a
    ``template.innerHTML`` fragment; alert 9657 had the generated-image
    directive swap spelled ``Node.replaceWith``. A violation name is
    phrased as the failure it reports so a red assertion is readable.
    """
    ui = _strip_js_comments(text)
    problems = []
    if _TEMPLATE_WRITE_RE.search(ui):
        problems.append("template.innerHTML assignment returned")
    for name in ("hardenSanitizedMarkdown", "processSpecialMarkdown"):
        if _DOM_PARSE_CALL not in _function_body(ui, name):
            problems.append(f"{name} no longer parses via DOMParser")
    swap = _function_body(ui, "processSpecialMarkdown")
    if "parentNode.replaceChild(" not in swap:
        problems.append(
            "generated-image swap is no longer parentNode.replaceChild"
        )
    if _REPLACEWITH_CALL_RE.search(swap):
        problems.append("generated-image swap calls Node.replaceWith")
    return problems


def test_markdown_helpers_never_write_a_template_innerhtml_fragment():
    """Alerts 9655/9656: parsing goes through the inert DOMParser
    document, never a ``template.innerHTML = html`` fragment write.

    Reverting either fix hunk turns this red (and so does the mutation
    case below, which splices the exact revert back in). The write, not
    the parse, is what is pinned: the DOMParser spelling in
    test_markdown_helpers_parse_their_markup_with_domparser is its
    positive half, so a revert cannot pass by renaming the template.
    """
    problems = markdown_parse_boundary_violations(_ui_js())
    assert not [p for p in problems if "template.innerHTML" in p], problems


def test_markdown_helpers_parse_their_markup_with_domparser():
    """Both hardened helpers parse via ``DOMParser().parseFromString(``.

    One parse per helper, so dropping the parse from either
    ``hardenSanitizedMarkdown`` (alert 9655) or ``processSpecialMarkdown``
    (alert 9656) turns this red even if the removed write is spelled
    without ``template`` in the name.
    """
    problems = markdown_parse_boundary_violations(_ui_js())
    assert not [p for p in problems if "DOMParser" in p], problems


def test_generated_image_swap_is_a_pure_node_operation():
    """Alert 9657: the directive paragraph is swapped with
    ``parentNode.replaceChild(wrapper, paragraph)`` and ``Node.replaceWith``
    does not reappear in the function.

    (``replaceChild`` is scanner-sink consistency, not an escaping fix --
    ``replaceWith`` stringifies a non-node argument to a Text node and
    never parses HTML either -- but the sink removal is what the alert
    grades, so the removal is what is pinned.)
    """
    problems = markdown_parse_boundary_violations(_ui_js())
    assert not [p for p in problems if "generated-image" in p], problems


#: The exact pre-fix shapes behind alerts 9655-9657 (from the fix
#: commit), spliced back into a copy of the shipped source by
#: test_parse_boundary_pins_reject_each_exact_bearer_revert below. Each
#: ``old`` text must occur exactly once in ui.js -- if the shipped
#: spelling moves, the splice site check fails instead of the pin
#: silently losing its target.
_BEARER_REVERTS = {
    "harden-parse": (
        "    const root = new window.DOMParser().parseFromString(html, "
        "'text/html').body;\n    // Interactive controls:",
        "    const template = document.createElement('template');\n"
        "    template.innerHTML = html;\n"
        "    const root = template.content;\n"
        "    // Interactive controls:",
    ),
    "process-parse": (
        "    const root = new window.DOMParser().parseFromString(html, "
        "'text/html').body;\n\n"
        "    for (const paragraph of [...root.querySelectorAll('p')]) {",
        "    const template = document.createElement('template');\n"
        "    template.innerHTML = html;\n"
        "    const root = template.content;\n\n"
        "    for (const paragraph of [...root.querySelectorAll('p')]) {",
    ),
    "image-swap": (
        "        paragraph.parentNode.replaceChild(wrapper, paragraph);",
        "        paragraph.replaceWith(wrapper);",
    ),
}

_BEARER_REVERT_FINDINGS = {
    "harden-parse": [
        "template.innerHTML assignment returned",
        "hardenSanitizedMarkdown no longer parses via DOMParser",
    ],
    "process-parse": [
        "template.innerHTML assignment returned",
        "processSpecialMarkdown no longer parses via DOMParser",
    ],
    "image-swap": [
        "generated-image swap is no longer parentNode.replaceChild",
        "generated-image swap calls Node.replaceWith",
    ],
}


@pytest.mark.parametrize("change", sorted(_BEARER_REVERTS))
def test_parse_boundary_pins_reject_each_exact_bearer_revert(change):
    """Mutation rejection: the pins above are not vacuous.

    Splice the exact revert of each fix hunk back into a copy of the
    shipped source and the pins must report exactly the finding that
    hunk's removal stands in for. A pin that stays green here would stay
    green on a real revert too -- which is how the pre-fix sinks shipped.
    """
    old, new = _BEARER_REVERTS[change]
    text = _ui_js()
    assert text.count(old) == 1, f"{change}: splice site moved"
    reverted = text.replace(old, new, 1)
    assert reverted != text
    assert (
        markdown_parse_boundary_violations(reverted)
        == _BEARER_REVERT_FINDINGS[change]
    )


def test_ui_js_innerhtml_writes_are_only_the_safe_set_html_boundary():
    """The untrusted-string-to-sink sweep, frozen: only safeSetHTML
    writes markup into an element -- sanitized and failing closed to
    text, pinned by test_safe_set_html_fails_closed_without_dompurify --
    and every other ``innerHTML`` assignment in ui.js blanks its element
    to ``''``.

    A new direct write -- e.g. the ``template.innerHTML = html``
    fragment writes removed for alerts 9655/9656 -- shows up here as an
    unexpected write even if it is spelled in a function no other pin
    looks at, so this is the file-wide half of the two pins above.
    """
    ui = _strip_js_comments(_ui_js())
    writes = [
        " ".join(m.group(0).split()) for m in _INNERHTML_WRITE_RE.finditer(ui)
    ]
    assert len(writes) >= 3, (
        f"expected the known innerHTML writes, found {writes} — "
        "the scan is not reaching the file"
    )
    safe_body = " ".join(_function_body(ui, "safeSetHTML").split())
    unexpected = [
        w
        for w in writes
        if not _BLANK_WRITE_RE.search(w) and w not in safe_body
    ]
    assert unexpected == [], unexpected
    non_blank = [w for w in writes if not _BLANK_WRITE_RE.search(w)]
    assert len(non_blank) == 1, (
        "safeSetHTML's sanitized write is no longer the only non-blank "
        f"innerHTML write in ui.js: {writes}"
    )


#: Rewriting a DOMPurify result with a regex re-opens what the sanitiser
#: closed. The set is empty and must stay empty: ``renderSnippet`` used to
#: be in it, and highlighting now runs *before* the sanitise pass. Adding
#: to it needs an argument, not a suppression comment.
REVIEWED_POST_SANITISE_REWRITERS: set[str] = set()

# NOTE: this is a textual scanner, not a parser — see the caveats on each
# piece below. It is defence-in-depth, not a hard guarantee; the vitest
# suite in tests/js/security/snippet-highlight-order.test.js, which
# exercises renderSnippet() and asserts on the DOM it produces, is the
# actual behavioural gate and cannot be fooled by the evasions noted here.
_HIGHLIGHT_REWRITE_RE = re.compile(r"html\s*=\s*highlightTerms\(html")
# .search() takes the FIRST textual occurrence of "DOMPurify.sanitize(" as
# *the* sanitise call. An aliased call (e.g. ``const purify =
# window.DOMPurify; ... purify.sanitize(html)``) is invisible to this
# regex, and a later, never-executed "DOMPurify.sanitize(" decoy (even
# inside a comment) would then be taken as the real call — masking a
# revert that keeps the actual (aliased) sanitise call ahead of the
# highlight call.
_SANITIZE_CALL_RE = re.compile(r"DOMPurify\.sanitize\(")


def find_post_sanitise_rewrites(text: str) -> bool:
    """Does a sanitised value get regex-rewritten *after* it is sanitised?

    Order-aware on purpose. Both halves — a ``DOMPurify.sanitize`` call
    and a ``html = highlightTerms(html…)`` rewrite — are present in the
    fixed code too; what makes them safe is that the rewrite runs first.
    A scanner that only asked "are both present?" would keep reporting
    the file after the fix and could never tell the two orders apart.
    """
    sanitize = _SANITIZE_CALL_RE.search(text)
    if not sanitize:
        return False
    return any(
        m.start() > sanitize.start()
        for m in _HIGHLIGHT_REWRITE_RE.finditer(text)
    )


def _render_snippet_body(text: str) -> str:
    """The body of ``renderSnippet``, up to its column-0 closing brace.

    Naive on purpose, and naive in a specific way: it stops at the FIRST
    ``\\n}`` at column 0 after the function keyword, so a top-level ``}``
    inside e.g. a column-0 template literal would truncate the body early.
    No such literal exists in this function today.
    """
    start = text.index("function renderSnippet(")
    end = text.index("\n}", start)
    return text[start:end]


def test_post_sanitise_rewrite_scanner_flags_a_synthetic_case():
    unsafe = (
        "html = window.DOMPurify.sanitize(x);\n"
        "html = highlightTerms(html, query);\n"
    )
    assert find_post_sanitise_rewrites(unsafe) is True


def test_post_sanitise_rewrite_scanner_is_quiet_on_a_plain_sanitise():
    safe = "return window.DOMPurify.sanitize(x);\n"
    assert find_post_sanitise_rewrites(safe) is False


def test_post_sanitise_rewrite_scanner_is_quiet_on_the_safe_order():
    """The discriminating case: same two lines, swapped."""
    safe = (
        "html = highlightTerms(html, query);\n"
        "html = window.DOMPurify.sanitize(x);\n"
    )
    assert find_post_sanitise_rewrites(safe) is False


def test_post_sanitise_rewriters_are_exactly_the_reviewed_set():
    """Search snippets are highlighted *before* they are sanitised.

    ``renderSnippet`` marks up query terms with ``highlightTerms``,
    which splits tags with ``/(<[^>]*>)|([^<]+)/`` and inserts
    ``<mark class="...">`` into what it takes for text. That tag regex
    stops at the first ``>``, including one inside a quoted attribute
    value — and the HTML serialiser does not entity-encode ``>`` in
    attribute values, so a *sanitised* snippet can contain one. Where
    the two disagree, the inserted markup's own double quotes land
    inside an attribute value and terminate it, reviving markup the
    sanitiser had already neutralised. Snippets are indexed document
    text, i.e. attacker-influenceable.

    So the highlighter must run first and DOMPurify must be the last
    thing to touch the string. Both halves of the hazard still exist in
    the file; this test pins the ordering that defuses them.

    This textual scanner is defence-in-depth with known evasions, not a
    hard guarantee: it catches a plain revert (moving the sanitise call
    back in front of the highlight call), but not an aliased sanitise
    call paired with a trailing decoy — see the caveats on
    ``_SANITIZE_CALL_RE`` and the tail-guard below. The vitest suite in
    tests/js/security/snippet-highlight-order.test.js is the actual
    behavioural gate: it exercises renderSnippet() and asserts on the DOM
    it produces, so it cannot be fooled by aliasing or decoys.
    """
    found = {
        rel for rel, text in _js_sources() if find_post_sanitise_rewrites(text)
    }
    assert found == REVIEWED_POST_SANITISE_REWRITERS

    text = (STATIC_JS / "components" / "semantic_search.js").read_text(
        encoding="utf-8"
    )
    # Floor: an empty census must mean "no post-sanitise rewriter left",
    # not "the walk reached nothing". Both halves of the hazard are still
    # here, so the scanner had something real to decide about.
    assert "/(<[^>]*>)|([^<]+)/g" in text
    assert '<mark class="ldr-search-highlight">' in text
    assert _HIGHLIGHT_REWRITE_RE.search(text)
    assert _SANITIZE_CALL_RE.search(text)

    # The ordering itself, inside renderSnippet.
    body = _render_snippet_body(text)
    highlight = _HIGHLIGHT_REWRITE_RE.search(body)
    sanitize = _SANITIZE_CALL_RE.search(body)
    assert highlight and sanitize, body
    assert highlight.start() < sanitize.start(), (
        "renderSnippet highlights AFTER sanitising again"
    )
    # ...and nothing rewrites the sanitised string afterwards. Matches
    # both a plain reassignment (``html = ...``, excluding the ``==``
    # comparison operator) and a compound one (``html += ...``), which a
    # bare ``=[^=]`` pattern would miss.
    tail = body[sanitize.end() :]
    assert not re.search(r"\bhtml\s*(?:\+=|=[^=])", tail), tail

    # With the sanitise pass last, the allow-lists are what keep the
    # highlight alive. Pinned here rather than in the vitest suite: under
    # happy-dom, DOMPurify only inspects the first top-level node, so the
    # browser-side tests cannot observe an allow-list change at all.
    tags = re.search(r"ALLOWED_TAGS:\s*\[([^]]*)]", text)
    assert tags and "'mark'" in tags.group(1), tags
    attrs = re.search(r"ALLOWED_ATTR:\s*\[([^]]*)]", text)
    assert attrs and "'class'" in attrs.group(1), attrs


def test_snippet_sanitiser_allows_no_event_handler_attributes():
    """Whatever else, the snippet allow-list must stay minimal."""
    text = (STATIC_JS / "components" / "semantic_search.js").read_text(
        encoding="utf-8"
    )
    allowed = re.search(r"ALLOWED_ATTR:\s*\[([^]]*)]", text)
    assert allowed, "renderSnippet lost its ALLOWED_ATTR list"
    names = set(re.findall(r"'([^']+)'", allowed.group(1)))
    assert names == {"href", "title", "class"}, names
    assert "ALLOW_DATA_ATTR: false" in text


def test_safe_set_html_fails_closed_without_dompurify():
    """``safeSetHTML`` must fail CLOSED when no sanitizer is available.

    The no-DOMPurify branch used to assign ``element.innerHTML = html``
    directly (unsanitised) on the theory that callers only pass
    controlled content -- making the safety of every call site, present
    and future, depend on a comment.

    A prior version of this test pinned that fix to the exact source line
    it landed as (``if (typeof DOMPurify !== 'undefined') {`` /
    ``element.innerHTML = DOMPurify.sanitize(html);``). A later,
    behaviour-preserving refactor routed the same guarded write through
    ``window.sanitizeHtml`` (security/xss-protection.js) instead of a
    bare ``DOMPurify.sanitize`` call -- so it runs the same
    ``sanitizeStable()`` fixpoint loop under ``SANITIZE_CONFIG`` as
    ``safeSetInnerHTML`` -- and that exact-line assertion started failing
    on code that was, if anything, more correct than before. That
    brittleness is exactly the bug: pinning an incidental spelling
    instead of the invariant that spelling was standing in for.

    This asserts the invariant directly instead: there is exactly one
    ``innerHTML`` write in the function, it only executes inside a
    guard that checks some sanitizer function is actually available, the
    value assigned there is that same sanitizer's OWN output (never raw
    ``html``), and a non-HTML (``textContent``) fallback exists for when
    the guard is false.
    """
    body = _ui_js().split("function safeSetHTML(element, html) {")[1]
    body = _strip_js_comments(body.split("\nfunction ")[0])
    assert "DOMPurify?.isSupported === true" in body

    # No second, unguarded write -- the guarded one below is the only path
    # from `html` to `innerHTML`.
    assert body.count("element.innerHTML") == 1

    guard = re.search(
        r"if\s*\([^{}]*?typeof\s+([\w.]*sanitize\w*)\s*===\s*'function'\s*\)\s*\{"
        r"(?P<block>.*?)\n    \}",
        body,
        re.IGNORECASE | re.DOTALL,
    )
    assert guard, "safeSetHTML has no sanitizer-availability guard"
    sanitizer_name = guard.group(1)
    block = guard["block"]

    # The guarded write sanitizes through the checked function itself,
    # not through some other name and not through raw `html`. An optional
    # trailing options object (e.g. `{ SAFE_FOR_TEMPLATES: false }`) is
    # permitted -- the invariant is that `html` is the sanitizer's first
    # and only *value* argument, not that no options are ever passed. A
    # bare `element.innerHTML = html` (no call at all) still fails this,
    # as does routing through any other name.
    #
    # Two loopholes the permissive options clause used to leave open, now
    # closed. (1) The statement is anchored on a trailing `;`, so
    # `sanitize(html, {...}) + html` -- sanitized output concatenated with
    # the raw value -- no longer satisfies it. (2) The options object may
    # not re-admit what the sanitizer exists to strip: `ADD_TAGS` /
    # `ADD_ATTR` turn the call back into a pass-through for exactly the
    # `<script>`/`on*` shapes this file is about, so an options object
    # mentioning either is rejected rather than waved through as "just
    # config".
    assert re.search(
        r"element\.innerHTML\s*=\s*"
        + re.escape(sanitizer_name)
        + r"\(html(?:\s*,\s*\{(?![^{}]*\bADD_(?:TAGS|ATTR)\b)[^{}]*\})?\)"
        r"\s*;",
        block,
    ), (
        f"guarded innerHTML write does not sanitize through {sanitizer_name}(html)"
    )

    # Outside the guard -- i.e. when the sanitizer is unavailable -- the
    # function falls back to text, never to raw HTML.
    after_guard = body[guard.end() :]
    assert "element.innerHTML" not in after_guard
    assert "element.textContent" in after_guard


# ---------------------------------------------------------------------
# Anti-tabnabbing
# ---------------------------------------------------------------------

_BLANK_ANCHOR = re.compile(
    r"<a\b[^>]*?target=[\"']_blank[\"'][^>]*?>", re.S | re.I
)
_HREF = re.compile(r"href=\"([^\"]*)\"", re.I)


def blank_anchors_without_rel(text: str) -> list[str]:
    """Cross-origin ``target=_blank`` anchors that carry no ``rel``."""
    out = []
    for tag in _BLANK_ANCHOR.findall(text):
        if "rel=" in tag.lower():
            continue
        href = _HREF.search(tag)
        target = href.group(1) if href else ""
        # Relative / same-origin hrefs cannot reach window.opener.
        if target.startswith(("/", "#", "${", "{{")) or not target:
            continue
        out.append(" ".join(tag.split())[:90])
    return out


def test_tabnabbing_scanner_flags_a_cross_origin_blank_anchor():
    unsafe = '<a href="https://evil.example" target="_blank">x</a>'
    assert blank_anchors_without_rel(unsafe) == [
        '<a href="https://evil.example" target="_blank">'
    ]


def test_tabnabbing_scanner_is_quiet_on_same_origin_and_on_rel():
    safe = (
        '<a href="/results/1" target="_blank">x</a>'
        '<a href="https://ok.example" target="_blank" '
        'rel="noopener noreferrer">y</a>'
    )
    assert blank_anchors_without_rel(safe) == []


def test_no_cross_origin_blank_anchor_ships_without_noopener():
    offenders, anchors = [], 0
    sources = list(_js_sources()) + [
        (
            path.relative_to(TEMPLATES).as_posix(),
            path.read_text(encoding="utf-8"),
        )
        for path in sorted(TEMPLATES.rglob("*.html"))
    ]
    for rel, text in sources:
        anchors += len(_BLANK_ANCHOR.findall(text))
        offenders += [
            f"{rel}: {tag}" for tag in blank_anchors_without_rel(text)
        ]
    assert anchors >= 15, (
        f"expected the known target=_blank anchors, found {anchors}"
    )
    assert offenders == []


def test_dompurify_tabnabbing_hook_registration_is_lazy_and_idempotent():
    """Every string sanitizer reaches the shared, clobber-safe lazy hook."""
    text = _strip_js_comments(
        (STATIC_JS / "security" / "xss-protection.js").read_text(
            encoding="utf-8"
        )
    )
    assert "const _hookedPurifiers = new WeakSet()" in text
    assert "_hookedPurifiers.has(purifier)" in text
    assert "_hookedPurifiers.add(purifier)" in text
    assert (
        "purifier.addHook('afterSanitizeAttributes', hardenLinkTarget)" in text
    )
    assert "ensureTabnabbingHook: _ensureTabnabbingHook" in text
    assert "ensureDOMPurifyHooks: _ensureTabnabbingHook" in text

    hook = text.split("function hardenLinkTarget(node) {", 1)[1]
    hook = hook.split("\n    function ", 1)[0]
    assert not re.search(r"\bnode\s*(\.|\[)", hook), hook
    for accessor in ("getTagName", "getAttr", "setAttr"):
        assert f"api.{accessor}.call(node" in hook

    stable = text.split("function sanitizeStable(dirty, config) {", 1)[1]
    stable = stable.split("\n    function ", 1)[0]
    assert stable.index("_ensureTabnabbingHook();") < stable.index(
        "DOMPurify.sanitize("
    )
    assert "if (!hasDOMPurify())" in stable
    assert "return escapeHtml(dirty);" in stable
    assert "sanitizeStable(contentString, SANITIZE_CONFIG)" in text
    assert "return sanitizeStable(dirty, finalConfig);" in text

    ui = _strip_js_comments(_ui_js())
    body = _render_markdown_body(ui)
    assert "sanitizeStable(html, MARKDOWN_SANITIZE_CONFIG)" in body
    allowed = ui.split("const MARKDOWN_ALLOWED_ATTR = [", 1)[1].split("];", 1)[
        0
    ]
    assert "'target', 'rel'" in allowed


def _strip_js_comments(text: str) -> str:
    """Drop ``/* ... */`` blocks and whole-line ``//`` comments.

    Naive: it does not track string or regex literals, so it only removes
    comments that start a line (after indentation) and block comments.
    That is enough to stop a commented-out call satisfying a pin.
    """
    text = re.sub(r"/\*.*?\*/", "", text, flags=re.DOTALL)
    return re.sub(r"(?m)^[ \t]*//.*$", "", text)


def _render_markdown_body(text: str) -> str:
    """The body of ``renderMarkdown``, up to its column-0 closing brace."""
    start = text.index("function renderMarkdown(")
    end = text.index("\n}", start)
    return text[start:end]


# ---------------------------------------------------------------------
# Stored XSS through a served file: filename -> Content-Type
# ---------------------------------------------------------------------

_MEDIA_TYPE = re.compile(r"media_type\s*=\s*([^,\n]+)")


def _trim_argument(value: str) -> str:
    """Drop the call's own trailing ``)`` from a captured argument."""
    value = value.strip()
    while value.endswith(")") and value.count(")") > value.count("("):
        value = value[:-1].strip()
    return value


def media_type_arguments(text: str) -> list[str]:
    return [_trim_argument(v) for v in _MEDIA_TYPE.findall(text)]


def dynamic_media_types(text: str) -> list[str]:
    """``media_type=`` arguments that are not string literals."""
    return [
        value
        for value in media_type_arguments(text)
        if not value.startswith(('"', "'"))
    ]


def test_media_type_scanner_flags_a_guessed_content_type():
    for constructor in ("Response", "in_memory_range_response"):
        unsafe = (
            f"return {constructor}(body, media_type=guess_type(filename)[0])\n"
        )
        assert dynamic_media_types(unsafe) == ["guess_type(filename)[0]"]


def test_media_type_scanner_is_quiet_on_a_literal():
    safe = 'return Response(body, media_type="application/pdf")\n'
    assert dynamic_media_types(safe) == []


def test_no_served_content_type_is_derived_from_a_filename():
    """A user-named upload must not be able to choose ``text/html``."""
    literals, dynamic = 0, {}
    for path in sorted(SRC.rglob("*.py")):
        text = path.read_text(encoding="utf-8")
        found = media_type_arguments(text)
        literals += sum(1 for v in found if v.startswith(('"', "'")))
        loose = dynamic_media_types(text)
        if loose:
            dynamic[path.relative_to(SRC).as_posix()] = loose
    assert literals >= 5, (
        f"expected the known media_type= call sites, found {literals}"
    )
    # The export router uses a closed format->mimetype mapping. The range
    # helper forwards its caller's media type; this same census checks those
    # callers, including the library route's literal application/pdf.
    assert dynamic == {
        "web/routers/research.py": ["mimetype"],
        "web/utils/range_response.py": ["media_type"],
    }, dynamic


def test_no_module_guesses_a_content_type_from_a_path():
    offenders = [
        path.relative_to(SRC).as_posix()
        for path in sorted(SRC.rglob("*.py"))
        if re.search(
            r"\bmimetypes\.|guess_type\(", path.read_text(encoding="utf-8")
        )
    ]
    assert offenders == []


def test_export_mimetypes_are_a_closed_set_of_non_html_types():
    """The one dynamic ``media_type`` resolves to a fixed table."""
    text = (SRC / "web" / "services" / "research_service.py").read_text(
        encoding="utf-8"
    )
    assert "return result.content, result.filename, result.mimetype" in text
    types = set()
    for path in sorted((SRC / "exporters").glob("*.py")):
        body = path.read_text(encoding="utf-8")
        for block in re.findall(
            r"def mimetype\(self\)[^\n]*\n(?:[^\n]*\n){0,4}", body
        ):
            types |= set(re.findall(r'return\s+"([^"]+)"', block))
    assert len(types) >= 4, f"exporter mimetype table not found: {types}"
    assert not any("html" in value for value in sorted(types)), sorted(types)


def test_html_responses_never_interpolate_request_data():
    """Every ``text/html`` body outside Jinja is a fixed string."""
    calls, dynamic = 0, []
    for path in sorted(ROUTERS.rglob("*.py")):
        text = path.read_text(encoding="utf-8")
        for match in re.finditer(r"HTMLResponse\(\s*([^\n]*)", text):
            arg = match.group(1).strip()
            calls += 1
            if not arg.startswith(('"', "'")):
                dynamic.append(f"{path.name}: {arg[:60]}")
    assert calls >= 5, f"expected the known HTMLResponse sites, got {calls}"
    # The single non-literal is library.py's `_serve_pdf._error(message)`,
    # a nested helper the `/api/` PDF route's split introduced so the page
    # route can answer text/html while its `/api/` sibling keeps JSON. The
    # regex sees the parameter name and cannot see what is passed to it;
    # `test_the_one_dynamic_html_body_is_only_ever_a_fixed_string` below
    # resolves that by AST and is the assertion that actually holds the
    # line here -- same shape as the `media_type` census above, which pairs
    # its one allowed dynamic value with
    # `test_export_mimetypes_are_a_closed_set_of_non_html_types`.
    assert dynamic == ["library.py: message, status_code=404)"], dynamic


def test_the_one_dynamic_html_body_is_only_ever_a_fixed_string():
    """Resolve the one dynamic ``HTMLResponse`` argument to literals.

    ``_serve_pdf`` builds its 404 through ``_error(message)`` so the page
    route and the ``/api/`` route can share one lookup and differ only in
    the error shape. That makes the ``HTMLResponse`` argument a *name*, so
    the census above cannot clear it. Here it is cleared properly: every
    call to ``_error`` anywhere in the module must pass exactly one
    positional string literal, and ``_error`` must take exactly that one
    parameter -- so nothing derived from the request can reach the HTML
    body. An f-string or a ``document.title`` argument fails this.
    """
    module = ast.parse(
        (ROUTERS / "library.py").read_text(encoding="utf-8"), "library.py"
    )
    helpers = [
        node
        for node in ast.walk(module)
        if isinstance(node, ast.FunctionDef) and node.name == "_error"
    ]
    assert len(helpers) == 1, (
        "expected exactly one `_error` helper in library.py; the census "
        f"exemption above is written for that one site, found {len(helpers)}"
    )
    args = helpers[0].args
    assert (
        [a.arg for a in args.args] == ["message"]
        and not args.posonlyargs
        and not args.kwonlyargs
        and not args.vararg
        and not args.kwarg
    ), "`_error`'s signature changed; re-derive the exemption"

    arguments = []
    for node in ast.walk(module):
        if (
            isinstance(node, ast.Call)
            and isinstance(node.func, ast.Name)
            and node.func.id == "_error"
        ):
            assert not node.keywords and len(node.args) == 1, ast.dump(node)
            arguments.append(node.args[0])

    assert len(arguments) >= 2, (
        f"only {len(arguments)} `_error(...)` call sites found; the scan "
        "has stopped matching the source"
    )
    non_literal = [
        ast.dump(a)
        for a in arguments
        if not (isinstance(a, ast.Constant) and isinstance(a.value, str))
    ]
    assert not non_literal, (
        "`_error` is called with a non-literal, so the text/html 404 body "
        "in library.py may now interpolate request-derived data:\n"
        + "\n".join(non_literal)
    )


def test_nosniff_is_set_on_every_response():
    """Without it a mislabelled download can still be sniffed as HTML."""
    app = (SRC / "web" / "fastapi_app.py").read_text(encoding="utf-8")
    assert '(b"x-content-type-options", b"nosniff")' in app


@pytest.mark.parametrize(
    "payload", [ATTR_BREAKOUT, TAG_BREAKOUT], ids=["attribute", "tag"]
)
def test_payload_constants_exercise_distinct_breakout_shapes(payload):
    """Guard the constants the census reasons about.

    ``ATTR_BREAKOUT`` must need only a double quote (an escaper that
    covers ``& < >`` does not stop it); ``TAG_BREAKOUT`` must need an
    angle bracket (one that does stop it).
    """
    if payload is ATTR_BREAKOUT:
        assert '"' in payload
        assert "<" not in payload and ">" not in payload
    else:
        assert "<" in payload and '"' not in payload