diff --git a/README.md b/README.md index eea0165..183d9fa 100644 --- a/README.md +++ b/README.md @@ -34,7 +34,7 @@ Native knowledge, plan, fix and configuration commands send the selected organiz ## Reviews, history, and reruns -`proofline review --path src/main.rs` reviews only that file's local changes against the normal merge-base. The path is literal and repository-relative; the command refuses directories, globs, and `..`. Combine it with `--staged` to read the index, or `--include-untracked` to select a new, non-ignored file. The command preserves the real index and applies the usual secret preflight. You cannot combine `--path` with pushed-commit, range, or pull-request review. +`proofline review --path src/main.rs` reviews only that file's local changes against the normal merge-base. The path is literal and repository-relative; the command refuses directories, globs, and `..`. Combine it with `--staged` to read the index, or `--include-untracked` to select a new, non-ignored file. The command preserves the real index and applies the usual local preflight: sensitive paths and credential-shaped content are refused, as are hidden bidirectional controls, Unicode tags, selected zero-width characters, and consecutive variation selectors. You cannot combine `--path` with pushed-commit, range, or pull-request review. `proofline reviews --repository-id UUID --cursor CURSOR` returns one page with its continuation metadata, and all flags are optional. `proofline routing REVIEW_ID` reads recorded routing. `proofline run --repo owner/name --pr 7 --run 2` reads one retained run, and `proofline history --repo owner/name --pr 7` reads all recorded runs. Both commands send the API the name without its owner, and use the response only when its repository choices list `owner/name`, or the Git remote's owner and name, among the organization's reviewed repositories. A repository with no reviews in the organization exits nonzero. `proofline findings --pr 7` finds the pull request's newest review through the same route and counts only runs of the repository whose full name matches. None of these commands reads the organization's review list. diff --git a/src/agent/config.rs b/src/agent/config.rs index 43b20c6..ed5a569 100644 --- a/src/agent/config.rs +++ b/src/agent/config.rs @@ -57,8 +57,11 @@ fn arguments(origin: &Origin) -> [String; 3] { } fn executable() -> Result { - std::env::current_exe() + let executable = std::env::current_exe() .map_err(InstallError::Executable)? + .canonicalize() + .map_err(InstallError::Executable)?; + executable .into_os_string() .into_string() .map_err(|_| InstallError::ExecutableEncoding) diff --git a/src/agent/tests.rs b/src/agent/tests.rs index 8a67e1d..0729b4f 100644 --- a/src/agent/tests.rs +++ b/src/agent/tests.rs @@ -109,7 +109,12 @@ fn configuration(client: Client) -> Vec { fn assert_new_server(client: Client, server: &Value, selected_origin: &str) { assert_eq!( server["command"], - std::env::current_exe().unwrap().to_str().unwrap() + std::env::current_exe() + .unwrap() + .canonicalize() + .unwrap() + .to_str() + .unwrap() ); assert_eq!( server["args"], @@ -177,7 +182,11 @@ fn all_clients_preserve_private_settings_and_add_only_the_launcher() { .unwrap(); assert_eq!( server["command"].as_str(), - std::env::current_exe().unwrap().to_str() + std::env::current_exe() + .unwrap() + .canonicalize() + .unwrap() + .to_str() ); assert_eq!( server["args"] diff --git a/src/annotations.rs b/src/annotations.rs index bf62f73..07efda9 100644 --- a/src/annotations.rs +++ b/src/annotations.rs @@ -92,5 +92,7 @@ mod tests { ); assert_eq!(escape_property("a:b,c%\nd"), "a%3Ab%2Cc%25%0Ad"); assert_eq!(escape_data("ok\u{1b}[2J"), "ok\u{FFFD}[2J"); + assert_eq!(escape_data("rule\u{e0049}"), "rule"); + assert_eq!(escape_data("ok\u{e0100}\u{e0101}"), "ok"); } } diff --git a/src/preflight.rs b/src/preflight.rs index 592ec54..95bad39 100644 --- a/src/preflight.rs +++ b/src/preflight.rs @@ -1,6 +1,9 @@ //! Local refusals before any patch bytes leave the checkout. -use crate::git::{LocalChanges, PatchPaths}; +use crate::{ + git::{LocalChanges, PatchPaths}, + text, +}; #[derive(Debug, thiserror::Error)] pub(crate) enum PreflightError { @@ -21,6 +24,16 @@ pub(crate) enum PreflightError { coordinate: &'static str, kind: &'static str, }, + #[error( + "local patch contains {kind} U+{codepoint:04X} at {path:?}:{line} ({coordinate}); remove it before upload" + )] + StealthUnicode { + path: String, + line: usize, + coordinate: &'static str, + kind: text::StealthKind, + codepoint: u32, + }, #[error("could not map the local patch to file paths and lines; no review was requested")] InvalidPatch, } @@ -43,6 +56,7 @@ pub(crate) fn check(changes: &LocalChanges, allowed: &[String]) -> Result<(), Pr for (patch_line, line) in changes.patch.lines().enumerate() { if line.starts_with("diff --git ") { let file = paths.next().ok_or(PreflightError::InvalidPatch)?; + new_path_stealth(file, patch_line + 1)?; environment_paths(file, allowed)?; current = Some(file); hunk = None; @@ -58,6 +72,7 @@ pub(crate) fn check(changes: &LocalChanges, allowed: &[String]) -> Result<(), Pr "patch line", line, allowed, + false, )?; hunk = Some(hunk_lines(line)?); } else if let Some(lines) = &mut hunk { @@ -86,6 +101,24 @@ fn environment_paths(file: &PatchPaths, allowed: &[String]) -> Result<(), Prefli Ok(()) } +/// A new path reaches the remote with the patch. Old-only paths are deletions +/// and must remain removable even when they contain a hidden character. +fn new_path_stealth(file: &PatchPaths, patch_line: usize) -> Result<(), PreflightError> { + let Some(path) = file.new.as_deref() else { + return Ok(()); + }; + let Some((kind, character)) = text::stealth(path) else { + return Ok(()); + }; + Err(PreflightError::StealthUnicode { + path: text::one_line(path), + line: patch_line, + coordinate: "path", + kind, + codepoint: character as u32, + }) +} + fn hunk_lines(line: &str) -> Result { let mut fields = line.split_whitespace(); if fields.next() != Some("@@") { @@ -118,10 +151,24 @@ fn inspect_hunk( allowed: &[String], ) -> Result<(), PreflightError> { if let Some(text) = line.strip_prefix('+') { - inspect(file.new.as_deref(), lines.new, "new line", text, allowed)?; + inspect( + file.new.as_deref(), + lines.new, + "new line", + text, + allowed, + true, + )?; lines.new = next_line(lines.new)?; } else if let Some(text) = line.strip_prefix('-') { - inspect(file.old.as_deref(), lines.old, "base line", text, allowed)?; + inspect( + file.old.as_deref(), + lines.old, + "base line", + text, + allowed, + false, + )?; lines.old = next_line(lines.old)?; } else if let Some(text) = line.strip_prefix(' ') { inspect( @@ -130,6 +177,7 @@ fn inspect_hunk( "new line", text, allowed, + false, )?; lines.old = next_line(lines.old)?; lines.new = next_line(lines.new)?; @@ -149,6 +197,7 @@ fn inspect( coordinate: &'static str, text: &str, allowed: &[String], + inspect_stealth: bool, ) -> Result<(), PreflightError> { let path = path.ok_or(PreflightError::InvalidPatch)?; if !is_allowed(path, allowed) @@ -161,6 +210,15 @@ fn inspect( kind, }); } + if inspect_stealth && let Some((kind, character)) = text::stealth(text) { + return Err(PreflightError::StealthUnicode { + path: text::one_line(path), + line, + coordinate, + kind, + codepoint: character as u32, + }); + } Ok(()) } diff --git a/src/sarif.rs b/src/sarif.rs index 4d30667..4452c7d 100644 --- a/src/sarif.rs +++ b/src/sarif.rs @@ -8,6 +8,7 @@ use uuid::Uuid; use crate::model::{Assessment, CodeAssessment, EvidenceRef, Finding, ReviewDetail}; use crate::outcome::{self, Outcome}; +use crate::text; const SCHEMA: &str = "https://docs.oasis-open.org/sarif/sarif/v2.1.0/errata01/os/schemas/sarif-schema-2.1.0.json"; @@ -317,7 +318,7 @@ pub(super) fn validate_subject(detail: &ReviewDetail, requested: Uuid) -> Result if detail.kind != "PULL_REQUEST" { return Err(SarifError::UnsupportedSubject { review: detail.id, - kind: crate::text::one_line(&detail.kind), + kind: text::one_line(&detail.kind), }); } if !detail.head_commit_sha.as_deref().is_some_and(|head| { @@ -485,7 +486,7 @@ fn finding_result<'a>( _ => { return Err(SarifError::UnsupportedSeverity { finding: finding.id, - severity: crate::text::one_line(&finding.severity), + severity: text::one_line(&finding.severity), }); } }; @@ -510,7 +511,7 @@ fn finding_result<'a>( .position(|&domain| domain == finding.risk_domain) .ok_or_else(|| SarifError::UnsupportedDomain { finding: finding.id, - domain: crate::text::one_line(&finding.risk_domain), + domain: text::one_line(&finding.risk_domain), })?; let mut locations = Vec::new(); let mut seen = BTreeSet::new(); @@ -640,6 +641,7 @@ fn valid_path(path: &str) -> bool { ch.is_control() || matches!(ch, '\\' | ':' | '\u{200e}' | '\u{200f}' | '\u{202a}'..='\u{202e}' | '\u{2066}'..='\u{2069}') }) + && text::stealth(path).is_none() } fn path_uri(path: &str) -> String { @@ -656,3 +658,17 @@ fn path_uri(path: &str) -> String { } uri } + +#[cfg(test)] +mod tests { + use super::valid_path; + + #[test] + fn paths_reject_hidden_unicode_but_keep_visible_unicode() { + assert!(valid_path("src/résumé.rs")); + assert!(valid_path("src/warning\u{fe0f}.rs")); + assert!(!valid_path("src/\u{e0041}auth.rs")); + assert!(!valid_path("src/auth\u{200b}.rs")); + assert!(!valid_path("src/code\u{e0100}\u{e0101}.rs")); + } +} diff --git a/src/text.rs b/src/text.rs index 6fbdb4c..ea12804 100644 --- a/src/text.rs +++ b/src/text.rs @@ -2,6 +2,28 @@ //! output and repository content, which is untrusted, so control characters //! that could move the cursor or rewrite earlier lines never reach the terminal. +use std::fmt::Write as _; + +/// A non-rendering character sequence that can conceal content from a reviewer. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum StealthKind { + BidiControl, + UnicodeTag, + ZeroWidth, + VariationSelectorRun, +} + +impl std::fmt::Display for StealthKind { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str(match self { + Self::BidiControl => "bidirectional control", + Self::UnicodeTag => "Unicode tag", + Self::ZeroWidth => "zero-width character", + Self::VariationSelectorRun => "variation-selector run", + }) + } +} + /// Returns whether a character is a Unicode bidirectional formatting control. fn is_bidi_control(character: char) -> bool { matches!( @@ -13,20 +35,95 @@ fn is_bidi_control(character: char) -> bool { ) } +fn is_unicode_tag(character: char) -> bool { + matches!(character as u32, 0xE0000..=0xE007F) +} + +fn is_zero_width(character: char) -> bool { + matches!( + character as u32, + 0x00AD | 0x034F | 0x180E | 0x200B | 0x2060 | 0xFEFF + ) +} + +fn is_variation_selector(character: char) -> bool { + matches!(character as u32, 0xFE00..=0xFE0F | 0xE0100..=0xE01EF) +} + +fn direct_stealth_kind(character: char) -> Option { + if is_bidi_control(character) { + Some(StealthKind::BidiControl) + } else if is_unicode_tag(character) { + Some(StealthKind::UnicodeTag) + } else if is_zero_width(character) { + Some(StealthKind::ZeroWidth) + } else { + None + } +} + +/// The first character from a sequence that hides or visually reorders text. +/// +/// A single variation selector is legitimate in emoji and ideographic text. A +/// consecutive run has no such normal rendering purpose and is the encoding +/// shape used to carry arbitrary bytes in invisible-selector attacks. +pub(crate) fn stealth(text: &str) -> Option<(StealthKind, char)> { + let mut characters = text.chars().peekable(); + while let Some(character) = characters.next() { + if let Some(kind) = direct_stealth_kind(character) { + return Some((kind, character)); + } + if is_variation_selector(character) { + let mut count = 1; + while characters + .next_if(|next| is_variation_selector(*next)) + .is_some() + { + count += 1; + } + if count >= 2 { + return Some((StealthKind::VariationSelectorRun, character)); + } + } + } + None +} + +fn visible_codepoint(output: &mut String, character: char) { + // Writing the scalar value, rather than the original character, gives a + // reviewer an unambiguous representation without replaying hidden text. + write!(output, "", character as u32).expect("writing to String cannot fail"); +} + /// Replaces every control character except a newline and a tab. pub fn terminal_safe(text: &str) -> String { - text.chars() - .map(|character| { - if (character.is_control() || is_bidi_control(character)) - && character != '\n' - && character != '\t' - { - '\u{FFFD}' + let mut output = String::with_capacity(text.len()); + let mut characters = text.chars().peekable(); + while let Some(character) = characters.next() { + if is_variation_selector(character) { + let mut selectors = String::from(character); + while let Some(next) = characters.next_if(|next| is_variation_selector(*next)) { + selectors.push(next); + } + if selectors.chars().count() >= 2 { + for selector in selectors.chars() { + visible_codepoint(&mut output, selector); + } } else { - character + output.push(character); } - }) - .collect() + } else if (character.is_control() || is_bidi_control(character)) + && character != '\n' + && character != '\t' + { + output.push('\u{FFFD}'); + } else if is_unicode_tag(character) || is_zero_width(character) { + visible_codepoint(&mut output, character); + } else { + output.push(character); + } + } + output } /// As [`terminal_safe`], on one line. @@ -71,4 +168,32 @@ mod tests { fn ordinary_unicode_is_preserved() { assert_eq!(terminal_safe("Café — résumé"), "Café — résumé"); } + + #[test] + fn hidden_unicode_is_classified_without_rejecting_an_emoji_selector() { + assert_eq!( + stealth("rule\u{e0049}"), + Some((StealthKind::UnicodeTag, '\u{e0049}')) + ); + assert_eq!( + stealth("file\u{200b}name"), + Some((StealthKind::ZeroWidth, '\u{200b}')) + ); + assert_eq!( + stealth("ok\u{e0100}\u{e0101}"), + Some((StealthKind::VariationSelectorRun, '\u{e0100}')) + ); + assert_eq!(stealth("warning\u{fe0f}"), None); + } + + #[test] + fn hidden_unicode_is_visible_in_terminal_output() { + assert_eq!(terminal_safe("rule\u{e0049}"), "rule"); + assert_eq!(terminal_safe("file\u{200b}name"), "filename"); + assert_eq!( + terminal_safe("ok\u{e0100}\u{e0101}"), + "ok" + ); + assert_eq!(terminal_safe("warning\u{fe0f}"), "warning\u{fe0f}"); + } } diff --git a/tests/hooks.rs b/tests/hooks.rs index 3473f84..c41b745 100644 --- a/tests/hooks.rs +++ b/tests/hooks.rs @@ -505,6 +505,40 @@ async fn the_exit_policy_blocks_only_on_request_and_never_reads_a_gap_as_clean() assert!(staged.contains("+fn main() { retry() }")); } +#[tokio::test] +async fn hooks_refuse_hidden_unicode_before_a_patch_upload() { + let checkout = Checkout::new().await; + let uploads = Uploads::default(); + let origin = serve(uploads.clone(), "SERIOUS", false).await; + let hidden = "\u{e0049}"; + tokio::fs::write( + checkout.root().join("orders.rs"), + format!("fn main() {{ /* rule{hidden} */ }}\n"), + ) + .await + .unwrap(); + checkout.git(&["add", "orders.rs"]).await; + + let run = ["hook", "run", "pre-commit"]; + let warning = checkout.proofline(&origin, &run, "").await; + let warning_text = stderr(&warning); + assert_eq!(warning.status.code(), Some(0), "{warning_text}"); + assert!( + warning_text.contains("Unicode tag U+E0049"), + "{warning_text}" + ); + assert!(!warning_text.contains(hidden), "{warning_text}"); + assert!(uploads.lock().unwrap().is_empty()); + + checkout + .git(&["config", "proofline.hook.pre-commit.onIncomplete", "block"]) + .await; + let blocked = checkout.proofline(&origin, &run, "").await; + assert_eq!(blocked.status.code(), Some(1), "{}", stderr(&blocked)); + assert!(stderr(&blocked).contains("no complete review")); + assert!(uploads.lock().unwrap().is_empty()); +} + #[tokio::test] async fn only_a_complete_review_prints_no_findings() { let checkout = Checkout::new().await; diff --git a/tests/local_patch.rs b/tests/local_patch.rs index 6da45f8..70061a6 100644 --- a/tests/local_patch.rs +++ b/tests/local_patch.rs @@ -927,6 +927,62 @@ async fn local_path_refuses_directory_glob_and_traversal_before_http() { server.close().await; } +#[tokio::test] +async fn added_hidden_unicode_refuses_before_http_without_echoing_it() { + for (hidden, diagnostic) in [ + ("\u{202e}", "bidirectional control U+202E"), + ("\u{e0049}", "Unicode tag U+E0049"), + ("\u{200b}", "zero-width character U+200B"), + ("\u{e0100}\u{e0101}", "variation-selector run U+E0100"), + ] { + let checkout = Checkout::new(&[("rules.md", "base\n")]).await; + checkout + .write("rules.md", &format!("keep this rule{hidden}\n")) + .await; + let server = Server::start(true).await; + let output = checkout.review(&server, &[], &[]).await; + let stderr = String::from_utf8_lossy(&output.stderr); + assert_eq!(output.status.code(), Some(1), "{stderr}"); + assert!(stderr.contains(diagnostic), "{stderr}"); + assert!(!stderr.contains(hidden), "{stderr}"); + server.assert_no_requests(); + server.close().await; + } +} + +#[tokio::test] +async fn removing_hidden_unicode_is_not_blocked() { + let checkout = Checkout::new(&[("rules.md", "keep this rule\u{e0049}\n")]).await; + checkout.write("rules.md", "keep this rule\n").await; + let server = Server::start(true).await; + let output = checkout.review(&server, &[], &[]).await; + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + assert_eq!(server.fixture.uploads.lock().unwrap().len(), 1); + server.close().await; +} + +#[tokio::test] +async fn hidden_unicode_in_a_new_path_refuses_before_http() { + let checkout = Checkout::new(&[]).await; + let path = "rules\u{e0049}.md"; + checkout.write(path, "ordinary text\n").await; + let server = Server::start(true).await; + let output = checkout + .review(&server, &[], &["--include-untracked"]) + .await; + let stderr = String::from_utf8_lossy(&output.stderr); + assert_eq!(output.status.code(), Some(1), "{stderr}"); + assert!(stderr.contains("Unicode tag U+E0049"), "{stderr}"); + assert!(stderr.contains("rules.md"), "{stderr}"); + assert!(!stderr.contains(path), "{stderr}"); + server.assert_no_requests(); + server.close().await; +} + #[tokio::test] async fn local_path_keeps_secret_preflight_and_can_select_a_deleted_file() { let checkout = Checkout::new(&[("selected.txt", "base\n"), ("other.txt", "base\n")]).await;