From 92d150fa3020df25773144f559073b177d284fc2 Mon Sep 17 00:00:00 2001 From: ammartahamohamedy Date: Wed, 2 Dec 2026 17:50:01 +0200 Subject: [PATCH 1/2] Escape bidi, C1 and DEL characters in JSON and SARIF output --- src/coverage.rs | 2 +- src/deploy.rs | 2 +- src/lib.rs | 14 +++--- src/text.rs | 58 +++++++++++++++++++++++ src/tools.rs | 17 +++++-- tests/http.rs | 123 +++++++++++++++++++++++++++++++++++++++++++++++- tests/sarif.rs | 59 +++++++++++++++++++++++ 7 files changed, 260 insertions(+), 15 deletions(-) diff --git a/src/coverage.rs b/src/coverage.rs index 9117299..89a1f7b 100644 --- a/src/coverage.rs +++ b/src/coverage.rs @@ -125,7 +125,7 @@ pub(crate) async fn upload( .await?; let mut stdout = std::io::stdout().lock(); if args.json { - writeln!(stdout, "{}", serde_json::to_string(&result)?)?; + writeln!(stdout, "{}", crate::tools::compact(&result)?)?; } else { writeln!( stdout, diff --git a/src/deploy.rs b/src/deploy.rs index 3736fd1..3557c00 100644 --- a/src/deploy.rs +++ b/src/deploy.rs @@ -473,7 +473,7 @@ async fn wait_with_output( } if let Some(verdict) = verdict { if args.json { - writeln!(stdout, "{}", serde_json::to_string_pretty(raw)?)?; + writeln!(stdout, "{}", crate::tools::pretty(raw)?)?; } else { for deploy in &selected { write_lines(stdout, deploy, args.until)?; diff --git a/src/lib.rs b/src/lib.rs index 2ac4644..9b624e3 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -479,7 +479,7 @@ pub async fn run(cli: Cli, token: Option) -> anyhow::Result) -> anyhow::Result anyhow::Result "review_id": review_id, "review_url": url.as_str(), }); - writeln!(stdout, "{}", serde_json::to_string_pretty(&acknowledgment)?)?; + writeln!(stdout, "{}", tools::pretty(&acknowledgment)?)?; } else { writeln!(stdout, "{url}")?; } @@ -1755,7 +1755,7 @@ async fn write_sarif( api.organization_id(), api.review_url(review_id).as_str(), )?; - tokio::fs::write(path, serde_json::to_vec_pretty(&document)?) + tokio::fs::write(path, tools::pretty(&document)?) .await .with_context(|| format!("could not write SARIF to {}", path.display())) } @@ -1861,7 +1861,7 @@ fn print_audit( "review_url": url.as_str(), "review": raw, }); - writeln!(stdout, "{}", serde_json::to_string_pretty(&document)?)?; + writeln!(stdout, "{}", tools::pretty(&document)?)?; } // `read_review` refuses SARIF for any review but a pull request's. OutputFormat::Sarif | OutputFormat::Text => { @@ -1890,7 +1890,7 @@ fn print_review( "review_url": api.review_url(detail.id).as_str(), "review": raw, }); - writeln!(stdout, "{}", serde_json::to_string_pretty(&document)?)?; + writeln!(stdout, "{}", tools::pretty(&document)?)?; } OutputFormat::Sarif => { let document = sarif::review( @@ -1899,7 +1899,7 @@ fn print_review( api.organization_id(), api.review_url(requested_review).as_str(), )?; - writeln!(stdout, "{}", serde_json::to_string_pretty(&document)?)?; + writeln!(stdout, "{}", tools::pretty(&document)?)?; } OutputFormat::Text => { write!( diff --git a/src/text.rs b/src/text.rs index 6fbdb4c..0b45d61 100644 --- a/src/text.rs +++ b/src/text.rs @@ -34,6 +34,30 @@ pub fn one_line(text: &str) -> String { terminal_safe(text).replace(['\n', '\t'], " ") } +/// Writes each character [`terminal_safe`] replaces that a serialized JSON +/// document still holds raw as a `\u` escape. `serde_json` escapes only +/// U+0000 to U+001F, so DEL, C1 controls and bidirectional controls in a +/// string would otherwise reach the terminal. Outside its strings a +/// serialized document holds only ASCII punctuation, digits, letters and +/// whitespace, so every such character is inside a string, where the escape +/// decodes to the same character: the document keeps its values. A raw +/// newline is the pretty printer's layout and stays. +pub fn json_safe(json: &str) -> String { + use std::fmt::Write as _; + + let mut escaped = String::with_capacity(json.len()); + for character in json.chars() { + if (character.is_control() && character != '\n') || is_bidi_control(character) { + // Every such character is in the Basic Multilingual Plane, so one + // escape holds it. Writing to a `String` cannot fail. + let _ = write!(escaped, "\\u{:04x}", u32::from(character)); + } else { + escaped.push(character); + } + } + escaped +} + #[cfg(test)] mod tests { use super::*; @@ -71,4 +95,38 @@ mod tests { fn ordinary_unicode_is_preserved() { assert_eq!(terminal_safe("Café — résumé"), "Café — résumé"); } + + #[test] + fn json_strings_escape_every_terminal_control_and_keep_their_value() { + let value = serde_json::json!({ + "title": "fix\u{202e}txt.exe \u{2066}x\u{2069} \u{9b}31m \u{7f} \u{85} \u{61c} \u{200e}", + "kept": "Café — résumé\u{1b}[2J\n\t\\\u{202e}", + }); + for json in [ + serde_json::to_string(&value).unwrap(), + serde_json::to_string_pretty(&value).unwrap(), + ] { + let escaped = json_safe(&json); + assert_eq!(terminal_safe(&escaped), escaped); + assert!( + escaped.contains( + r"fix\u202etxt.exe \u2066x\u2069 \u009b31m \u007f \u0085 \u061c \u200e" + ) + ); + // A backslash in the string stays escaped ahead of the new escape. + assert!(escaped.contains(r#"\\\u202e""#)); + assert_eq!( + serde_json::from_str::(&escaped).unwrap(), + value + ); + } + let pretty = serde_json::to_string_pretty(&value).unwrap(); + assert_eq!(json_safe(&pretty).lines().count(), pretty.lines().count()); + } + + #[test] + fn json_without_terminal_controls_is_unchanged() { + let json = r#"{"name":"Café — résumé","escaped":"\u001b[2J\n"}"#; + assert_eq!(json_safe(json), json); + } } diff --git a/src/tools.rs b/src/tools.rs index c1c4af0..4287d5d 100644 --- a/src/tools.rs +++ b/src/tools.rs @@ -86,14 +86,21 @@ pub(crate) struct ExportArgs { } pub(crate) fn json(value: &serde_json::Value) -> anyhow::Result { - writeln!( - std::io::stdout().lock(), - "{}", - serde_json::to_string_pretty(value)? - )?; + writeln!(std::io::stdout().lock(), "{}", pretty(value)?)?; Ok(Verdict::Done) } +/// `value` as indented JSON to print or save, with the terminal controls its +/// strings hold escaped (see [`crate::text::json_safe`]). +pub(crate) fn pretty(value: &impl serde::Serialize) -> serde_json::Result { + serde_json::to_string_pretty(value).map(|json| crate::text::json_safe(&json)) +} + +/// As [`pretty`], on one line. +pub(crate) fn compact(value: &impl serde::Serialize) -> serde_json::Result { + serde_json::to_string(value).map(|json| crate::text::json_safe(&json)) +} + pub(crate) async fn rerun(api: &Api, args: &RerunArgs) -> anyhow::Result { let reply = api.rerun(args.review_id).await?; let id: Uuid = reply diff --git a/tests/http.rs b/tests/http.rs index eb15b98..00e75e8 100644 --- a/tests/http.rs +++ b/tests/http.rs @@ -2158,6 +2158,19 @@ async fn identity_console( kind: &'static str, repository_id: &'static str, status: &'static str, +) -> String { + named_identity_console(id, head, kind, repository_id, status, "production").await +} + +/// As [`identity_console`], with the assessment's environment named +/// `environment`. +async fn named_identity_console( + id: &'static str, + head: &'static str, + kind: &'static str, + repository_id: &'static str, + status: &'static str, + environment: &'static str, ) -> String { let app = Router::new() .route( @@ -2196,7 +2209,7 @@ async fn identity_console( "assessment_count": 1, "assessments": [{ "id": "0190f3a0-0000-7000-8000-0000000000f2", - "environment_display_name": "production", + "environment_display_name": environment, "status": "COMPLETED", "findings": [], "checks": { "receipt_recorded": true, "status": "READY", "families": [] }, @@ -3679,3 +3692,111 @@ async fn config_proposal_targets_must_match_the_selected_organization() { assert_eq!(server.requests()[0]["arguments"]["organization_id"], ORG); assert_eq!(server.frames.load(Ordering::SeqCst), 3); } + +/// Untrusted server text with every kind of terminal control that +/// `serde_json` leaves raw: bidirectional controls, a C1 control (the 8-bit +/// CSI) and DEL, next to a C0 escape it already escapes. +const SPOOF: &str = "fix\u{202e}txt.exe\u{2066}x\u{2069}\u{61c}\u{200f} \u{9b}31m\u{7f}\u{1b}[2J"; + +/// The characters `text::terminal_safe` replaces, other than the newline the +/// pretty printer lays JSON out with. +fn raw_terminal_controls(output: &str) -> Vec { + output + .chars() + .filter(|character| { + (character.is_control() && *character != '\n') + || matches!( + character, + '\u{61c}' | '\u{200e}'..='\u{200f}' | '\u{202a}'..='\u{202e}' | '\u{2066}'..='\u{2069}' + ) + }) + .collect() +} + +/// Commands that print the server's document (`reviews`, `routing`, +/// `fix-prompt`) escape every terminal control left in a JSON string, not +/// only the C0 range `serde_json` escapes, and keep the document's values. +#[tokio::test] +async fn raw_json_commands_escape_terminal_controls_and_keep_the_values() { + let document = json!({ + "items": [{"pull_request_title": SPOOF, "pull_request_author_name": SPOOF}], + "next_cursor": null, + "untrusted_text": SPOOF, + }); + let served = document.clone(); + let app = Router::new().fallback(move || { + let served = served.clone(); + async move { Json(served) } + }); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let origin = format!("http://{}", listener.local_addr().unwrap()); + let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + for args in [ + vec!["reviews"], + vec!["routing", SELECTED_REVIEW], + vec!["fix-prompt", SELECTED_REVIEW], + ] { + let output = cli(&origin, &args).await; + assert!( + output.status.success(), + "{args:?}: {}", + String::from_utf8_lossy(&output.stderr) + ); + let stdout = String::from_utf8(output.stdout).unwrap(); + let raw = raw_terminal_controls(&stdout); + assert!(raw.is_empty(), "{args:?}: {raw:?} reached stdout"); + assert!(stdout.contains(r"\u202e"), "{args:?}: {stdout}"); + assert_eq!( + serde_json::from_str::(&stdout).unwrap(), + document, + "{args:?}" + ); + } + server.abort(); +} + +/// The SARIF file `ci review --sarif` writes escapes the same characters, so +/// opening it in a terminal shows the escapes, and it parses to the +/// environment name the server sent. +#[tokio::test] +async fn ci_review_sarif_file_escapes_terminal_controls_and_keeps_the_values() { + let origin = named_identity_console( + CI_REVIEW, + CI_HEAD, + "PULL_REQUEST", + CI_REPOSITORY, + "COMPLETED", + SPOOF, + ) + .await; + let directory = tempfile::tempdir().unwrap(); + let sarif_path = directory.path().join("proofline.sarif"); + let output = cli_in( + &origin, + &[ + "ci", + "review", + "--repo", + "acme/app", + "--commit", + CI_HEAD, + "--timeout", + "0", + "--sarif", + sarif_path.to_str().unwrap(), + ], + directory.path(), + ) + .await; + let stderr = String::from_utf8_lossy(&output.stderr); + let sarif = std::fs::read_to_string(&sarif_path) + .unwrap_or_else(|error| panic!("no SARIF file ({error}): {stderr}")); + let raw = raw_terminal_controls(&sarif); + assert!(raw.is_empty(), "{raw:?} reached the SARIF file"); + assert!(sarif.contains(r"\u202e"), "{sarif}"); + let document: Value = serde_json::from_str(&sarif).unwrap(); + assert_eq!( + document["runs"][0]["properties"]["assessments"][0]["environment"], SPOOF, + "{sarif}" + ); +} diff --git a/tests/sarif.rs b/tests/sarif.rs index 77fa843..39e8487 100644 --- a/tests/sarif.rs +++ b/tests/sarif.rs @@ -1030,3 +1030,62 @@ async fn sarif_usage_errors_are_rejected_before_reading_a_review() { } assert!(console.requests.lock().unwrap().is_empty()); } + +/// Finding text is untrusted, and `serde_json` escapes only U+0000 to U+001F. +/// JSON and SARIF output therefore write the other characters that +/// `text::terminal_safe` keeps from a terminal (DEL, C1 controls and +/// bidirectional controls) as `\u` escapes, so the document parses to the +/// server's values without those characters reaching the terminal raw. +#[tokio::test] +async fn json_and_sarif_output_escape_terminal_controls_and_keep_the_values() { + const SPOOF: &str = "Safe\u{202e}txt.exe\u{2066}x\u{2069}\u{61c}\u{200f} \u{9b}31m\u{7f}"; + let mut recorded = finding(1, "SERIOUS", vec![code("src/orders.rs", 10, Some(14))]); + recorded["claim"] = json!(SPOOF); + recorded["impact"] = json!(SPOOF); + recorded["remediation"] = json!(SPOOF); + let mut document = review(vec![recorded]); + document["assessments"][0]["environment_display_name"] = json!(SPOOF); + let console = Console::new(document.clone()); + let origin = serve(console.clone()).await; + let schema = schema(); + for format in ["--json", "--sarif"] { + let output = cli( + &origin, + ORG, + TOKEN, + &["findings", "--review", REVIEW, format], + ) + .await; + let stdout = String::from_utf8(output.stdout.clone()).unwrap(); + let raw: Vec = stdout + .chars() + .filter(|character| { + (character.is_control() && *character != '\n') + || matches!( + character, + '\u{61c}' + | '\u{200e}'..='\u{200f}' + | '\u{202a}'..='\u{202e}' + | '\u{2066}'..='\u{2069}' + ) + }) + .collect(); + assert!(raw.is_empty(), "{format}: {raw:?} reached stdout"); + for escape in [ + r"\u202e", r"\u2066", r"\u2069", r"\u061c", r"\u200f", r"\u009b", r"\u007f", + ] { + assert!(stdout.contains(escape), "{format}: no {escape} in {stdout}"); + } + if format == "--json" { + let parsed: Value = serde_json::from_str(&stdout).unwrap(); + assert_eq!(parsed["review"], document); + } else { + let parsed = report(&output, &schema); + assert_eq!( + parsed["runs"][0]["properties"]["assessments"][0]["environment"], + SPOOF + ); + } + } + console.assert_reads(2, ORG); +} From fa2af969193f5aeeecfdc4009caebe17469be69f Mon Sep 17 00:00:00 2001 From: ammartahamohamedy Date: Wed, 2 Dec 2026 18:08:05 +0200 Subject: [PATCH 2/2] Leave JSON whitespace raw in json_safe --- src/text.rs | 25 ++++++++++++++++--------- 1 file changed, 16 insertions(+), 9 deletions(-) diff --git a/src/text.rs b/src/text.rs index 0b45d61..a90c100 100644 --- a/src/text.rs +++ b/src/text.rs @@ -34,20 +34,17 @@ pub fn one_line(text: &str) -> String { terminal_safe(text).replace(['\n', '\t'], " ") } -/// Writes each character [`terminal_safe`] replaces that a serialized JSON -/// document still holds raw as a `\u` escape. `serde_json` escapes only -/// U+0000 to U+001F, so DEL, C1 controls and bidirectional controls in a -/// string would otherwise reach the terminal. Outside its strings a -/// serialized document holds only ASCII punctuation, digits, letters and -/// whitespace, so every such character is inside a string, where the escape -/// decodes to the same character: the document keeps its values. A raw -/// newline is the pretty printer's layout and stays. +/// Writes what [`terminal_safe`] replaces (DEL, C1 and bidirectional controls, +/// which `serde_json` leaves raw) as JSON `\u` escapes, so values are kept. +/// JSON whitespace (space, tab, newline, carriage return) stays as it is. pub fn json_safe(json: &str) -> String { use std::fmt::Write as _; let mut escaped = String::with_capacity(json.len()); for character in json.chars() { - if (character.is_control() && character != '\n') || is_bidi_control(character) { + if (character.is_control() && !matches!(character, '\t' | '\n' | '\r')) + || is_bidi_control(character) + { // Every such character is in the Basic Multilingual Plane, so one // escape holds it. Writing to a `String` cannot fail. let _ = write!(escaped, "\\u{:04x}", u32::from(character)); @@ -129,4 +126,14 @@ mod tests { let json = r#"{"name":"Café — résumé","escaped":"\u001b[2J\n"}"#; assert_eq!(json_safe(json), json); } + + #[test] + fn json_whitespace_between_tokens_stays_raw() { + let json = "{\r\n\t\"a\" :\t[1,\r\n 2]\n}"; + assert_eq!(json_safe(json), json); + assert_eq!( + serde_json::from_str::(&json_safe(json)).unwrap(), + serde_json::json!({"a": [1, 2]}) + ); + } }