Files
pruefwerk/compliance-dashboard/src/components/markdown.rs
T
sharangandClaude Opus 5.5 5407e1d7ed
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Skipped
CI / Deploy MCP (push) Successful in 6m2s
CI / Deploy Agent (push) Successful in 12m25s
CI / Deploy Dashboard (push) Successful in 14m42s
feat(dashboard): CRA requirements by name, no off-site advisory links (#1074)
The Prüfwerk views name each CRA requirement and what green, orange and red mean, in a map by area. Off-site advisory links become copy buttons; a "Quelle" link stays only where the provider requires a backlink (Siemens ProductCERT). Ticket texts and the readable evidence pack use the names; machine-readable exports keep their IDs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Q9inRcu428A2iNjDHPEAT9
2026-11-27 22:49:10 +00:00

143 lines
5.5 KiB
Rust

//! Markdown from the language model or a scanner, made safe to show as HTML.
//!
//! The help assistant answers in markdown, and semgrep rule messages are
//! markdown (the finding description). Neither is ours, so nothing in it may
//! reach the page as markup of its own: raw HTML is shown as text, and links
//! keep only Breakpilot's own pages, relative paths and mail targets.
//! Prüfwerk sends nobody to another site: a link anywhere else (an advisory
//! database, a vendor page) is shown as its text, and an image from another
//! site as its description.
use pulldown_cmark::{CowStr, Event, Options, Parser, Tag, TagEnd};
/// The domain whose pages (and subdomains) a link may open.
const OWN_DOMAIN: &str = "breakpilot.com";
/// Render `markdown` to HTML that is safe to insert into the page.
///
/// # Arguments
///
/// * `markdown` - Text in CommonMark (with tables and strikethrough)
///
/// # Returns
///
/// HTML with every raw HTML tag escaped and every link pointing at a
/// Breakpilot page, a mail address or a relative path; other links are left
/// as their text.
///
/// # Examples
///
/// ```ignore
/// assert_eq!(render_markdown("**a** `b`"), "<p><strong>a</strong> <code>b</code></p>\n");
/// ```
pub fn render_markdown(markdown: &str) -> String {
let options = Options::ENABLE_TABLES | Options::ENABLE_STRIKETHROUGH;
// Links and images do not nest, so one flag per kind says whether the
// open one was dropped and its end tag must go too.
let (mut link_dropped, mut image_dropped) = (false, false);
let events = Parser::new_ext(markdown, options).filter_map(move |event| match event {
// Shown as the text it is; `push_html` escapes text.
Event::Html(html) | Event::InlineHtml(html) => Some(Event::Text(html)),
Event::Start(Tag::Link { ref dest_url, .. }) => {
link_dropped = !allowed(dest_url);
(!link_dropped).then_some(event)
}
Event::End(TagEnd::Link) => (!std::mem::take(&mut link_dropped)).then_some(event),
// An image's inner text is its description: a dropped image leaves it.
Event::Start(Tag::Image { ref dest_url, .. }) => {
image_dropped = !allowed(dest_url);
(!image_dropped).then_some(event)
}
Event::End(TagEnd::Image) => (!std::mem::take(&mut image_dropped)).then_some(event),
other => Some(other),
});
let mut html = String::with_capacity(markdown.len() * 3 / 2);
pulldown_cmark::html::push_html(&mut html, events);
html
}
/// Whether a link to `url` may stay a link: a relative path, a mail
/// address, or a web page on Breakpilot's own domain.
fn allowed(url: &CowStr<'_>) -> bool {
let lower = url.trim().to_ascii_lowercase();
if lower.starts_with("mailto:") {
return true;
}
let Some(rest) = lower
.strip_prefix("https://")
.or_else(|| lower.strip_prefix("http://"))
else {
// `//host/…` is another site, `javascript:` and the like are not pages.
return !lower.contains(':') && !lower.starts_with("//");
};
// The host ends at the path, query or fragment; a `user@` before it and
// a port after it are not part of it.
let authority = rest.split(['/', '?', '#']).next().unwrap_or_default();
let host = authority.rsplit('@').next().unwrap_or_default();
let host = host.split(':').next().unwrap_or_default();
host == OWN_DOMAIN || host.ends_with(&format!(".{OWN_DOMAIN}"))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn bold_and_code_are_closed() {
let html = render_markdown("**HTTPS only** and `ssh://` are rejected");
assert_eq!(
html,
"<p><strong>HTTPS only</strong> and <code>ssh://</code> are rejected</p>\n"
);
}
#[test]
fn lists_render_as_lists() {
let html = render_markdown("- one\n- two");
assert!(html.contains("<ul>") && html.contains("<li>two</li>"));
}
#[test]
fn raw_html_is_shown_as_text() {
let html = render_markdown("<img src=x onerror=alert(1)> hi");
assert!(!html.contains("<img"));
assert!(html.contains("&lt;img"));
}
#[test]
fn only_breakpilot_pages_and_relative_paths_stay_links() {
let html = render_markdown(
"[x](javascript:alert(1)) [osv](https://osv.dev/vulnerability/CVE-1) \
[docs](https://docs.breakpilot.com/pruefwerk/) [z](/guide) [m](mailto:a@b.example)",
);
assert!(!html.contains("javascript:"));
assert!(!html.contains("osv.dev"));
assert!(html.contains("osv"), "the text stays: {html}");
assert!(html.contains("href=\"https://docs.breakpilot.com/pruefwerk/\""));
assert!(html.contains("href=\"/guide\""));
assert!(html.contains("href=\"mailto:a@b.example\""));
}
#[test]
fn a_look_alike_host_is_another_site() {
for url in [
"https://breakpilot.com.evil.example/x",
"https://evilbreakpilot.com/x",
"https://breakpilot.com@evil.example/x",
"//evil.example/x",
] {
let html = render_markdown(&format!("[a]({url})"));
assert!(!html.contains("href"), "{url}: {html}");
}
let html = render_markdown("[a](https://user@cloud.breakpilot.com:443/x)");
assert!(html.contains("href"), "{html}");
}
#[test]
fn an_image_from_another_site_leaves_its_description() {
let html = render_markdown("![diagram](https://evil.example/p.png)");
assert!(!html.contains("<img"));
assert!(html.contains("diagram"));
}
}