fix(semgrep): short finding titles, rule messages shown as Markdown
CI / Check (push) Skipped
CI / Detect Changes (pull_request) Skipped
CI / Deploy Agent (pull_request) Skipped
CI / Deploy Dashboard (pull_request) Skipped
CI / Deploy Docs (pull_request) Skipped
CI / Deploy MCP (pull_request) Skipped
CI / Check (pull_request) Successful in 8m30s
CI / Check (push) Skipped
CI / Detect Changes (pull_request) Skipped
CI / Deploy Agent (pull_request) Skipped
CI / Deploy Dashboard (pull_request) Skipped
CI / Deploy Docs (pull_request) Skipped
CI / Deploy MCP (pull_request) Skipped
CI / Check (pull_request) Successful in 8m30s
The vendored GitLab rules (#492) carry pages of Markdown with code examples as their message, and the scanner used the message as both the title and the description: the finding title, the findings list and the tracker issue title were a wall of text, and the description showed the code collapsed into one paragraph. - Title: the rule's metadata.shortDescription (every GitLab rule has one), else the message's first sentence on one line, without code marks, cut at a word after 120 characters. The description keeps the whole message. Fingerprints are unchanged (rule, path, line). - Dashboard: a semgrep finding's description is rendered as Markdown through the existing safe renderer (raw HTML shown as text, only web and mail links); other scanners' plain text is shown as before. - Startup migration: stored semgrep findings with a multi-line or longer title get the short description of their bundled rule, else the first sentence (logged as semgrep_titles in "migrated stored findings"). Open tracker issues keep their old titles (trackers only change an issue's status); new issues get the short title. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EYKjxacrr6K88DruUmP48p
This commit is contained in:
1 parent
e1bf9e861c
commit
78e6185822
6 files changed
+203
-9
No files matched your search
@@ -5,6 +5,10 @@
|
||||
//! #463: semgrep findings of our own rules were stored with the staging path
|
||||
//! in their rule id (`tmp.cra-ai-20-csharp-xxe`), and control-check findings
|
||||
//! with the catalog's transliterated titles ("cra-ai-6: Integritaetspruefung").
|
||||
//! A1: semgrep findings were stored with the rule's whole message as their
|
||||
//! title, pages of Markdown for the vendored GitLab rules; the title becomes
|
||||
//! the rule's short description or the message's first sentence.
|
||||
//!
|
||||
//! The fingerprints stay as they are (see [`crate::pipeline::semgrep::fingerprint`]),
|
||||
//! so the next scan finds the stored findings again and their triage, status
|
||||
//! and tracker issues stay with them.
|
||||
@@ -28,6 +32,8 @@ pub struct Migrated {
|
||||
pub fingerprints: u64,
|
||||
/// control-check findings whose title or description got its umlauts.
|
||||
pub titles: u64,
|
||||
/// semgrep findings whose title was the rule's whole message.
|
||||
pub semgrep_titles: u64,
|
||||
}
|
||||
|
||||
/// Rewrite the stored findings of every tenant. A tenant that fails is
|
||||
@@ -44,6 +50,7 @@ pub async fn migrate_stored_findings(pool: &DatabasePool) -> Result<Migrated, Ag
|
||||
total.rule_ids += m.rule_ids;
|
||||
total.fingerprints += m.fingerprints;
|
||||
total.titles += m.titles;
|
||||
total.semgrep_titles += m.semgrep_titles;
|
||||
}
|
||||
Err(e) => tracing::error!(
|
||||
database = db.inner().name(),
|
||||
@@ -120,9 +127,51 @@ pub async fn migrate_tenant(db: &Database) -> Result<Migrated, AgentError> {
|
||||
.await?;
|
||||
migrated.titles += 1;
|
||||
}
|
||||
|
||||
// Only titles a scan would now write shorter: a long or multi-line one.
|
||||
let mut cursor = findings
|
||||
.find(doc! {
|
||||
"scanner": "semgrep",
|
||||
"$or": [
|
||||
{ "title": { "$regex": "\n" } },
|
||||
{ "$expr": { "$gt": [{ "$strLenCP": "$title" }, MAX_STORED_TITLE_CHARS] } },
|
||||
],
|
||||
})
|
||||
.projection(doc! { "title": 1, "rule_id": 1 })
|
||||
.await?;
|
||||
while let Some(row) = cursor.try_next().await? {
|
||||
let (Ok(id), Ok(title)) = (row.get_object_id("_id"), row.get_str("title")) else {
|
||||
continue;
|
||||
};
|
||||
let new_title = semgrep_title(row.get_str("rule_id").ok(), title);
|
||||
if new_title == title {
|
||||
continue;
|
||||
}
|
||||
findings
|
||||
.update_one(doc! { "_id": id }, doc! { "$set": { "title": new_title } })
|
||||
.await?;
|
||||
migrated.semgrep_titles += 1;
|
||||
}
|
||||
Ok(migrated)
|
||||
}
|
||||
|
||||
/// A stored semgrep title longer than this was the rule's whole message: a
|
||||
/// scan writes at most [`semgrep::headline`]'s length.
|
||||
const MAX_STORED_TITLE_CHARS: i32 = 160;
|
||||
|
||||
/// The title a scan now gives a semgrep finding of `rule_id` whose stored
|
||||
/// title is the rule's message: the bundled rule's short description, else
|
||||
/// the message's first sentence.
|
||||
fn semgrep_title(rule_id: Option<&str>, stored: &str) -> String {
|
||||
rule_id
|
||||
.and_then(|rule| {
|
||||
semgrep::bundled_short_descriptions()
|
||||
.get(semgrep::bare_rule_id(rule))
|
||||
.copied()
|
||||
})
|
||||
.map_or_else(|| semgrep::headline(stored), str::to_string)
|
||||
}
|
||||
|
||||
/// The bare id of a stored semgrep rule id that still carries a path
|
||||
/// prefix; `None` when there is nothing to rewrite.
|
||||
fn bare_semgrep_rule_id(stored: &str) -> Option<&str> {
|
||||
|
||||
@@ -38,6 +38,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
rule_ids = m.rule_ids,
|
||||
fingerprints = m.fingerprints,
|
||||
titles = m.titles,
|
||||
semgrep_titles = m.semgrep_titles,
|
||||
"migrated stored findings"
|
||||
),
|
||||
Err(e) => tracing::error!("migrating stored findings failed: {e}"),
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use std::collections::HashMap;
|
||||
use std::ffi::OsString;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
@@ -121,6 +122,70 @@ pub fn fingerprint(repo_id: &str, rule: &str, path: &str, line: u32) -> String {
|
||||
dedup::compute_fingerprint(&[repo_id, &hashed, path, &line.to_string()])
|
||||
}
|
||||
|
||||
/// Longest title taken from a rule's message; longer ones are cut at a word.
|
||||
const MAX_TITLE_CHARS: usize = 120;
|
||||
|
||||
/// A finding's title: the rule's `metadata.shortDescription` (the GitLab
|
||||
/// pack has one for every rule, whose message is pages of Markdown with code
|
||||
/// examples), else the first sentence of `message`, at most
|
||||
/// [`MAX_TITLE_CHARS`] characters. The whole message stays the description.
|
||||
pub fn finding_title(message: &str, metadata: Option<&serde_json::Value>) -> String {
|
||||
metadata
|
||||
.and_then(|m| m.get("shortDescription"))
|
||||
.and_then(serde_json::Value::as_str)
|
||||
.map(str::trim)
|
||||
.filter(|short| !short.is_empty())
|
||||
.map_or_else(|| headline(message), str::to_string)
|
||||
}
|
||||
|
||||
/// The first sentence of `message`, on one line, without Markdown code
|
||||
/// marks, cut at a word boundary after [`MAX_TITLE_CHARS`] characters.
|
||||
pub fn headline(message: &str) -> String {
|
||||
// The first paragraph; a wrapped one is joined to one line.
|
||||
let paragraph = message
|
||||
.trim()
|
||||
.split("\n\n")
|
||||
.next()
|
||||
.unwrap_or_default()
|
||||
.replace('`', "");
|
||||
let line = paragraph.split_whitespace().collect::<Vec<_>>().join(" ");
|
||||
// A sentence ends at a full stop followed by a space; a dot inside a
|
||||
// name (`String.Format`, `os.Executable`) is not one.
|
||||
let sentence = line.find(". ").map_or(line.as_str(), |end| &line[..=end]);
|
||||
if sentence.chars().count() <= MAX_TITLE_CHARS {
|
||||
return sentence.to_string();
|
||||
}
|
||||
let cut: String = sentence.chars().take(MAX_TITLE_CHARS).collect();
|
||||
let at_word = cut.rfind(' ').map_or(cut.as_str(), |space| &cut[..space]);
|
||||
format!("{}…", at_word.trim_end_matches([',', ';', ':', ' ']))
|
||||
}
|
||||
|
||||
/// The `shortDescription` of every bundled rule that has one, by rule id:
|
||||
/// for findings stored with their whole message as the title.
|
||||
pub fn bundled_short_descriptions() -> &'static HashMap<&'static str, &'static str> {
|
||||
static SHORT: std::sync::LazyLock<HashMap<&'static str, &'static str>> =
|
||||
std::sync::LazyLock::new(|| {
|
||||
let mut short = HashMap::new();
|
||||
for (_, rules) in RULE_PACKS {
|
||||
let mut id = None;
|
||||
for line in rules.lines().map(str::trim) {
|
||||
if let Some(rule) = line.strip_prefix("- id:") {
|
||||
id = Some(rule.trim().trim_matches(|c| c == '"' || c == '\''));
|
||||
} else if let (Some(rule), Some(text)) =
|
||||
(id, line.strip_prefix("shortDescription:"))
|
||||
{
|
||||
let text = text.trim().trim_matches(|c| c == '"' || c == '\'');
|
||||
if !text.is_empty() {
|
||||
short.insert(rule, text);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
short
|
||||
});
|
||||
&SHORT
|
||||
}
|
||||
|
||||
/// Write the bundled rule packs to stable temp paths (atomic: unique tmp +
|
||||
/// rename). The tmp name is unique per call, not per process: scans run
|
||||
/// concurrently in one agent, and a shared tmp file let one scan rename it
|
||||
@@ -224,12 +289,13 @@ impl Scanner for SemgrepScanner {
|
||||
let snippet = read_lines(repo_path, &path, r.start.line, end_line)
|
||||
.or_else(|| (r.extra.lines != REDACTED_LINES).then(|| r.extra.lines.clone()));
|
||||
|
||||
let title = finding_title(&r.extra.message, r.extra.metadata.as_ref());
|
||||
let mut finding = Finding::new(
|
||||
repo_id.to_string(),
|
||||
fingerprint,
|
||||
"semgrep".to_string(),
|
||||
ScanType::Sast,
|
||||
r.extra.message.clone(),
|
||||
title,
|
||||
r.extra.message,
|
||||
severity,
|
||||
);
|
||||
@@ -731,6 +797,59 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_gitlab_rule_is_titled_by_its_short_description() {
|
||||
let message = "The `HttpOnly` attribute when set to `true` protects the cookie value from being accessed by\nclient side JavaScript such\nas reading the `document.cookie` values.\n\nExample of protecting an HttpCookie:\n```\n// Create an HttpOnly cookie.\nHttpCookie someCookie = new HttpCookie(\"SomeCookieName\", \"SomeValue\");\nsomeCookie.HttpOnly = true;\n```\n";
|
||||
let metadata = serde_json::json!({
|
||||
"shortDescription": "Sensitive cookie without 'HttpOnly' flag",
|
||||
"cwe": "CWE-1004",
|
||||
});
|
||||
assert_eq!(
|
||||
finding_title(message, Some(&metadata)),
|
||||
"Sensitive cookie without 'HttpOnly' flag"
|
||||
);
|
||||
// Without one: the first sentence, on one line, no code marks.
|
||||
assert_eq!(
|
||||
finding_title(message, None),
|
||||
"The HttpOnly attribute when set to true protects the cookie value from being accessed by client side JavaScript such as…"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_short_message_stays_the_title() {
|
||||
let ours = "A process is started with a command line built from strings — command injection (CWE-78). Start a fixed program.";
|
||||
assert_eq!(
|
||||
finding_title(ours, Some(&serde_json::json!({"cwe": ["CWE-78"]}))),
|
||||
"A process is started with a command line built from strings — command injection (CWE-78)."
|
||||
);
|
||||
// A dot inside a name does not end the sentence.
|
||||
assert_eq!(
|
||||
headline("Use String.Format with care"),
|
||||
"Use String.Format with care"
|
||||
);
|
||||
let long = "word ".repeat(40);
|
||||
let title = headline(&long);
|
||||
assert!(title.ends_with('…') && title.chars().count() <= MAX_TITLE_CHARS + 1);
|
||||
assert!(!title.contains(" "));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_gitlab_rule_has_a_bundled_short_description() {
|
||||
let short = bundled_short_descriptions();
|
||||
let gitlab: Vec<_> = bundled_rule_ids()
|
||||
.iter()
|
||||
.filter(|id| id.starts_with("gitlab-"))
|
||||
.collect();
|
||||
assert!(!gitlab.is_empty());
|
||||
for id in gitlab {
|
||||
assert!(short.contains_key(*id), "{id}");
|
||||
}
|
||||
assert_eq!(
|
||||
short["gitlab-csharp_cookies_rule-CookieWithoutHttpOnlyFlag"],
|
||||
"Sensitive cookie without 'HttpOnly' flag"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extract_cwe_handles_list_and_normalises() {
|
||||
let md = serde_json::json!({"cwe": ["CWE-798: Use of Hard-coded Credentials"]});
|
||||
|
||||
@@ -84,8 +84,18 @@ async fn stored_findings_are_migrated_and_a_rescan_finds_nothing_new() {
|
||||
Severity::Medium,
|
||||
);
|
||||
control.file_path = Some("a.c".into());
|
||||
// A1: a vendored GitLab rule's whole message as the title.
|
||||
let message = "The `HttpOnly` attribute when set to `true` protects the cookie value from being accessed by\nclient side JavaScript.\n\nExample:\n```\nsomeCookie.HttpOnly = true;\n```\n";
|
||||
let mut cookie = semgrep_finding(
|
||||
"gitlab-csharp_cookies_rule-CookieWithoutHttpOnlyFlag",
|
||||
"fp-cookie".into(),
|
||||
"src/Web.cs",
|
||||
4,
|
||||
);
|
||||
cookie.title = message.into();
|
||||
cookie.description = message.into();
|
||||
db.findings()
|
||||
.insert_many([xxe.clone(), cred.clone(), older.clone(), control])
|
||||
.insert_many([xxe.clone(), cred.clone(), older.clone(), control, cookie])
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
@@ -99,9 +109,13 @@ async fn stored_findings_are_migrated_and_a_rescan_finds_nothing_new() {
|
||||
Migrated {
|
||||
rule_ids: 3,
|
||||
fingerprints: 1,
|
||||
titles: 1
|
||||
titles: 1,
|
||||
semgrep_titles: 1,
|
||||
}
|
||||
);
|
||||
let row = by_fingerprint(&db, "fp-cookie").await;
|
||||
assert_eq!(row.title, "Sensitive cookie without 'HttpOnly' flag");
|
||||
assert_eq!(row.description, message);
|
||||
let row = by_fingerprint(&db, &xxe.fingerprint).await;
|
||||
assert_eq!(row.rule_id.as_deref(), Some("cra-ai-20-csharp-xxe"));
|
||||
let row = by_fingerprint(&db, &cred.fingerprint).await;
|
||||
@@ -154,7 +168,7 @@ async fn stored_findings_are_migrated_and_a_rescan_finds_nothing_new() {
|
||||
.count_documents(doc! { "scanner": "semgrep" })
|
||||
.await
|
||||
.unwrap(),
|
||||
3
|
||||
4
|
||||
);
|
||||
|
||||
pool.drop_tenant(TENANT).await.ok();
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
//! Markdown from the language model, made safe to show as HTML.
|
||||
//! Markdown from the language model or a scanner, made safe to show as HTML.
|
||||
//!
|
||||
//! The help assistant answers in markdown. It is model output, so nothing in
|
||||
//! it may reach the page as markup of its own: raw HTML is shown as text, and
|
||||
//! links keep only web and mail targets.
|
||||
//! 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 web and mail targets.
|
||||
|
||||
use pulldown_cmark::{CowStr, Event, Options, Parser, Tag};
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ use dioxus_free_icons::Icon;
|
||||
|
||||
use crate::app::Route;
|
||||
use crate::components::code_snippet::CodeSnippet;
|
||||
use crate::components::markdown::render_markdown;
|
||||
use crate::components::page_header::PageHeader;
|
||||
use crate::components::severity_badge::SeverityBadge;
|
||||
use crate::i18n::texts::{common, findings as tx};
|
||||
@@ -133,7 +134,16 @@ pub fn FindingDetailPage(id: String) -> Element {
|
||||
|
||||
div { class: "card",
|
||||
div { class: "card-header", {tx::DESCRIPTION.get(lang)} }
|
||||
p { {shown(&f.description)} }
|
||||
// A semgrep rule's message is Markdown (paragraphs, code
|
||||
// examples); other scanners write plain text.
|
||||
if f.scanner == "semgrep" {
|
||||
div {
|
||||
class: "finding-md help-md",
|
||||
dangerous_inner_html: render_markdown(&f.description),
|
||||
}
|
||||
} else {
|
||||
p { {shown(&f.description)} }
|
||||
}
|
||||
}
|
||||
|
||||
// Where it is and what it violates, even when there is no
|
||||
|
||||
Reference in new issue
Block a user