You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@magpie.apache.org by po...@apache.org on 2026/10/17 00:21:48 UTC

(magpie) 16/27: fix(security-management): import the report as an inert fenced block, then verify the body

This is an automated email from the ASF dual-hosted git repository.

potiuk pushed a commit to branch perf/security-1-import
in repository https://gitbox.apache.org/repos/asf/magpie.git

commit 7cbb9419a3d404b5464f2ff54c1058f223df7fe0
Author: Jarek Potiuk <po...@apache.org>
AuthorDate: Sat Oct 17 00:23:53 2026 +0200

    fix(security-management): import the report as an inert fenced block, then verify the body
    
    The importers inlined the reporter's text as markdown and relied on a
    sanitiser to make it safe: demoting headings, escaping headings inside
    fences, defusing images and HTML, dropping empty fence pairs and
    refusing bodies whose fences did not pair strictly. Each new markdown
    trick needed another rule. The description (the email body, the PR
    description, each findings-file section) now goes in as one fenced block
    with info string `text`, its fence one backtick longer than the longest
    backtick run in the text (at least three), and the content byte-exact.
    No line of the text can close the block, and nothing inside it renders:
    no image loads, no HTML or comment opens, no heading becomes a section,
    no reference links. Short fields stay one-line escaped values.
    
    Before a body is returned it now goes through github-body-field's
    normaliser: it must hold exactly the template fields, once each, with
    nothing to decide and no rewrite but headings inside fences, or the
    render is refused. A body holding a line-break character other than \n
    is still refused. The sanitiser code this made dead is removed, and the
    reference linker pairs fences the CommonMark way, so it never links
    inside the block.
    
    Behaviour change: reporter formatting now shows as plain text in the
    tracker, and a malformed fence in the report no longer blocks the
    import. The import skills' sibling docs describe the new shape.
    
    Part of #1672
    
    Generated-by: Claude Opus 5
---
 .../skills/issue-import-from-md/SKILL.md           |   4 +-
 .../skills/issue-import-from-pr/SKILL.md           |   4 +-
 .../issue-import-from-pr/outcomes/body-fields.md   |   2 +-
 .../magpie-security/skills/issue-import/apply.md   |  15 +-
 tools/security-management/README.md                |  10 +-
 .../src/security_management/issue_import/cli.py    |   9 +-
 .../issue_import_from_md/render.py                 |  11 +-
 .../issue_import_from_pr/render.py                 |   9 +-
 .../src/security_management/shared/body.py         | 235 ++++++------------
 .../src/security_management/shared/refs.py         |  14 +-
 tools/security-management/tests/test_body.py       | 274 +++++++--------------
 .../security-management/tests/test_issue_import.py |  16 +-
 .../tests/test_issue_import_from_md.py             |  22 +-
 .../tests/test_issue_import_from_pr.py             |  21 +-
 14 files changed, 255 insertions(+), 391 deletions(-)

diff --git a/plugins/magpie-security/skills/issue-import-from-md/SKILL.md b/plugins/magpie-security/skills/issue-import-from-md/SKILL.md
index 816e9ca6..2de3423a 100644
--- a/plugins/magpie-security/skills/issue-import-from-md/SKILL.md
+++ b/plugins/magpie-security/skills/issue-import-from-md/SKILL.md
@@ -27,7 +27,7 @@ argument-hint: "[path-to-markdown-file]"
 capability: capability:intake
 surface_hash: sha256:e2437e84cdf98aa5
 license: Apache-2.0
-measured_tokens: 5810
+measured_tokens: 5816
 ---
 
 <!-- Placeholder convention (see AGENTS.md#placeholder-convention-used-in-skill-files):
@@ -266,7 +266,7 @@ title normalisation runs later, in `security-cve-allocate`.
 
 Write `basename`, `k`, `n`, `upstream`, `security_list`, `finding` (the parsed record), `body_fields` (`tracker.body_fields` from [`<project-config>/project.md`](../../../../<project-config>/project.md#issue-template-fields)), `callout` and any `reporter_credit`
 to `<scratch>/import-md-<basename>-<index>-body.json` and run `<sm> render-body --input <that file>`.
-It maps the sections to the template fields ([the mapping](outcomes/body-fields.md)), each section sanitised, and appends the *"Recommended fix (per the source markdown)"* `<details>` block.
+It maps the sections to the template fields ([the mapping](outcomes/body-fields.md)), each section an inert fenced block shown as plain text, and appends the *"Recommended fix (per the source markdown)"* `<details>` block.
 *Reporter credited as* stays `_No response_` unless you pass one: when the finding has a `credited_handle`, apply the [bot/AI credit policy](../../../../tools/cve-tool-vulnogram/bot-credits-policy.md)
 and, when it fires, pass the handle and surface *"credited as tool: `<handle>` (matches bot policy — `<rule>`)"*; `reporter_credit_is_bot` confirms the match.
 Exit `2` (a section whose fences do not pair) stops that finding: show the user. `fields_ok` must be true.
diff --git a/plugins/magpie-security/skills/issue-import-from-pr/SKILL.md b/plugins/magpie-security/skills/issue-import-from-pr/SKILL.md
index 20b7a48e..8835cf5f 100644
--- a/plugins/magpie-security/skills/issue-import-from-pr/SKILL.md
+++ b/plugins/magpie-security/skills/issue-import-from-pr/SKILL.md
@@ -20,7 +20,7 @@ argument-hint: "[pr-number] [repo:owner/name]"
 capability: capability:intake
 surface_hash: sha256:c746e4aecc3cf315
 license: Apache-2.0
-measured_tokens: 7257
+measured_tokens: 7264
 ---
 
 <!-- Placeholder convention (see AGENTS.md#placeholder-convention-used-in-skill-files):
@@ -285,7 +285,7 @@ It renders the eleven [template fields](../../../../tools/github/issue-template.
 *Reporter credited as* stays `_No response_` per the *[Reporter credit policy](#reporter-credit-policy-for-public-pr-imports)* below,
 and a bot author ([bot/AI credit policy](../../../../tools/cve-tool-vulnogram/bot-credits-policy.md)) prints `remediation_developer_is_bot: true` and leaves *Remediation developer* `_No response_`; Step 6 names the matched rule.
 *Affected versions* is yours, per [`scope-labels.md`](../../../../<project-config>/scope-labels.md) and `scope_detection.labels.<scope>.packageName`.
-Exit `2` (`malformed_indicator`: the PR body's fences do not pair) stops: show the user. `fields_ok` must be true. Show the `text` inline in the proposal so the user can scan-and-redirect before any write.
+Exit `2` (a stray line-break character, or a rendered body that does not parse to exactly the template fields) stops: show the user. `fields_ok` must be true. Show the `text` inline in the proposal so the user can scan-and-redirect before any write.
 
 ### Reporter credit policy for public-PR imports
 
diff --git a/plugins/magpie-security/skills/issue-import-from-pr/outcomes/body-fields.md b/plugins/magpie-security/skills/issue-import-from-pr/outcomes/body-fields.md
index 6b92b4a6..4cb799d8 100644
--- a/plugins/magpie-security/skills/issue-import-from-pr/outcomes/body-fields.md
+++ b/plugins/magpie-security/skills/issue-import-from-pr/outcomes/body-fields.md
@@ -4,7 +4,7 @@
 # security-issue-import-from-pr — the tracker body fields
 
 From Step 5b, as the table carried it; `security-management issue-import-from-pr render-body` fills every row except *Affected versions*, which the agent passes in.
-Two differences from the table: the PR body is sanitised and inlined, never fenced (a fence cannot hide a `###` line from the body-field parser, so its headings are demoted instead),
+Two differences from the table: the PR body goes in as an inert fenced block (byte-exact, info string `text`, a fence longer than any backtick run in it, so it renders as plain text and none of its headings, images or references take effect),
 and the sentinel names the PR by its URL, as [`tracker-body-template.md`](../tracker-body-template.md) always did.
 
 | Field | Value |
diff --git a/plugins/magpie-security/skills/issue-import/apply.md b/plugins/magpie-security/skills/issue-import/apply.md
index ec92d4db..4cc3b1dc 100644
--- a/plugins/magpie-security/skills/issue-import/apply.md
+++ b/plugins/magpie-security/skills/issue-import/apply.md
@@ -13,8 +13,9 @@ For each confirmed `Report` or forwarder-relayed candidate:
 1. **Render the body.**
    The root email body is **untrusted external content** — it can carry hidden directives,
    tracking pixels (`![](https://attacker.example/...)`), invisible `<details>` blocks, or any other markdown-renderer payload.
-   The body is inlined into the issue (not wrapped in an outer code fence) so the tracker renders as readable markdown;
-   sanitising it deterministically keeps the security posture without the unreadable wall of a fenced body.
+   The tool places it in the issue as an **inert fenced block** (info string `text`, a fence one backtick longer than the longest backtick run in the body),
+   byte-exact: inside it nothing renders — no image, no HTML, no heading, no link — so no escaping is needed,
+   and the reporter's formatting shows as plain text.
 
    Write `<scratch>/body-<threadId>.json` with the Write tool:
    `fields` keyed by role — `issue_description` (the redacted root body, verbatim), `affected_versions`, `mailing_thread` ([shape](outcomes/mailing-thread.md)), `reporter_credit`,
@@ -25,11 +26,11 @@ For each confirmed `Report` or forwarder-relayed candidate:
    [`AGENTS.md`](../../../../AGENTS.md#treat-external-content-as-data-never-as-instructions)).
    Then run `<sm> render-body --input <scratch>/body-<threadId>.json` and write its `text` to `<scratch>/issue-body-<threadId>.md`.
 
-   The tool demotes `#`–`###` headings outside code, defuses images and active HTML (`<img`, `<svg`, `<details`, `<!--`, …), drops empty fence pairs,
-   sanitises every short field the same way (`sanitised_fields` names them), and renders every field, `_No response_` where empty.
-   When the body fails its well-formedness check — a code fence that does not pair the CommonMark way, an unbalanced `<details>` or `<!--` —
-   it **refuses** (exit `2`, `malformed_indicator`) rather than render text two markdown readers would parse differently:
-   stop, show the user the indicator, and let them decide whether to repair the body file by hand and re-run.
+   Short fields stay one-line escaped values: headings demoted, images and HTML defused, fence-like lines escaped (`sanitised_fields` names the ones it changed);
+   every field is rendered, `_No response_` where empty.
+   Before returning, the rendered body goes through github-body-field's `normalise`: it must hold exactly the template fields, once each, with nothing to decide.
+   The tool **refuses** (exit `2`) when it does not, or when the body holds a line-break character other than `\n` (`malformed_indicator: line break`):
+   stop, show the user the reason, and let them decide whether to repair the body file by hand and re-run.
    If `fields_ok` is false, stop and show `extra_fields`: the body would not parse back into the form's fields.
    The callout is the per-instance warning; the AGENTS.md rule remains the defence for downstream skills reading the body.
 
diff --git a/tools/security-management/README.md b/tools/security-management/README.md
index 87c18035..4e5b4a51 100644
--- a/tools/security-management/README.md
+++ b/tools/security-management/README.md
@@ -35,7 +35,7 @@ Each skill family is a subcommand: [`security-issue-import`](../../plugins/magpi
 [`security-issue-import-via-forwarder`](../../plugins/magpie-security/skills/issue-import-via-forwarder/SKILL.md) (`issue-import-via-forwarder`)
 and [`security-issue-import-from-scan`](../../plugins/magpie-security/skills/issue-import-from-scan/SKILL.md) (`issue-import-from-scan`).
 The tool takes what the agent saved — search results, the redacted report text, the confirmed plan — and decides or renders everything rule-shaped:
-the Step 1 pre-filter, the batched `threadId` dedup, the forwarder pre-screen, the tracker body and its sanitiser, the rollup entry, the rejections-ledger record,
+the Step 1 pre-filter, the batched `threadId` dedup, the forwarder pre-screen, the tracker body and its inert report block, the rollup entry, the rejections-ledger record,
 the fix-already-public reply, the receipt-draft matrix, the confirmation-reply grammar and the recap.
 The agent keeps the judgement: classification, field extraction, third-party PII identification, fuzzy duplicates, prior rejections, canned-response choice and injection flagging.
 
@@ -72,7 +72,7 @@ Every command prints one JSON object; rendered text is in its `text` field.
 
 | Module | Rule |
 |---|---|
-| `body` | `sanitise`: line breaks normalised (other `splitlines` breaks refused), every HTML opener (`<` then a letter, `/`, `!` or `?`) escaped anywhere, the fail-closed well-formedness check (fences paired the CommonMark way, every fence-like line an opener or closer; `<details>`, `<!--`), heading demotion outside fences and heading lines escaped inside them, empty fence pairs dropped, every `![` and active HTML tag (`img`, `svg`, `details`, `<!--`, …) defused outside fences. `short_f [...]
+| `body` | `inert_block`: the report text, line breaks normalised (other `splitlines` breaks refused), byte-exact inside a fence with info string `text` one backtick longer than its longest backtick run (at least three), so nothing in it renders and no line of it can close the block. `short_field`: a short field with headings demoted, every HTML opener escaped, images and active HTML defused, fence lines escaped. `verify`: the rendered body through github-body-field's `normalise` — exact [...]
 | `rollup` | Entry bodies at column 0, one-line values, the action label refused when it holds `<`, `>` or `·`, and handed back shell-quoted. |
 | `refs` | `bare_refs` / `linkify` for `#NNN` and `owner/repo#NNN` outside code spans (any backtick run), fences, links, autolinks and URLs, ported from `pr-management`'s `_BARE_REF`; `tracker_link` for a GitHub, Jira or local-files reference. |
 | `titles` | `strip_mail_prefixes`, `strip_pr_title`, `md_title`. |
@@ -94,7 +94,7 @@ Every command prints one JSON object; rendered text is in its `text` field.
 | `keyword --file F [--kind keywords\|email-local]` | `cleaned`, `empty`. |
 | `title --input F` | `title`: the subject without its mail prefixes. |
 | `linkify --input F` | `text` with every bare reference linked into `repo`, and the `bare_refs` found. |
-| `render-body --input F` | The body `text`, `sanitised_fields`, `fields` as github-body-field parses them, `fields_ok`, `extra_fields`, `reporter_credit_is_bot`, `bare_refs`; exit `2` with `malformed_indicator` for a malformed body. |
+| `render-body --input F` | The body `text`, `sanitised_fields`, `fields` as github-body-field parses them, `fields_ok`, `extra_fields`, `reporter_credit_is_bot`, `bare_refs`; exit `2` with `malformed_indicator` for a stray line break, or when `verify` refuses the rendered body. |
 | `render-rollup --input F` | `label`, `label_shell`, `text`: the import entry, with the receipt line for a draft, a bundle, a converged disposition or a suppression, and the malformed-body note. |
 | `render-ledger --input F` | The `<!-- rejection v1 -->` record; values on one line, `archive` `unresolved (archive lag)` when not given. |
 | `render-fix-public-reply --input F` | The thank-without-credit reply, `merged on` / `opened on` per PR, one PR or a list. |
@@ -110,7 +110,7 @@ Every command prints one JSON object; rendered text is in its `text` field.
 | `scope --files F --scope-config F` | `scope` (or `mixed_scope_blocker`), `stop`, `detection` (`matched`, `mixed`, `unresolved`, `disabled`), `overlapping`, `mixed_scopes`, `sub_packages` (also as `affected_providers`), `packages`, `files_counted`, `test_files_stripped` (any `tests/` segment), `unmatched`, `matched`. |
 | `milestone-check --input F` | `exists` (exact match only), `near_matches`, `blocker`. |
 | `title --input F` | `title` without conventional-commit prefix, skip-ci markers and trailing `(#N)`; `too_short` under 25 characters. |
-| `render-body --input F` | The body `text`: imported-from note over the sanitised, linked PR body, the mailing-thread sentinel, *PR with the fix*, *Remediation developer* (`_No response_` for a bot, `remediation_developer_is_bot`); `sanitised_fields`, `fields_ok`, `bare_refs`; exit `2` with `malformed_indicator` for a PR body that does not pair. |
+| `render-body --input F` | The body `text`: imported-from note over the PR body as an inert block (its references stay unlinked text), the mailing-thread sentinel, *PR with the fix*, *Remediation developer* (`_No response_` for a bot, `remediation_developer_is_bot`); `sanitised_fields`, `fields_ok`, `bare_refs`; exit `2` with `malformed_indicator` for a PR body that does not pair. |
 | `labels --input F` | `labels`: scope, `pr_open` / `pr_merged`, `security_marker` from `tracker.labels`; never `needs_triage`; `warnings` for a closed PR. |
 | `render-rollup --input F` | `label`, `label_shell`, `text`: the first rollup entry, column 0. |
 | `dup-query --pr N --tracker T [--hits F]` | The search `query` and `command`; with `--hits`, `hits` with links, `duplicate`, `truncated` at 30 and its `warning`. |
@@ -122,7 +122,7 @@ Every command prints one JSON object; rendered text is in its `text` field.
 |---|---|
 | `parse <file> --upstream U` | `findings[]` (`index`, `title`, `tracker_title`, `severity`, `category`, `repository`, `branch`, `date_created`, the section payloads, `has_*`, `warnings`), `warnings`, `total_findings`; exit `2` with `not-a-findings-file` without a `# ` heading, a `**Severity:**` line or a pair. |
 | `keyword --file F [--tracker T]` | `cleaned`, `empty` and the single-quoted `search_command`. |
-| `render-body --input F` | The body `text`: each section sanitised (exit `2` on one that does not pair), the field mapping, the Recommended-fix `<details>`; `sanitised_fields`, `fields_ok`, `reporter_credit_is_bot`, `bare_refs`. |
+| `render-body --input F` | The body `text`: each section an inert block (exit `2` on a stray line break or a body `verify` refuses), the field mapping, the Recommended-fix `<details>`; `sanitised_fields`, `fields_ok`, `reporter_credit_is_bot`, `bare_refs`. |
 | `render-rollup --input F --k K --n N` | `label`, `label_shell`, `text`. |
 | `render-proposal --input F` | The proposal table, default disposition and reply forms, duplicates linked. |
 | `render-recap --input F` | The recap `text` and hand-off. |
diff --git a/tools/security-management/src/security_management/issue_import/cli.py b/tools/security-management/src/security_management/issue_import/cli.py
index 6d856394..db43ce48 100644
--- a/tools/security-management/src/security_management/issue_import/cli.py
+++ b/tools/security-management/src/security_management/issue_import/cli.py
@@ -85,7 +85,7 @@ def add_parsers(sub: Any) -> None:
     command("linkify", "link every bare #NNN / owner/repo#NNN", ("--input", "JSON: text, repo, kind"))
     command(
         "render-body",
-        "Step 7.1: sanitise the description and render the tracker body",
+        "Step 7.1: render the tracker body, the description as an inert block",
         ("--input", "JSON: fields{role: value}, body_fields, callout"),
     )
     command("render-rollup", "Step 7.5: the import rollup entry", ("--input", "JSON: see the README"))
@@ -98,15 +98,18 @@ def add_parsers(sub: Any) -> None:
 
 def _render_body(data: dict[str, Any]) -> dict[str, Any]:
     fields = dict(data.get("fields") or {})
-    cleaned = body.sanitise(str(fields.get("issue_description") or ""))
+    cleaned = body.inert_block(str(fields.get("issue_description") or ""))
     if not cleaned["ok"]:
         return {
             "ok": False,
-            "refused": f"the report body is malformed (unpaired {cleaned['indicator']}); it is not rendered",
+            "refused": f"the report body is malformed ({cleaned['indicator']}); it is not rendered",
             "malformed_indicator": cleaned["indicator"],
         }
     fields["issue_description"] = cleaned["text"]
     text = body.render(fields, data.get("body_fields"), callout=bool(data.get("callout")))
+    problem = body.verify(text, data.get("body_fields"))
+    if problem is not None:
+        return {"ok": False, "refused": f"{problem}; it is not rendered", "malformed_indicator": None}
     expected = list(body.headings(data.get("body_fields")).values())
     parsed = reuse.fields(text)
     credit = str(fields.get("reporter_credit") or "").strip()
diff --git a/tools/security-management/src/security_management/issue_import_from_md/render.py b/tools/security-management/src/security_management/issue_import_from_md/render.py
index 57f434ff..6073c02f 100644
--- a/tools/security-management/src/security_management/issue_import_from_md/render.py
+++ b/tools/security-management/src/security_management/issue_import_from_md/render.py
@@ -16,8 +16,8 @@
 # under the License.
 """Steps 3, 4 and 6 of the findings-file import: body, rollup, proposal table, recap.
 
-Every finding section is sanitised on its own (`shared.body.sanitise`); a
-section that does not pair its fences refuses the whole render. What stays
+Every finding section becomes its own inert block (`shared.body.inert_block`),
+and the rendered body must pass `shared.body.verify` or the render is refused. What stays
 the model's: the duplicate judgement, the credit decision under the bot/AI
 policy, and the confirmation reply.
 """
@@ -44,9 +44,9 @@ def _clean(name: str, text: object) -> str:
     raw = "" if text is None else str(text).strip("\n")
     if not raw.strip():
         return body.NO_RESPONSE
-    out = body.sanitise(raw)
+    out = body.inert_block(raw)
     if not out["ok"]:
-        raise Refused(f"section {name!r} is malformed (unpaired {out['indicator']}); it is not rendered")
+        raise Refused(f"section {name!r} is malformed ({out['indicator']}); it is not rendered")
     return str(out["text"])
 
 
@@ -93,6 +93,9 @@ def render_body(data: Mapping[str, Any]) -> dict[str, Any]:
             "\n<details><summary>Recommended fix (per the source markdown)</summary>\n\n"
             f"{fix_text}\n</details>\n"
         )
+    problem = body.verify(text, data.get("body_fields"))
+    if problem is not None:
+        return {"ok": False, "refused": f"{problem}; it is not rendered"}
     expected = list(body.headings(data.get("body_fields")).values())
     parsed = reuse.fields(text)
     credit = one_line(data.get("reporter_credit"))
diff --git a/tools/security-management/src/security_management/issue_import_from_pr/render.py b/tools/security-management/src/security_management/issue_import_from_pr/render.py
index e9a8abff..6077bfdd 100644
--- a/tools/security-management/src/security_management/issue_import_from_pr/render.py
+++ b/tools/security-management/src/security_management/issue_import_from_pr/render.py
@@ -83,14 +83,14 @@ def render_body(data: Mapping[str, Any]) -> dict[str, Any]:
     pr = data["pr"]
     number = int(pr["number"])
     url = f"https://github.com/{upstream}/pull/{number}"
-    cleaned = body.sanitise(str(pr.get("body") or ""))
+    cleaned = body.inert_block(str(pr.get("body") or ""))
     if not cleaned["ok"]:
         return {
             "ok": False,
-            "refused": f"the PR body is malformed (unpaired {cleaned['indicator']}); it is not rendered",
+            "refused": f"the PR body is malformed ({cleaned['indicator']}); it is not rendered",
             "malformed_indicator": cleaned["indicator"],
         }
-    pr_body = refs.linkify(cleaned["text"], upstream, "pull")
+    pr_body = cleaned["text"]  # inert: references inside render as text, so they are not linked
     note = (
         f"> **Imported from public PR {_pr_link(upstream, number)}** — there is no inbound `security@` report; "
         "the PR description below is the public statement of the vulnerability."
@@ -106,6 +106,9 @@ def render_body(data: Mapping[str, Any]) -> dict[str, Any]:
         "severity": data.get("severity"),
     }
     text = body.render(fields, data.get("body_fields"), callout=bool(data.get("callout")))
+    problem = body.verify(text, data.get("body_fields"))
+    if problem is not None:
+        return {"ok": False, "refused": f"{problem}; it is not rendered", "malformed_indicator": None}
     expected = list(body.headings(data.get("body_fields")).values())
     parsed = reuse.fields(text)
     return {
diff --git a/tools/security-management/src/security_management/shared/body.py b/tools/security-management/src/security_management/shared/body.py
index 74281de0..3dd6d6ec 100644
--- a/tools/security-management/src/security_management/shared/body.py
+++ b/tools/security-management/src/security_management/shared/body.py
@@ -14,47 +14,33 @@
 # KIND, either express or implied.  See the License for the
 # specific language governing permissions and limitations
 # under the License.
-"""The tracker issue body: sanitise the untrusted report, render the field sections.
+"""The tracker issue body: the untrusted report as an inert block, the field sections.
 
-The root email body is untrusted external content. It is inlined into the
-issue as readable markdown, not wrapped in a fence, so it is sanitised
-deterministically first:
+The report text (an email body, a PR description, a findings-file section)
+is untrusted external content. It goes into the issue as an **inert fenced
+block** (`inert_block`), not as markdown:
 
 - **One set of lines.** `\r\n` and `\r` become `\n`; any other character
-  `str.splitlines` breaks on (`\x0c`, U+2028, …) fails closed.
-- **Well-formedness, failing closed.** Two readers see the body: GitHub's
-  CommonMark renderer and github-body-field, which toggles "inside a fence"
-  on *every* line whose first non-whitespace is three backticks or tildes.
-  Fences are paired the CommonMark way — at most three spaces of indent, an
-  opening run of one character, closed only by a bare run of the same
-  character at least as long — and **every** fence-like line must be one of
-  those openers or closers. Otherwise (an unclosed fence, ``` "closed" by
-  `~~~`, ```` "closed" by ```, a four-space-indented fence, a fence-like
-  line inside a block) the two readers would disagree about what is code,
-  so `sanitise` returns `ok: False` with an `indicator` and the caller
-  refuses to render. Unbalanced `<details>` / `<!--` fail the same way.
-- **No raw HTML.** Every `<` followed by a letter, `/`, `!` or `?` becomes
-  `&lt;`, anywhere and fenced lines included: an HTML block (even behind a
-  list marker or a `>`) renders through fences, and an inline tag can load or
-  hide content.
-- **Demote headings.** A `#`, `##` or `###` heading outside a fence becomes
-  `####`, so a reporter's `### Severity` can never pose as a form section.
-  Inside a fence, a heading line of any level is escaped (`\\### Severity`):
-  it still reads as code, and no field parser, fence-aware or not, can match it.
-- **Drop empty fence pairs.** A bare fence opener followed only by blank lines
-  and a bare closer renders an empty code block; it is removed. A fence that
-  wraps content is never touched.
-- **Defuse images and active HTML.** Every `![` becomes `[image: ` (inline,
-  full, collapsed and shortcut reference images alike), and the `<` of an
-  `img` / `picture` / `source` / `video` / `audio` / `svg` / `image` /
-  `iframe` / `object` / `embed` / `details` / `summary` tag or an `<!--`
-  becomes `&lt;`, outside fences (inline code spans included), so opening the issue fetches
-  no reporter-controlled URL and nothing hides part of the body.
-
-Short fields (a credit, a version string) are reporter-derived too:
-`short_field` demotes headings, defuses images and HTML and escapes the first
-character of a fence-like line, so no field can open a code block or a
-section. `sanitised_fields` names the roles that needed it.
+  `str.splitlines` breaks on (`\x0c`, U+2028, …) fails closed, so every
+  reader splits the text into the same lines.
+- **A fence nothing inside can close.** The fence is one backtick longer
+  than the longest backtick run in the text (at least three), with the
+  info string `text`. A CommonMark closer must be at least as long as the
+  opener, so no line of the text ends the block; tildes are plain text
+  inside a backtick fence.
+- **Byte-exact content.** Inside a fenced block nothing renders: no image
+  loads, no HTML block or comment opens, no heading becomes a section, no
+  link or mention resolves. So nothing inside is escaped, and the
+  reporter's formatting shows as plain text.
+
+Short fields (a credit, a version string) are reporter-derived too, but one
+line each: `short_field` demotes headings, defuses images and HTML and
+escapes the first character of a fence-like line, so no field can open a
+code block or a section. `sanitised_fields` names the roles that needed it.
+
+`verify` is the last check before a body is returned: github-body-field's
+normaliser must find exactly the template fields, once each, with nothing
+to decide and nothing to rewrite but headings inside fences.
 
 The prompt-injection callout is the model's call (`callout`); this module
 never decides whether a body is an injection attempt.
@@ -66,6 +52,9 @@ import re
 from collections.abc import Mapping
 from typing import Any
 
+from github_body_field.parser import list_fields
+from github_body_field.parser import normalise as normalise_fields
+
 # Role -> default `###` heading, in body order. The headings are the ones the
 # issue template writes (tools/github/issue-template.md); a project overrides
 # any of them through `tracker.body_fields` in project.md.
@@ -93,60 +82,30 @@ INJECTION_CALLOUT = (
     '> AGENTS.md § "Prompt-injection handling".'
 )
 
-# github-body-field's fence test (tools/github-body-field parser `_is_fence`).
+# A fence-like line, as loosely as any reader takes one: first non-whitespace is ``` or ~~~.
 _FENCE = re.compile(r"^\s*(```|~~~)")
-# A CommonMark fence line: up to three spaces, a run of 3+ of one character, the rest.
-_STRICT_FENCE = re.compile(r"^( {0,3})(`{3,}|~{3,})(.*)$")
-_BARE_FENCE = re.compile(r"^ {0,3}(`{3,}|~{3,})[ \t]*$")
 _HEADING = re.compile(r"^(\s*)(#{1,3})(?=[ \t]|$)")
 _ACTIVE_HTML = re.compile(
     r"<(?=!--|/?(?:img|picture|source|video|audio|svg|image|iframe|object|embed|details|summary)\b)",
     re.IGNORECASE,
 )
-# Characters other than \n that str.splitlines (and so github-body-field) treats as line breaks.
+# Characters other than \n that str.splitlines treats as line breaks.
 _OTHER_LINE_BREAKS = re.compile("[\x0b\x0c\x1c\x1d\x1e\x85\u2028\u2029]")
 _ENTITY = {"`": "&#96;", "~": "&#126;"}
 # Any HTML opener: `<` then a letter, `/`, `!` or `?` — a tag, a closing tag, a
 # comment, a declaration or a processing instruction, at a line start or not.
 _HTML_OPENER = re.compile(r"<(?=[A-Za-z/!?])")
-# A heading line, at any level: inside a fence it is escaped so no reader takes it for a field.
-_ANY_HEADING = re.compile(r"^(\s*)(?=#{1,6}(?:[ \t]|$))")
+_BACKTICKS = re.compile(r"`+")
+# The only rewrite `verify` accepts: github-body-field escaping a heading-shaped
+# line inside a fence, which only a reader that ignores fences could misread.
+_HARMLESS_CHANGES = {"heading_in_fence"}
 
 
 def is_fence(line: str) -> bool:
-    """github-body-field's fence test: first non-whitespace is ``` or ~~~."""
+    """Whether `line` looks like a fence to the loosest reader: first non-whitespace is ``` or ~~~."""
     return bool(_FENCE.match(line))
 
 
-def fence_mask(lines: list[str]) -> list[bool] | None:
-    """Which lines are fence delimiters, or None when the fences do not pair strictly.
-
-    Every line `is_fence` matches must be a CommonMark opener (outside a block)
-    or the closer of the open block; then github-body-field's toggling and
-    CommonMark agree on what is code.
-    """
-    mask: list[bool] = []
-    opened: tuple[str, int] | None = None
-    for line in lines:
-        if not is_fence(line):
-            mask.append(False)
-            continue
-        match = _STRICT_FENCE.match(line)
-        if match is None:
-            return None
-        run, rest = match.group(2), match.group(3)
-        if opened is None:
-            if run[0] == "`" and "`" in rest:
-                return None  # not a fence in CommonMark, a toggle for the parser
-            opened = (run[0], len(run))
-        elif run[0] == opened[0] and len(run) >= opened[1] and re.fullmatch(r"[ \t]*", rest):
-            opened = None
-        else:
-            return None
-        mask.append(True)
-    return None if opened is not None else mask
-
-
 def normalise(text: str) -> str:
     """`text` with `\r\n` and `\r` as `\n`; refuses any other line-break character.
 
@@ -161,16 +120,29 @@ def normalise(text: str) -> str:
     return text
 
 
-def check(body: str) -> str | None:
-    """The first unpaired-block indicator in `body` (already `normalise`d), or None when it is well-formed."""
-    if fence_mask(body.split("\n")) is None:
-        return "code fence"
-    lowered = body.lower()
-    if lowered.count("<details") != lowered.count("</details>"):
-        return "<details>"
-    if body.count("<!--") != body.count("-->"):
-        return "<!--"
-    return None
+def fence_for(text: str) -> str:
+    """The backtick fence no line of `text` can close: one longer than its longest run, at least three."""
+    longest = max((len(run) for run in _BACKTICKS.findall(text)), default=0)
+    return "`" * max(3, longest + 1)
+
+
+def inert_block(text: str) -> dict[str, Any]:
+    """`{ok, indicator, text}`: `text` as an inert ```` ```text ```` block, or `ok: False` and why.
+
+    The content is byte-exact after line-ending normalisation; an empty or
+    blank `text` gives an empty result. A caller must not render the text
+    of an `ok: False` result.
+    """
+    try:
+        content = normalise(text)
+    except ValueError:
+        return {"ok": False, "indicator": "line break", "text": text}
+    if not content.strip():
+        return {"ok": True, "indicator": None, "text": ""}
+    if not content.endswith("\n"):
+        content += "\n"
+    fence = fence_for(content)
+    return {"ok": True, "indicator": None, "text": f"{fence}text\n{content}{fence}"}
 
 
 def _defuse_text(text: str) -> str:
@@ -178,86 +150,20 @@ def _defuse_text(text: str) -> str:
 
 
 def defuse(line: str) -> str:
-    """`line` with every image and active HTML tag defused, inside inline code spans too.
-
-    Code spans are not exempt: telling one apart (escaped backticks, spans across
-    lines) takes a CommonMark inline parser, and an escaped `<` or `[image: ` in
-    code is harmless.
-    """
+    """`line` with every image and active HTML tag defused, inside inline code spans too."""
     return _defuse_text(line)
 
 
 def escape_html(line: str) -> str:
-    """`line` with every HTML opener's `<` as `&lt;`.
-
-    An HTML block swallows what follows it up to a blank line, fence lines
-    included, so GitHub and this sanitiser would disagree about what is code;
-    behind a list marker or a `>` it still opens one. Escaping every opener,
-    not only one at a line start, closes the whole class without parsing
-    container prefixes, and `&lt;` is harmless in code.
-    """
+    """`line` with every HTML opener's `<` as `&lt;`, so no HTML block or tag opens."""
     return _HTML_OPENER.sub("&lt;", line)
 
 
-def escape_heading(line: str) -> str:
-    """`line` with a leading `#` heading marker escaped (`\\### x`), for lines inside a fence."""
-    return _ANY_HEADING.sub(lambda m: m.group(1) + "\\", line, count=1)
-
-
 def demote(line: str) -> str:
     """`line` with a `#` to `###` heading marker raised to `####`."""
     return _HEADING.sub(lambda m: m.group(1) + "####", line, count=1)
 
 
-def _drop_empty_fence_pairs(lines: list[str], mask: list[bool]) -> list[str]:
-    """`lines` without bare opener + blank lines + bare closer; only whole pairs go."""
-    out: list[str] = []
-    i = 0
-    in_fence = False
-    while i < len(lines):
-        if mask[i]:
-            if not in_fence and _BARE_FENCE.match(lines[i]):
-                j = i + 1
-                while j < len(lines) and not lines[j].strip():
-                    j += 1
-                if j < len(lines) and mask[j] and _BARE_FENCE.match(lines[j]):
-                    i = j + 1
-                    continue
-            in_fence = not in_fence
-        out.append(lines[i])
-        i += 1
-    return out
-
-
-def sanitise(body: str) -> dict[str, Any]:
-    """`{ok, indicator, text}`: the sanitised body, or `ok: False`, why, and the body untouched.
-
-    A caller must not render the text of an `ok: False` result.
-    """
-    try:
-        text = normalise(body)
-    except ValueError:
-        return {"ok": False, "indicator": "line break", "text": body}
-    indicator = check(text)
-    if indicator is not None:
-        return {"ok": False, "indicator": indicator, "text": body}
-    original = [escape_html(line) for line in text.split("\n")]
-    first = fence_mask(original)
-    assert first is not None  # check() passed
-    lines = _drop_empty_fence_pairs(original, first)
-    mask = fence_mask(lines)
-    assert mask is not None  # dropping whole pairs keeps the pairing
-    out: list[str] = []
-    in_fence = False
-    for line, delimiter in zip(lines, mask, strict=True):
-        if delimiter:
-            in_fence = not in_fence
-            out.append(line)
-            continue
-        out.append(escape_heading(line) if in_fence else defuse(demote(line)))
-    return {"ok": True, "indicator": None, "text": "\n".join(out)}
-
-
 def _short_line(line: str) -> str:
     if is_fence(line):
         stripped = line.lstrip()
@@ -314,7 +220,8 @@ def render(
 ) -> str:
     """The tracker body: one `### <heading>` section per role, `_No response_` where empty.
 
-    `fields["issue_description"]` must already be the text of an `ok` `sanitise` result.
+    `fields["issue_description"]` is placed as given: the caller builds it from
+    `inert_block` results and its own fixed text.
     """
     unknown = sorted(set(fields) - set(DEFAULT_HEADINGS))
     if unknown:
@@ -327,3 +234,23 @@ def render(
             value = f"{INJECTION_CALLOUT}\n\n{value}"
         sections.append(f"### {heading}\n\n{value}")
     return "\n\n".join(sections) + "\n"
+
+
+def verify(text: str, body_fields: Mapping[str, str] | None = None) -> str | None:
+    """Why the rendered body `text` must not be returned, or None when it is safe.
+
+    github-body-field's normaliser must find nothing to decide, nothing to
+    rewrite but headings inside fences, and exactly the template fields,
+    once each and in order.
+    """
+    expected = list(headings(body_fields).values())
+    result = normalise_fields(text, expected)
+    if result.needs_decision:
+        kinds = sorted({str(d["kind"]) for d in result.needs_decision})
+        return f"the rendered body has an ambiguous field ({', '.join(kinds)})"
+    rewrites = sorted({str(c["kind"]) for c in result.changes} - _HARMLESS_CHANGES)
+    if rewrites:
+        return f"the rendered body is not canonical ({', '.join(rewrites)})"
+    if list_fields(text) != expected:
+        return "the rendered body does not parse to exactly the template fields, once each"
+    return None
diff --git a/tools/security-management/src/security_management/shared/refs.py b/tools/security-management/src/security_management/shared/refs.py
index a2e899cd..79196c82 100644
--- a/tools/security-management/src/security_management/shared/refs.py
+++ b/tools/security-management/src/security_management/shared/refs.py
@@ -31,6 +31,8 @@ from __future__ import annotations
 
 import re
 
+from github_body_field.parser import fence_roles
+
 # Ported from tools/pr-management (pr_management/triage/render.py `_BARE_REF`):
 # a `#NNN` not already inside a link, a path, an anchor, an entity or a code span.
 # Keep the two in step.
@@ -53,16 +55,14 @@ _URL_SAFE = re.compile(r"(?:https?://|/|\.\.?/|[A-Za-z0-9_-]+/)[^\s()<>\[\]]*")
 def _segments(text: str) -> list[tuple[bool, str]]:
     """`(linkable, piece)` pairs covering `text`, line structure preserved."""
     out: list[tuple[bool, str]] = []
-    inside_fence = False
-    for index, line in enumerate(text.split("\n")):
+    lines = text.split("\n")
+    # Fences pair the CommonMark way (github-body-field), so a ```` block holding ``` stays code.
+    roles = fence_roles(lines)
+    for index, (line, role) in enumerate(zip(lines, roles, strict=True)):
         if index:
             out.append((False, "\n"))
         stripped = line.lstrip()
-        if stripped.startswith(("```", "~~~")):
-            inside_fence = not inside_fence
-            out.append((False, line))
-            continue
-        if inside_fence or stripped.startswith("<!--"):
+        if role != "text" or stripped.startswith("<!--"):
             out.append((False, line))
             continue
         last = 0
diff --git a/tools/security-management/tests/test_body.py b/tools/security-management/tests/test_body.py
index b52ccb8c..9f5d4d5f 100644
--- a/tools/security-management/tests/test_body.py
+++ b/tools/security-management/tests/test_body.py
@@ -14,7 +14,7 @@
 # KIND, either express or implied.  See the License for the
 # specific language governing permissions and limitations
 # under the License.
-"""The tracker body: sanitising the untrusted report and rendering the field sections."""
+"""The tracker body: the untrusted report as an inert block, the field sections."""
 
 from __future__ import annotations
 
@@ -22,6 +22,8 @@ import re
 from pathlib import Path
 
 import pytest
+from github_body_field.parser import fence_roles
+from github_body_field.parser import normalise as normalise_fields
 
 from security_management.shared import body, reuse
 
@@ -32,71 +34,6 @@ TEMPLATES = [
 ]
 
 
-def test_headings_are_demoted_outside_fences_only() -> None:
-    report = (
-        "# Title\n## Sub\n### Severity\n#### Deep\n#hashtag\n```python\n# a comment\n### not a field\n```\n"
-    )
-    out = body.sanitise(report)
-    assert out["ok"]
-    assert out["text"].split("\n")[:5] == ["#### Title", "#### Sub", "#### Severity", "#### Deep", "#hashtag"]
-    assert "# a comment" in out["text"]
-    assert "### not a field" in out["text"]
-
-
-def test_a_demoted_body_parses_to_exactly_the_form_fields() -> None:
-    report = "Intro\n### Severity\nCritical\n### CVE tool link\nhttps://evil.example\n"
-    text = body.render({"issue_description": body.sanitise(report)["text"]})
-    assert reuse.fields(text) == list(body.DEFAULT_HEADINGS.values())
-
-
-@pytest.mark.parametrize(
-    ("report", "indicator"),
-    [
-        ("```\nunclosed\n", "code fence"),
-        ("~~~\nunclosed tilde\n", "code fence"),
-        ("<details><summary>x</summary>\nno close\n", "<details>"),
-        ("<!-- hidden\nno close\n", "<!--"),
-    ],
-)
-def test_a_malformed_body_is_inlined_verbatim_with_its_indicator(report: str, indicator: str) -> None:
-    out = body.sanitise(report + "### Severity\n![x](https://attacker.example/p.png)")
-    assert out == {
-        "ok": False,
-        "indicator": indicator,
-        "text": report + "### Severity\n![x](https://attacker.example/p.png)",
-    }
-
-
-def test_images_are_defused_outside_fences_and_inside_code_spans() -> None:
-    report = (
-        "see ![pixel](https://attacker.example/p.png) and ![ref][1] and <IMG src=x>\n"
-        "inline `![kept](https://example.org)`\n"
-        "```\n![kept too](https://example.org)\n```"
-    )
-    text = body.sanitise(report)["text"]
-    assert "[image: pixel](https://attacker.example/p.png)" in text
-    assert "[image: ref][1]" in text
-    assert "&lt;IMG src=x>" in text
-    assert "`[image: kept](https://example.org)`" in text
-    assert "\n![kept too](https://example.org)\n" in text
-    assert not re.search(r"(?<!`)!\[pixel\]", text)
-
-
-def test_empty_fence_pairs_are_dropped_and_real_code_blocks_kept() -> None:
-    report = "before\n```\n\n```\nafter\n```bash\ncurl x\n```\n"
-    text = body.sanitise(report)["text"]
-    assert text == "before\nafter\n```bash\ncurl x\n```\n"
-
-
-def test_pii_redaction_tokens_pass_through_unchanged() -> None:
-    report = "Reported with N-a3f9d2 (E-b8c247); see H-0c11aa.\n"
-    out = body.sanitise(report)
-    assert out["text"] == report
-    rendered = body.render({"issue_description": out["text"], "reporter_credit": "N-a3f9d2"})
-    assert "N-a3f9d2 (E-b8c247); see H-0c11aa." in rendered
-    assert "### Reporter credited as\n\nN-a3f9d2\n" in rendered
-
-
 def test_empty_fields_read_no_response_and_severity_unknown() -> None:
     text = body.render({"issue_description": "report"})
     assert "### Short public summary for publish\n\n_No response_\n" in text
@@ -145,52 +82,6 @@ def test_the_tracker_body_templates_carry_the_rendered_headings(template: Path)
     assert len(headings) == 11
 
 
-@pytest.mark.parametrize(
-    "report",
-    [
-        "```\n### Severity\n~~~\n",  # ``` opened, ~~~ "closes"
-        "````\ncode\n```\n### Severity\n````\n",  # ```` opened, ``` "closes"
-        "    ```\n### Severity\n    ```\n",  # a four-space-indented fence
-        "```\nunclosed\n",
-        "```\n```python\n```\n",  # a fence-like line inside a block
-        "``` a`b\nx\n```\n",  # a backtick info string: not a fence in CommonMark
-        "\t```\nx\n\t```\n",
-    ],
-)
-def test_fences_that_do_not_pair_strictly_fail_closed(report: str) -> None:
-    out = body.sanitise(report)
-    assert (out["ok"], out["indicator"]) == (False, "code fence")
-
-
-def test_strictly_paired_fences_pass() -> None:
-    report = "```python\n# c\n```\n~~~~\n### x\n~~~~~\n   ```\ny\n   ````  \nafter\n"
-    out = body.sanitise(report)
-    assert out["ok"], out
-
-
-def test_an_empty_pair_is_dropped_only_as_a_whole_pair() -> None:
-    report = "```\na\n```\n\n~~~\nb\n~~~\n"
-    assert body.sanitise(report)["text"] == report
-    assert body.sanitise("x\n~~~\n\n~~~\ny")["text"] == "x\ny"
-
-
-@pytest.mark.parametrize(
-    ("raw", "expected"),
-    [
-        ("![x][]", "[image: x][]"),
-        ("![x]", "[image: x]"),
-        ("<picture><source srcset=u>", "&lt;picture>&lt;source srcset=u>"),
-        ("<svg onload=x>", "&lt;svg onload=x>"),
-        ("<details><summary>s</summary></details>", "&lt;details>&lt;summary>s&lt;/summary>&lt;/details>"),
-        ("<iframe src=u></iframe> <video src=u>", "&lt;iframe src=u>&lt;/iframe> &lt;video src=u>"),
-        ("x <b>tag</b> a < b", "x &lt;b>tag&lt;/b> a < b"),
-        ("<b>block</b>", "&lt;b>block&lt;/b>"),
-    ],
-)
-def test_images_and_active_html_are_defused(raw: str, expected: str) -> None:
-    assert body.sanitise(raw)["text"] == expected
-
-
 @pytest.mark.parametrize(
     ("value", "expected"),
     [
@@ -216,97 +107,112 @@ def test_a_title_like_field_cannot_open_a_code_block() -> None:
     assert reuse.fields(text) == list(body.DEFAULT_HEADINGS.values())
 
 
-@pytest.mark.parametrize(
-    "line",
-    [
-        "\\` ![x](https://a.example/p) \\`",  # escaped backticks are not a code span
-        "`a` ![x](https://a.example/p) `b`",
-        "`open\n![x](https://a.example/p) close`",  # a span across two lines
-        "``![x](https://a.example/p)``",
-    ],
-)
-def test_images_are_defused_whatever_the_backticks(line: str) -> None:
-    text = body.sanitise(line)["text"]
-    assert "![" not in text
-    assert "[image: x](https://a.example/p)" in text
+def test_html_block_starts_in_short_fields_are_escaped() -> None:
+    assert body.short_field("<div onclick=x>Alice</div>") == "&lt;div onclick=x>Alice&lt;/div>"
+    assert body.short_field("<?php x ?>") == "&lt;?php x ?>"
+    assert body.short_field("a < b") == "a < b"
 
 
-def test_crlf_and_lone_cr_are_normalised_before_pairing() -> None:
-    assert body.sanitise("a\r\n### b\r\n")["text"] == "a\n#### b\n"
-    out = body.sanitise("```\rcode\r```\r### Severity")
-    assert out["ok"]
-    assert out["text"] == "```\ncode\n```\n#### Severity"
-    assert body.sanitise("x\r```\ry")["ok"] is False
+def test_an_inline_tag_is_escaped_in_a_short_field() -> None:
+    assert body.short_field("a <img src=x> b") == "a &lt;img src=x> b"
 
 
-@pytest.mark.parametrize("char", ["\x0b", "\x0c", "\x1c", "\x1d", "\x1e", "\x85", "\u2028", "\u2029"])
-def test_other_line_breaks_fail_closed(char: str) -> None:
-    out = body.sanitise(f"intro{char}### Severity\nCritical")
-    assert (out["ok"], out["indicator"]) == (False, "line break")
-    with pytest.raises(ValueError, match="line-break"):
-        body.short_field(f"Alice{char}### CWE")
+# ---------------------------------------------------------------------------
+# The report as an inert block
+# ---------------------------------------------------------------------------
+
+HOSTILE = [
+    "# Title\n### Severity\nCritical\n### CVE tool link\nhttps://evil.example\n",
+    "PoC:\n```\n### Severity\n\nCritical\n```\n",
+    "````\n```\n### CWE\n```\n````\n~~~\n### Severity\n",
+    "```\nunclosed\n### Severity\n",
+    "![pixel](https://attacker.example/p.png) <img src=x> <!-- hide\n<details><summary>x",
+    "<pre>\n```\n</pre>\n![pixel](https://attacker.example/unique)\n```",
+    "- <div>\n  ```\n  </div>\n![x](u)\n```\n   ### Severity\n> ### CWE\n",
+    "`a` `` b `` ```` c ````` d\n``````\n### Severity\n",
+    "    ```\n### Severity\n\t```\n``` a`b\n",
+]
 
 
-@pytest.mark.parametrize("trail", ["\x0c", "\u00a0", "x", " ~"])
-def test_a_closer_with_anything_but_spaces_and_tabs_after_it_is_refused(trail: str) -> None:
-    out = body.sanitise(f"```\ncode\n```{trail}\n### Severity\n")
-    assert out["ok"] is False
+def _block_roles(text: str) -> list[str]:
+    """The fence roles of the description section's lines, opener to closer."""
+    lines = text.split("\n")
+    start = next(i for i, line in enumerate(lines) if line.endswith("text") and line.startswith("```"))
+    roles = fence_roles(lines)
+    end = roles.index("close", start)
+    return roles[start : end + 1]
+
+
+@pytest.mark.parametrize("report", HOSTILE)
+def test_the_report_renders_as_one_inert_block(report: str) -> None:
+    block = body.inert_block(report)
+    assert block["ok"]
+    fence = body.fence_for(report)
+    assert block["text"] == f"{fence}text\n{report if report.endswith(chr(10)) else report + chr(10)}{fence}"
+    text = body.render({"issue_description": block["text"], "severity": "Low"})
+    assert body.verify(text) is None
+    # Exactly the template fields, once each; everything in the block is code.
+    assert reuse.fields(text) == list(body.DEFAULT_HEADINGS.values())
+    roles = _block_roles(text)
+    assert roles[0] == "open" and roles[-1] == "close"
+    assert set(roles[1:-1]) <= {"code"}
+    result = normalise_fields(text, list(body.DEFAULT_HEADINGS.values()))
+    assert result.needs_decision == []
+    assert {c["kind"] for c in result.changes} <= {"heading_in_fence"}
 
 
-def test_a_closer_followed_by_spaces_and_tabs_closes() -> None:
-    assert body.sanitise("```\ncode\n``` \t\n### x\n")["text"] == "```\ncode\n``` \t\n#### x\n"
+def test_the_fence_is_one_longer_than_the_longest_backtick_run() -> None:
+    assert body.fence_for("no ticks") == "```"
+    assert body.fence_for("a `b` c") == "```"
+    assert body.fence_for("```") == "````"
+    assert body.fence_for("x ```````` y\n``` z") == "`" * 9
 
 
 def test_a_fenced_field_heading_cannot_reach_the_cve_record() -> None:
     from generate_cve_json.cve_json import extract_field
 
-    report = "PoC:\n```\n### Severity\n\nCritical\n# comment\n```\n"
-    cleaned = body.sanitise(report)
-    assert cleaned["ok"]
-    assert "\\### Severity\n\nCritical\n\\# comment" in cleaned["text"]
-    text = body.render({"issue_description": cleaned["text"], "severity": "Low"})
+    block = body.inert_block("PoC:\n````\n### Severity\n\nCritical\n```\n# comment\n")["text"]
+    text = body.render({"issue_description": block, "severity": "Low"})
     assert extract_field(text, "Severity") == "Low"
-    assert reuse.fields(text) == list(body.DEFAULT_HEADINGS.values())
+    assert "### Severity\n\nCritical\n```\n# comment\n" in text  # byte-exact, not escaped
 
 
-@pytest.mark.parametrize(
-    "report",
-    [
-        "<pre>\n```\n</pre>\n![pixel](https://attacker.example/unique)\n```",
-        "<div>\n```\n</div>\n![pixel](https://attacker.example/unique)\n```",
-        "<details>\n```\n</details>\n![pixel](https://attacker.example/unique)\n```",
-        "<!-- x\n```\n-->\n![pixel](https://attacker.example/unique)\n```",
-    ],
-)
-def test_html_blocks_cannot_hide_an_image_behind_a_fence(report: str) -> None:
-    out = body.sanitise(report)
-    assert out["ok"]
-    for line in out["text"].split("\n"):
-        assert not line.lstrip().startswith("<")
-    # the image line is code here, and no HTML block can end the fence early on GitHub
-    assert out["text"].startswith("&lt;")
+def test_an_empty_report_reads_no_response() -> None:
+    assert body.inert_block(" \n\n")["text"] == ""
+    text = body.render({"issue_description": body.inert_block("")["text"]})
+    assert "### The issue description\n\n_No response_\n" in text
 
 
-def test_html_block_starts_in_short_fields_are_escaped() -> None:
-    assert body.short_field("<div onclick=x>Alice</div>") == "&lt;div onclick=x>Alice&lt;/div>"
-    assert body.short_field("<?php x ?>") == "&lt;?php x ?>"
-    assert body.short_field("a < b") == "a < b"
+def test_pii_redaction_tokens_pass_through_unchanged() -> None:
+    report = "Reported with N-a3f9d2 (E-b8c247); see H-0c11aa.\n"
+    rendered = body.render(
+        {"issue_description": body.inert_block(report)["text"], "reporter_credit": "N-a3f9d2"}
+    )
+    assert "N-a3f9d2 (E-b8c247); see H-0c11aa." in rendered
+    assert "### Reporter credited as\n\nN-a3f9d2\n" in rendered
 
 
-@pytest.mark.parametrize(
-    "report",
-    [
-        "- <div>\n  ```\n  </div>\n![x](u)\n```",
-        "> <div>\n```\n</div>\n![x](u)\n```",
-        "1. <details>\n```\n</details>\n![x](u)\n```",
-        "* <!--\n```\n-->\n![x](u)\n```",
-    ],
-)
-def test_html_openers_behind_container_prefixes_are_escaped(report: str) -> None:
-    out = body.sanitise(report)
-    assert "<" not in out["text"].replace("&lt;", "")
+def test_crlf_and_lone_cr_become_lf() -> None:
+    assert body.inert_block("a\r\n### b\rc")["text"] == "```text\na\n### b\nc\n```"
 
 
-def test_an_inline_tag_is_escaped() -> None:
-    assert body.sanitise("a <img src=x> b")["text"] == "a &lt;img src=x> b"
-    assert body.short_field("a <img src=x> b") == "a &lt;img src=x> b"
+@pytest.mark.parametrize("char", ["\x0b", "\x0c", "\x1c", "\x1d", "\x1e", "\x85", "\u2028", "\u2029"])
+def test_other_line_breaks_fail_closed(char: str) -> None:
+    out = body.inert_block(f"intro{char}### Severity\nCritical")
+    assert (out["ok"], out["indicator"]) == (False, "line break")
+    with pytest.raises(ValueError, match="line-break"):
+        body.short_field(f"Alice{char}### CWE")
+
+
+def test_the_injection_callout_keeps_the_block_inert() -> None:
+    block = body.inert_block("```\n### Severity\n")["text"]
+    text = body.render({"issue_description": block}, callout=True)
+    assert body.verify(text) is None
+
+
+def test_verify_refuses_a_body_that_is_not_canonical() -> None:
+    assert "ambiguous" in str(body.verify(body.render({"issue_description": "### Severity\n\nHigh"})))
+    raw = body.render({"issue_description": "x"}).replace("### CWE", "###  CWE")
+    assert "not canonical" in str(body.verify(raw))
+    unclosed = body.render({"issue_description": "```\nx"})
+    assert body.verify(unclosed) is not None
diff --git a/tools/security-management/tests/test_issue_import.py b/tools/security-management/tests/test_issue_import.py
index b6c101e1..621c1ffc 100644
--- a/tools/security-management/tests/test_issue_import.py
+++ b/tools/security-management/tests/test_issue_import.py
@@ -398,16 +398,24 @@ def test_render_body_reports_sanitising_fields_and_bot_credit(capsys, tmp_path)
     assert out["sanitised"] and out["fields_ok"] and out["extra_fields"] == []
     assert out["fields"][3] == "Mailing list thread URL"
     assert out["reporter_credit_is_bot"] is True
-    assert out["bare_refs"] == ["#12"]
-    assert "#### Severity" in out["text"]
+    assert out["bare_refs"] == []  # inside the inert block a reference renders as text
+    assert "```text\n### Severity\nCritical ![p](https://attacker.example/p) see #12\n```" in out["text"]
 
 
-def test_render_body_refuses_a_malformed_body(capsys, tmp_path) -> None:
+def test_render_body_keeps_an_unclosed_fence_inert(capsys, tmp_path) -> None:
     data = {"fields": {"issue_description": "```\n### Severity\nCritical"}}
     code, out = run(capsys, "render-body", "--input", write(tmp_path, "b.json", data))
+    assert code == 0
+    assert out["fields_ok"]
+    assert "````text\n```\n### Severity\nCritical\n````" in out["text"]
+
+
+def test_render_body_refuses_a_body_with_a_stray_line_break(capsys, tmp_path) -> None:
+    data = {"fields": {"issue_description": "intro\x0c### Severity\nCritical"}}
+    code, out = run(capsys, "render-body", "--input", write(tmp_path, "b.json", data))
     assert code == 2
     assert out["ok"] is False
-    assert out["malformed_indicator"] == "code fence"
+    assert out["malformed_indicator"] == "line break"
     assert "text" not in out
 
 
diff --git a/tools/security-management/tests/test_issue_import_from_md.py b/tools/security-management/tests/test_issue_import_from_md.py
index ae547a69..c1192d28 100644
--- a/tools/security-management/tests/test_issue_import_from_md.py
+++ b/tools/security-management/tests/test_issue_import_from_md.py
@@ -234,7 +234,7 @@ def test_render_body_maps_the_sections(capsys, tmp_path) -> None:
     assert code == 0, out
     text = out["text"]
     assert out["fields_ok"]
-    assert "**Details:**\n\nUses `---` in prose." in text
+    assert "**Details:**\n\n````text\nUses `---` in prose." in text
     assert (
         "### Affected versions\n\n`apache/airflow` @ `main` — versions to be confirmed during triage." in text
     )
@@ -244,7 +244,7 @@ def test_render_body_maps_the_sections(capsys, tmp_path) -> None:
     assert "### Severity\n\nLOW\n" in text
     assert "### Reporter credited as\n\n_No response_\n" in text
     assert text.endswith(
-        "<details><summary>Recommended fix (per the source markdown)</summary>\n\nFix it.\n</details>\n"
+        "<details><summary>Recommended fix (per the source markdown)</summary>\n\n```text\nFix it.\n```\n</details>\n"
     )
 
 
@@ -260,16 +260,22 @@ def test_render_body_section_defaults_and_bot_credit(capsys, tmp_path) -> None:
     assert out["reporter_credit_is_bot"] is True
 
 
-def test_render_body_refuses_an_unpaired_section_and_defuses_the_rest(capsys, tmp_path) -> None:
+def test_render_body_keeps_every_section_inert(capsys, tmp_path) -> None:
     f = finding(capsys, tmp_path)
     f["recommended_fix"] = "<details>x</details>\n<img src=https://a.example/p> ![x](https://a.example/p)"
-    f["impact"] = "N-a3f9d2 told E-b8c247.\n### Severity\nCRITICAL"
+    f["impact"] = "N-a3f9d2 told E-b8c247.\n### Severity\nCRITICAL\n```\nunclosed"
     data = {"basename": "m.md", "k": 1, "n": 1, "upstream": UPSTREAM, "finding": f}
-    _, out = run(capsys, "render-body", "--input", write(tmp_path, "b.json", data))
+    code, out = run(capsys, "render-body", "--input", write(tmp_path, "b.json", data))
+    assert code == 0
     assert out["fields_ok"]
-    assert "N-a3f9d2 told E-b8c247.\n#### Severity" in out["text"]
-    assert "&lt;details>x&lt;/details>\n&lt;img src=https://a.example/p> [image: x]" in out["text"]
-    f["impact"] = "```\nunclosed"
+    assert body.verify(out["text"]) is None
+    # Byte-exact inside a fence one longer than the longest backtick run.
+    assert "````text\nN-a3f9d2 told E-b8c247.\n### Severity\nCRITICAL\n```\nunclosed\n````" in out["text"]
+    assert (
+        "```text\n<details>x</details>\n<img src=https://a.example/p> ![x](https://a.example/p)\n```"
+        in out["text"]
+    )
+    f["impact"] = "line\u2028break"
     code, out = run(capsys, "render-body", "--input", write(tmp_path, "b.json", data))
     assert code == 2
     assert "Impact" in out["refused"]
diff --git a/tools/security-management/tests/test_issue_import_from_pr.py b/tools/security-management/tests/test_issue_import_from_pr.py
index 2750e234..9440c2c2 100644
--- a/tools/security-management/tests/test_issue_import_from_pr.py
+++ b/tools/security-management/tests/test_issue_import_from_pr.py
@@ -213,7 +213,7 @@ def body_input(**extra: Any) -> dict[str, Any]:
     }
 
 
-def test_render_body_sentinels_and_sanitised_pr_body(capsys, tmp_path) -> None:
+def test_render_body_sentinels_and_inert_pr_body(capsys, tmp_path) -> None:
     _, out = run(capsys, "render-body", "--input", write(tmp_path, "b.json", body_input()))
     text = out["text"]
     assert out["fields_ok"] and out["sanitised"]
@@ -224,9 +224,8 @@ def test_render_body_sentinels_and_sanitised_pr_body(capsys, tmp_path) -> None:
     assert "### Reporter credited as\n\n_No response_\n" in text
     assert "### Remediation developer\n\nJustin Pakzad\n" in text
     assert "### Severity\n\nUnknown\n" in text
-    assert "#### Severity" in text
-    assert "[image: x]" in text
-    assert "[#123](https://github.com/apache/airflow/pull/123)" in text
+    # The PR body is an inert block: byte-exact, nothing in it renders or links.
+    assert "```text\nFixes #123.\n### Severity\nCritical\n![x](https://attacker.example/p.png)\n```" in text
     assert out["bare_refs"] == []
 
 
@@ -370,13 +369,21 @@ def test_render_rollup_keeps_a_markdown_remediation_developer_in_code(capsys, tm
 
 
 @pytest.mark.parametrize("pr_body", ["```\nunclosed", "```\n### Severity\n~~~\n", "    ```\nx\n    ```"])
-def test_render_body_refuses_a_pr_body_that_does_not_pair(capsys, tmp_path, pr_body: str) -> None:
+def test_render_body_keeps_unpaired_fences_inert(capsys, tmp_path, pr_body: str) -> None:
     data = body_input()
     data["pr"]["body"] = pr_body
     code, out = run(capsys, "render-body", "--input", write(tmp_path, "b.json", data))
+    assert code == 0
+    assert out["fields_ok"]
+    assert "````text\n" + pr_body.rstrip("\n") + "\n````" in out["text"]
+
+
+def test_render_body_refuses_a_pr_body_with_a_stray_line_break(capsys, tmp_path) -> None:
+    data = body_input()
+    data["pr"]["body"] = "x\u2029### Severity"
+    code, out = run(capsys, "render-body", "--input", write(tmp_path, "b.json", data))
     assert code == 2
-    assert out["ok"] is False
-    assert out["malformed_indicator"] == "code fence"
+    assert out["malformed_indicator"] == "line break"
 
 
 @pytest.mark.parametrize("segment", ["\\1", "\\g<0>", "..", "a b", "-x"])