Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/coverage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
2 changes: 1 addition & 1 deletion src/deploy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)?;
Expand Down
14 changes: 7 additions & 7 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -479,7 +479,7 @@ pub async fn run(cli: Cli, token: Option<SecretString>) -> anyhow::Result<Verdic
{
let document = result::schema()?;
let mut stdout = std::io::stdout().lock();
writeln!(stdout, "{}", serde_json::to_string_pretty(&document)?)?;
writeln!(stdout, "{}", tools::pretty(&document)?)?;
return Ok(Verdict::Done);
}
match &cli.command {
Expand Down Expand Up @@ -596,7 +596,7 @@ pub async fn run(cli: Cli, token: Option<SecretString>) -> anyhow::Result<Verdic
let (raw, stopped) = api.stop_review(args.review_id).await?;
let mut stdout = std::io::stdout().lock();
if args.json {
writeln!(stdout, "{}", serde_json::to_string(&raw)?)?;
writeln!(stdout, "{}", tools::compact(&raw)?)?;
} else {
writeln!(stdout, "Stopped review {}.", stopped.review_id)?;
}
Expand Down Expand Up @@ -1312,7 +1312,7 @@ async fn finish(api: &Api, review_id: Uuid, args: &ReviewArgs) -> 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}")?;
}
Expand Down Expand Up @@ -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()))
}
Expand Down Expand Up @@ -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 => {
Expand Down Expand Up @@ -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(
Expand All @@ -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!(
Expand Down
65 changes: 65 additions & 0 deletions src/text.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,27 @@ pub fn one_line(text: &str) -> String {
terminal_safe(text).replace(['\n', '\t'], " ")
}

/// 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() && !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));
} else {
escaped.push(character);
}
}
escaped
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down Expand Up @@ -71,4 +92,48 @@ 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::<serde_json::Value>(&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);
}

#[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::<serde_json::Value>(&json_safe(json)).unwrap(),
serde_json::json!({"a": [1, 2]})
);
}
}
17 changes: 12 additions & 5 deletions src/tools.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,14 +86,21 @@ pub(crate) struct ExportArgs {
}

pub(crate) fn json(value: &serde_json::Value) -> anyhow::Result<Verdict> {
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<String> {
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<String> {
serde_json::to_string(value).map(|json| crate::text::json_safe(&json))
}

pub(crate) async fn rerun(api: &Api, args: &RerunArgs) -> anyhow::Result<Verdict> {
let reply = api.rerun(args.review_id).await?;
let id: Uuid = reply
Expand Down
123 changes: 122 additions & 1 deletion tests/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -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": [] },
Expand Down Expand Up @@ -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<char> {
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::<Value>(&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}"
);
}
59 changes: 59 additions & 0 deletions tests/sarif.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<char> = 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);
}