CVE-2026-59930: Mistune Heading IDs Use Predictable `toc_N` Vulnerability

MODERATE
Advisory Identifier: GHSA-2hm2-hc3v-44h9
CVSS 4.3
CWE-1284 CWE-345
Published
Advisory Summary

CVE-2026-59930 is a MODERATE (CVSS 4.3) heading ids use predictable `toc_n` vulnerability (CWE-1284: Improper Validation of Specified Quantity in Input) affecting Mistune libraries in the PyPI ecosystem. The issue involves heading ids use predictable `toc_n` numbering with no slugification, allowing collision with attacker-controlled `id="toc_n"` content. Remediation is available by upgrading affected packages to version 3.3.0.

CVE-2026-59930 at a Glance

CVE Identifier CVE-2026-59930
GHSA Identifier GHSA-2hm2-hc3v-44h9
Severity MODERATE
CVSS v3.1 Base Score 4.3
CWE Classification CWE-1284: Improper Validation of Specified Quantity in Input
Affected Product Mistune
Package Ecosystem PyPI
Published Date
Last Updated

Security Impact

CVSS: 4.3

The security impact metrics below are parsed directly from the CVSS v3.1 vector string (CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:L/A:N).

Attack Vector Network (AV:N)
Attack Complexity Low (AC:L)
Privileges Required None (PR:N)
User Interaction Required (UI:R)
Scope Unchanged (S:U)
Confidentiality None (C:N)
Integrity Low (I:L)
Availability None (A:N)

How to Fix CVE-2026-59930

To remediate this vulnerability, upgrade all affected Mistune dependencies to a patched release. Both direct and transitive dependencies should be checked, as frameworks or security libraries may pull in vulnerable versions transitively.

mistune fixed: 3.3.0
pip install mistune>=3.3.0
Verify Direct and Transitive Dependencies

Run the following command in your project directory to verify that all resolved dependencies use the patched release:

pip show mistune

How to Check if You Are Affected

To determine whether your Python environment is affected by CVE-2026-59930, inspect your installed packages using pip:

pip show mistune

Analyze the terminal output to locate any version of Mistune in your dependency tree. If any resolved version matches the vulnerable ranges listed in the table below (for example, versions earlier than 3.3.0), your application is affected.

Note: The pip show mistune command checks currently installed packages in your active Python environment.

Technical Details

Vulnerability Mechanism & Technical Analysis

This vulnerability is classified under CWE-1284: Improper Validation of Specified Quantity in Input, where the product receives input that is expected to specify a quantity (such as size or length), but it does not validate or incorrectly validates that the quantity has the required properties. In Mistune, software state validation or input boundaries are circumvented during processing. Review the official source advisory statement below for specific affected components, classes, and reproduction details.

Source Advisory Statement

## Summary **Type:** Predictable identifier generation. The `toc` plugin and `TableOfContents` directive both default to generating heading IDs of the form `toc_1`, `toc_2`, `toc_3`, ... with no input-derived component. An attacker who can place a heading anywhere in the document can predict which `toc_N` ID it will receive, and can inject HTML elsewhere (in a non-heading context) that uses the same `id="toc_N"` to either (a) shadow the legitimate heading anchor, breaking same-page navigation, or (b) collide with CSS or JavaScript that targets `#toc_N` selectors, redirecting click handlers and styling to attacker-chosen content. **File:** `src/mistune/toc.py` line 36-37 (`heading_id = lambda token, index: "toc_" + str(index + 1)`); `src/mistune/directives/toc.py` line 33 (same default). **Root cause:** the default `heading_id` callback ignores the heading's text content and uses only the headings's order in the document. Two documents rendered together (or one document with attacker-influenced headings spliced into trusted content) produce overlapping `toc_N` IDs. Because `id` attribute uniqueness is required by HTML, browsers behaviour on duplicate IDs is undefined; `document.getElementById('toc_1')` returns the first match, `getElementsByTagName + querySelector` semantics differ across paths, and CSS rules targeting `#toc_1` apply to whichever element matches first in tree order. ## Affected Code **File:** `src/mistune/toc.py`, lines 33-39. ```python def add_toc_hook(md, min_level=1, max_level=3, heading_id=None): if heading_id is None: def heading_id(token, index): return "toc_" + str(index + 1) # <-- BUG: index-only ID, no slug derived from heading text ``` **File:** `src/mistune/directives/toc.py`, lines 32-33. ```python class TableOfContents(DirectivePlugin): def __init__(self, min_level=1, max_level=3): # ... def generate_heading_id(self, token, index): return "toc_" + str(index + 1) # <-- BUG: same predictable scheme ``` **Why it's wrong:** the standard markdown-engine convention (used by GitHub-flavoured Markdown, Sphinx, MkDocs, pandoc, every modern markdown renderer in production) is to slugify the heading TEXT for the ID — `<h1 id="introduction">Introduction</h1>` — with a numeric suffix appended only when slug collisions occur. mistune's default punts the slugification entirely and produces purely positional IDs that an attacker can predict in O(1). The downstream impacts: - Same-page links with `[click](#toc_1)` go to whichever element with `id="toc_1"` appears first in tree order. If the attacker can land any HTML element with `id="toc_1"` before the real heading (via inline_html with `escape=False`, via the include-directive HTML branch, via attacker-supplied content earlier in the document), navigation is hijacked. - CSS rules targeting `#toc_1` apply to the wrong element. - JavaScript bound to `document.getElementById('toc_1')` operates on the wrong element. - The TOC's own `<a href="#toc_1">` link in the rendered TOC list points to whichever element wins the duplicate-ID race. ## Exploit Chain 1. Application uses mistune with `add_toc_hook(md)` or `TableOfContents` directive enabled (the documented setup for sites with TOC support). 2. Application renders an attacker-supplied document, or splices attacker content into a trusted document. With `escape=False` (or via the include-directive `.html` branch covered by my prior advisory), the attacker can place `<a id="toc_1">...</a>` anywhere in the document. 3. mistune assigns `id="toc_1"` to the first heading. Now there are two elements with `id="toc_1"` in the page. 4. The rendered TOC contains `<a href="#toc_1">First heading</a>`. Clicking it navigates to whichever element with `id="toc_1"` appears first in tree order. If the attacker placed their `<a id="toc_1">` BEFORE the heading, navigation is hijacked. 5. Same-page CSS / JS / aria-described references to `#toc_1` similarly redirect. ## Security Impact **Severity:** sec-low. Not a direct XSS or RCE; the issue is identifier confusion that enables UI-redirection / navigation-hijack attacks. The realistic attacker capability is "make an internal anchor link go to attacker content instead of the real heading", or "make a CSS selector apply to attacker content", or "break aria/screen-reader associations". **Attacker capability:** with the ability to plant any HTML element with `id="toc_N"` in the document, hijack `<a href="#toc_N">` navigation and any CSS/JS targeting that ID. With `escape=False`, this is straightforward. With `escape=True`, the attacker needs another vector to land a raw `id` attribute (one of the include-directive branches, a sibling tooling pipeline that lets HTML through, etc.). **Preconditions:** application uses TOC + the default `heading_id` callback. If the application provides its own `heading_id` (e.g., one based on slugified heading text, with collision suffixes), this finding does not apply. **Differential:** PoC-verified against mistune@3.2.1: ```python import mistune from mistune.directives import RSTDirective, TableOfContents md = mistune.create_markdown(plugins=[RSTDirective([TableOfContents()])]) print(md(''' .. toc:: # Heading 1 # Heading 2 ''')) # Output (note: id="toc_1" / id="toc_2", purely positional): # <details class="toc" open> # <summary>Table of Contents</summary> # <ul> # <li><a href="#toc_1">Heading 1</a></li> # <li><a href="#toc_2">Heading 2</a></li> # </ul> # </details> # <h1 id="toc_1">Heading 1</h1> # <h1 id="toc_2">Heading 2</h1> ``` The patched build (with the suggested fix below) produces text-derived slugs like `id="heading-1"` and `id="heading-2"`, which are tied to content rather than position. ## Suggested Fix Default to slugifying the heading text: ```diff --- a/src/mistune/toc.py +++ b/src/mistune/toc.py @@ -33,9 +33,18 @@ def add_toc_hook(md, min_level=1, max_level=3, heading_id=None): if heading_id is None: + import re + _slug_re = re.compile(r"[^a-z0-9]+") + seen = {} def heading_id(token, index): - return "toc_" + str(index + 1) + text = striptags(md.renderer(md.inline(token["text"], {}), BlockState())) + slug = _slug_re.sub("-", text.lower()).strip("-") or "section" + n = seen.get(slug, 0) + seen[slug] = n + 1 + return slug if n == 0 else f"{slug}-{n}" ``` Same change applies to `src/mistune/directives/toc.py:33`. Existing applications that have hardcoded `#toc_N` anchors will break; document the migration in the changelog and consider providing an opt-out flag for the legacy behaviour. Add a regression test that asserts heading IDs are slug-derived, not position-derived, and that collisions get a `-N` suffix.

CVE-2026-59930 Affected Mistune Versions

1 component(s)
Fixed Versions:
3.3.0
Product / Package Ecosystem Affected Versions Fixed Version
mistune
PyPI
< 3.3.0
3.3.0

References

Frequently Asked Questions

What is CVE-2026-59930?
CVE-2026-59930 is a security vulnerability in Mistune involving heading IDs use predictable `toc_N` numbering with no slugification, allowing collision with attacker-controlled `id="toc_N"` content under CWE-1284: Improper Validation of Specified Quantity in Input.
Which Mistune versions are affected?
Affected versions include releases prior to 3.3.0 across affected packages: mistune.
What version fixes CVE-2026-59930?
Upgrading to 3.3.0 (or the latest patched release for your respective branch) resolves the vulnerability.
Is mistune affected?
Yes, mistune is affected in releases prior to 3.3.0. Upgrade your dependency to 3.3.0 or later.
What is the CVSS score of CVE-2026-59930?
CVE-2026-59930 has a CVSS v3.1 base score of 4.3 (MODERATE) with vector string CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:L/A:N.
What CWE is associated with CVE-2026-59930?
CVE-2026-59930 is classified under CWE-1284: Improper Validation of Specified Quantity in Input (The product receives input that is expected to specify a quantity (such as size or length), but it does not validate or incorrectly validates that the quantity has the required properties.).
How can I check PyPI dependencies for CVE-2026-59930?
Run the dependency tree command: 'pip show mistune'. This command lists direct and transitive dependencies in your build configuration so you can verify if a vulnerable version is resolved.
Machine-readable OSV JSON OSV v1.5 Schema
Normalized schema output
{
  "schema_version" : "1.4.0",
  "id" : "GHSA-2hm2-hc3v-44h9",
  "modified" : "2026-07-20T21:35:12Z",
  "published" : "2026-07-20T21:35:11Z",
  "aliases" : [ "CVE-2026-59930" ],
  "summary" : "Mistune toc / TableOfContents directive: heading IDs use predictable `toc_N` numbering with no slugification, allowing collision with attacker-controlled `id=\"toc_N\"` content",
  "details" : "## Summary\n\n**Type:** Predictable identifier generation. The `toc` plugin and `TableOfContents` directive both default to generating heading IDs of the form `toc_1`, `toc_2`, `toc_3`, ... with no input-derived component. An attacker who can place a heading anywhere in the document can predict which `toc_N` ID it will receive, and can inject HTML elsewhere (in a non-heading context) that uses the same `id=\"toc_N\"` to either (a) shadow the legitimate heading anchor, breaking same-page navigation, or (b) collide with CSS or JavaScript that targets `#toc_N` selectors, redirecting click handlers and styling to attacker-chosen content.\n**File:** `src/mistune/toc.py` line 36-37 (`heading_id = lambda token, index: \"toc_\" + str(index + 1)`); `src/mistune/directives/toc.py` line 33 (same default).\n**Root cause:** the default `heading_id` callback ignores the heading's text content and uses only the headings's order in the document. Two documents rendered together (or one document with attacker-influenced headings spliced into trusted content) produce overlapping `toc_N` IDs. Because `id` attribute uniqueness is required by HTML, browsers behaviour on duplicate IDs is undefined; `document.getElementById('toc_1')` returns the first match, `getElementsByTagName + querySelector` semantics differ across paths, and CSS rules targeting `#toc_1` apply to whichever element matches first in tree order.\n\n## Affected Code\n\n**File:** `src/mistune/toc.py`, lines 33-39.\n\n```python\ndef add_toc_hook(md, min_level=1, max_level=3, heading_id=None):\n    if heading_id is None:\n        def heading_id(token, index):\n            return \"toc_\" + str(index + 1)               # <-- BUG: index-only ID, no slug derived from heading text\n```\n\n**File:** `src/mistune/directives/toc.py`, lines 32-33.\n\n```python\nclass TableOfContents(DirectivePlugin):\n    def __init__(self, min_level=1, max_level=3):\n        # ...\n\n    def generate_heading_id(self, token, index):\n        return \"toc_\" + str(index + 1)                   # <-- BUG: same predictable scheme\n```\n\n**Why it's wrong:** the standard markdown-engine convention (used by GitHub-flavoured Markdown, Sphinx, MkDocs, pandoc, every modern markdown renderer in production) is to slugify the heading TEXT for the ID — `<h1 id=\"introduction\">Introduction</h1>` — with a numeric suffix appended only when slug collisions occur. mistune's default punts the slugification entirely and produces purely positional IDs that an attacker can predict in O(1).\n\nThe downstream impacts:\n- Same-page links with `[click](#toc_1)` go to whichever element with `id=\"toc_1\"` appears first in tree order. If the attacker can land any HTML element with `id=\"toc_1\"` before the real heading (via inline_html with `escape=False`, via the include-directive HTML branch, via attacker-supplied content earlier in the document), navigation is hijacked.\n- CSS rules targeting `#toc_1` apply to the wrong element.\n- JavaScript bound to `document.getElementById('toc_1')` operates on the wrong element.\n- The TOC's own `<a href=\"#toc_1\">` link in the rendered TOC list points to whichever element wins the duplicate-ID race.\n\n## Exploit Chain\n\n1. Application uses mistune with `add_toc_hook(md)` or `TableOfContents` directive enabled (the documented setup for sites with TOC support).\n2. Application renders an attacker-supplied document, or splices attacker content into a trusted document. With `escape=False` (or via the include-directive `.html` branch covered by my prior advisory), the attacker can place `<a id=\"toc_1\">...</a>` anywhere in the document.\n3. mistune assigns `id=\"toc_1\"` to the first heading. Now there are two elements with `id=\"toc_1\"` in the page.\n4. The rendered TOC contains `<a href=\"#toc_1\">First heading</a>`. Clicking it navigates to whichever element with `id=\"toc_1\"` appears first in tree order. If the attacker placed their `<a id=\"toc_1\">` BEFORE the heading, navigation is hijacked.\n5. Same-page CSS / JS / aria-described references to `#toc_1` similarly redirect.\n\n## Security Impact\n\n**Severity:** sec-low. Not a direct XSS or RCE; the issue is identifier confusion that enables UI-redirection / navigation-hijack attacks. The realistic attacker capability is \"make an internal anchor link go to attacker content instead of the real heading\", or \"make a CSS selector apply to attacker content\", or \"break aria/screen-reader associations\".\n**Attacker capability:** with the ability to plant any HTML element with `id=\"toc_N\"` in the document, hijack `<a href=\"#toc_N\">` navigation and any CSS/JS targeting that ID. With `escape=False`, this is straightforward. With `escape=True`, the attacker needs another vector to land a raw `id` attribute (one of the include-directive branches, a sibling tooling pipeline that lets HTML through, etc.).\n**Preconditions:** application uses TOC + the default `heading_id` callback. If the application provides its own `heading_id` (e.g., one based on slugified heading text, with collision suffixes), this finding does not apply.\n**Differential:** PoC-verified against mistune@3.2.1:\n\n```python\nimport mistune\nfrom mistune.directives import RSTDirective, TableOfContents\nmd = mistune.create_markdown(plugins=[RSTDirective([TableOfContents()])])\n\nprint(md('''\n.. toc::\n\n# Heading 1\n\n# Heading 2\n'''))\n\n# Output (note: id=\"toc_1\" / id=\"toc_2\", purely positional):\n# <details class=\"toc\" open>\n#   <summary>Table of Contents</summary>\n#   <ul>\n#     <li><a href=\"#toc_1\">Heading 1</a></li>\n#     <li><a href=\"#toc_2\">Heading 2</a></li>\n#   </ul>\n# </details>\n# <h1 id=\"toc_1\">Heading 1</h1>\n# <h1 id=\"toc_2\">Heading 2</h1>\n```\n\nThe patched build (with the suggested fix below) produces text-derived slugs like `id=\"heading-1\"` and `id=\"heading-2\"`, which are tied to content rather than position.\n\n## Suggested Fix\n\nDefault to slugifying the heading text:\n\n```diff\n--- a/src/mistune/toc.py\n+++ b/src/mistune/toc.py\n@@ -33,9 +33,18 @@ def add_toc_hook(md, min_level=1, max_level=3, heading_id=None):\n     if heading_id is None:\n+        import re\n+        _slug_re = re.compile(r\"[^a-z0-9]+\")\n+        seen = {}\n         def heading_id(token, index):\n-            return \"toc_\" + str(index + 1)\n+            text = striptags(md.renderer(md.inline(token[\"text\"], {}), BlockState()))\n+            slug = _slug_re.sub(\"-\", text.lower()).strip(\"-\") or \"section\"\n+            n = seen.get(slug, 0)\n+            seen[slug] = n + 1\n+            return slug if n == 0 else f\"{slug}-{n}\"\n```\n\nSame change applies to `src/mistune/directives/toc.py:33`. Existing applications that have hardcoded `#toc_N` anchors will break; document the migration in the changelog and consider providing an opt-out flag for the legacy behaviour. Add a regression test that asserts heading IDs are slug-derived, not position-derived, and that collisions get a `-N` suffix.",
  "severity" : [ {
    "type" : "CVSS_V3",
    "score" : "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:L/A:N"
  } ],
  "affected" : [ {
    "package" : {
      "ecosystem" : "PyPI",
      "name" : "mistune"
    },
    "ranges" : [ {
      "type" : "ECOSYSTEM",
      "events" : [ {
        "introduced" : "0"
      }, {
        "fixed" : "3.3.0"
      } ]
    } ]
  } ],
  "references" : [ {
    "type" : "WEB",
    "url" : "https://github.com/lepture/mistune/security/advisories/GHSA-2hm2-hc3v-44h9"
  }, {
    "type" : "ADVISORY",
    "url" : "https://nvd.nist.gov/vuln/detail/CVE-2026-59930"
  }, {
    "type" : "WEB",
    "url" : "https://github.com/lepture/mistune/commit/c4093c4742ed0d10d9332fb8edb455869b7b581b"
  }, {
    "type" : "PACKAGE",
    "url" : "https://github.com/lepture/mistune"
  }, {
    "type" : "WEB",
    "url" : "https://github.com/lepture/mistune/releases/tag/v3.3.0"
  }, {
    "type" : "WEB",
    "url" : "https://github.com/pypa/advisory-database/tree/main/vulns/mistune/PYSEC-2026-2218.yaml"
  } ],
  "database_specific" : {
    "cwe_ids" : [ "CWE-1284", "CWE-345" ],
    "severity" : "MODERATE",
    "github_reviewed" : true,
    "github_reviewed_at" : "2026-07-20T21:35:11Z",
    "nvd_published_at" : "2026-07-08T17:17:28Z"
  }
}