From 664806992ed4b56b3b95fbd1f19409cdc5b31706 Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Mon, 9 Nov 2026 10:40:37 +0100 Subject: [PATCH] fix(scan): read UTF-16 and Windows-1252 files in the remaining readers (t84) The t84 audit found five readers that still skipped a file silently when it was not UTF-8: the GDPR/OAuth pattern scanner, the content fingerprints of findings, the control-check surface retrieval, the PR review diff and the Werkbank PLC program reader. They now decode as the code graph does: BOM, then UTF-8, then Windows-1252. The decoder moves from compliance-graph to compliance-core, so the Werkbank runner uses it without pulling in the graph crate. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 2 +- compliance-agent/src/api/handlers/graph.rs | 2 +- compliance-agent/src/controls/scan_triage.rs | 2 +- compliance-agent/src/controls/surface.rs | 21 ++++++++- compliance-agent/src/llm/triage.rs | 2 +- compliance-agent/src/pipeline/dotnet/mod.rs | 4 +- .../src/pipeline/embedded_versions.rs | 2 +- .../src/pipeline/finding_store.rs | 23 ++++++++- compliance-agent/src/pipeline/git.rs | 47 ++++++++++++++++++- compliance-agent/src/pipeline/patterns.rs | 40 ++++++++++++++-- compliance-agent/src/pipeline/plc/mod.rs | 6 +-- compliance-agent/src/pipeline/source_text.rs | 4 +- compliance-core/Cargo.toml | 2 + .../src/encoding.rs | 22 +++++++-- compliance-core/src/lib.rs | 1 + compliance-graph/Cargo.toml | 2 - compliance-graph/src/graph/chunking.rs | 2 +- compliance-graph/src/lib.rs | 1 - compliance-graph/src/parsers/registry.rs | 4 +- werkbank-exec/src/plc/mod.rs | 17 ++++++- 20 files changed, 178 insertions(+), 28 deletions(-) rename {compliance-graph => compliance-core}/src/encoding.rs (90%) diff --git a/Cargo.lock b/Cargo.lock index fc18742..3238ca6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -662,6 +662,7 @@ dependencies = [ "base64 0.22.1", "bson", "chrono", + "encoding_rs", "hex", "jsonschema", "jsonwebtoken", @@ -749,7 +750,6 @@ dependencies = [ "bson", "chrono", "compliance-core", - "encoding_rs", "futures-util", "mongodb", "petgraph", diff --git a/compliance-agent/src/api/handlers/graph.rs b/compliance-agent/src/api/handlers/graph.rs index 0ff79e6..2f1899c 100644 --- a/compliance-agent/src/api/handlers/graph.rs +++ b/compliance-agent/src/api/handlers/graph.rs @@ -413,7 +413,7 @@ pub async fn get_file_content( // Decoded as the graph read it, so a UTF-16 or Windows-1252 file opens. let content = - compliance_graph::encoding::read_source(&canonical).map_err(|_| StatusCode::NOT_FOUND)?; + compliance_core::encoding::read_source(&canonical).map_err(|_| StatusCode::NOT_FOUND)?; // Cap at 10,000 lines let truncated: String = content.lines().take(10_000).collect::>().join("\n"); diff --git a/compliance-agent/src/controls/scan_triage.rs b/compliance-agent/src/controls/scan_triage.rs index 2969c0f..f7bf44a 100644 --- a/compliance-agent/src/controls/scan_triage.rs +++ b/compliance-agent/src/controls/scan_triage.rs @@ -215,7 +215,7 @@ pub async fn grounded_surface_findings( /// Read a window of lines around `line` (1-based) from `repo_path/file`. fn fetch_region(repo_path: &Path, file: &str, line: u32) -> Option { - let content = compliance_graph::encoding::read_source(&repo_path.join(file)).ok()?; + let content = compliance_core::encoding::read_source(&repo_path.join(file)).ok()?; let lines: Vec<&str> = content.lines().collect(); if lines.is_empty() { return None; diff --git a/compliance-agent/src/controls/surface.rs b/compliance-agent/src/controls/surface.rs index 11865da..afa2289 100644 --- a/compliance-agent/src/controls/surface.rs +++ b/compliance-agent/src/controls/surface.rs @@ -156,7 +156,8 @@ pub fn retrieve(repo_path: &Path, terms: &[&str], excluded: &[String]) -> Vec MAX_FILE_BYTES { continue; } - let Ok(content) = std::fs::read_to_string(path) else { + // UTF-8, UTF-16 with a BOM, or Windows-1252; a binary is skipped. + let Ok(content) = compliance_core::encoding::read_source(path) else { continue; }; let rel = path @@ -286,6 +287,24 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + #[test] + fn a_windows_1252_file_is_read() { + let dir = std::env::temp_dir().join(format!("surface-{}", uuid::Uuid::new_v4())); + std::fs::create_dir_all(&dir).unwrap(); + // "Prüfung" as Windows-1252 writes it: 0xFC for "ü". + let path = dir.join("app/Auth.cs"); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write( + &path, + b"// Pr\xFCfung\nbool Login(string u, string p) { }\n", + ) + .unwrap(); + let regions = retrieve(&dir, terms_for("cra-ai-11"), &[]); + let _ = std::fs::remove_dir_all(&dir); + assert_eq!(regions.len(), 1); + assert!(regions[0].content.contains("Prüfung")); + } + #[test] fn firmware_update_code_is_read_but_not_the_vendor_hal() { let dir = std::env::temp_dir().join(format!("surface-{}", uuid::Uuid::new_v4())); diff --git a/compliance-agent/src/llm/triage.rs b/compliance-agent/src/llm/triage.rs index 3546de8..61c1996 100644 --- a/compliance-agent/src/llm/triage.rs +++ b/compliance-agent/src/llm/triage.rs @@ -861,7 +861,7 @@ fn read_surrounding_context(finding: &Finding) -> Option { let line = finding.line_number? as usize; // Try to read the file — this works because the repo is cloned locally - let content = compliance_graph::encoding::read_source(std::path::Path::new(file_path)).ok()?; + let content = compliance_core::encoding::read_source(std::path::Path::new(file_path)).ok()?; let lines: Vec<&str> = content.lines().collect(); let start = line.saturating_sub(25); diff --git a/compliance-agent/src/pipeline/dotnet/mod.rs b/compliance-agent/src/pipeline/dotnet/mod.rs index 92b59d4..8943da8 100644 --- a/compliance-agent/src/pipeline/dotnet/mod.rs +++ b/compliance-agent/src/pipeline/dotnet/mod.rs @@ -146,14 +146,14 @@ pub(crate) fn relative(root: &Path, path: &Path) -> String { /// The text of a file that may start with a byte-order mark (Visual Studio /// writes UTF-8 with BOM, older tools UTF-16) or be Windows-1252, decoded by -/// [`compliance_graph::encoding::read_source`]. `None` for a file too large or +/// [`compliance_core::encoding::read_source`]. `None` for a file too large or /// unreadable. pub(crate) fn read_text(path: &Path) -> Option { let meta = std::fs::metadata(path).ok()?; if meta.len() > MAX_FILE_BYTES { return None; } - compliance_graph::encoding::read_source(path).ok() + compliance_core::encoding::read_source(path).ok() } /// Parse XML the way project and configuration files need: a DTD is allowed diff --git a/compliance-agent/src/pipeline/embedded_versions.rs b/compliance-agent/src/pipeline/embedded_versions.rs index 5f6b956..c3a764d 100644 --- a/compliance-agent/src/pipeline/embedded_versions.rs +++ b/compliance-agent/src/pipeline/embedded_versions.rs @@ -148,7 +148,7 @@ pub fn detect(root: &Path, repo_id: &str) -> Vec { let small = entry.metadata().is_ok_and(|m| m.len() <= MAX_HEADER_BYTES); let Some(text) = small // Vendor SDK headers are often Windows-1252 (a "©" in the banner). - .then(|| compliance_graph::encoding::read_source(entry.path()).ok()) + .then(|| compliance_core::encoding::read_source(entry.path()).ok()) .flatten() else { continue; diff --git a/compliance-agent/src/pipeline/finding_store.rs b/compliance-agent/src/pipeline/finding_store.rs index c9229dc..3a8a3f7 100644 --- a/compliance-agent/src/pipeline/finding_store.rs +++ b/compliance-agent/src/pipeline/finding_store.rs @@ -973,7 +973,8 @@ fn content_fingerprints(tree: &Path, findings: &mut [Finding]) { continue; }; let lines = files.entry(path.clone()).or_insert_with(|| { - std::fs::read_to_string(tree.join(&path)) + // Decoded like the scanners read it: UTF-8, UTF-16, Windows-1252. + compliance_core::encoding::read_source(&tree.join(&path)) .ok() .map(|text| text.lines().map(normalised).collect()) }); @@ -1249,6 +1250,26 @@ mod tests { assert!(missing[0].legacy_fingerprints.is_empty()); } + #[test] + fn a_windows_1252_file_is_keyed_by_content_as_its_utf8_version_is() { + let dir = std::env::temp_dir().join(format!("cs-fp-{}", uuid::Uuid::new_v4())); + std::fs::create_dir_all(&dir).unwrap(); + // "größe" as Windows-1252 writes it (0xF6 0xDF), then the same file + // saved again as UTF-8. + std::fs::write(dir.join("a.c"), b"int x;\nint gr\xF6\xDFe = read();\n").unwrap(); + let ansi = keyed(&dir, vec![at("a.c", 2)]); + std::fs::write(dir.join("a.c"), "int x;\nint größe = read();\n").unwrap(); + let utf8 = keyed(&dir, vec![at("a.c", 2)]); + let _ = std::fs::remove_dir_all(&dir); + // Keyed by content, with the line-based key kept to adopt the row + // stored under it while the file could not be read. + let line_key = crate::pipeline::dedup::compute_fingerprint(&["repo-1", "rule", "a.c", "2"]); + assert_eq!(ansi[0].legacy_fingerprints, std::slice::from_ref(&line_key)); + assert_ne!(ansi[0].fingerprint, line_key); + // Re-saving the file in another encoding keeps the key. + assert_eq!(ansi[0].fingerprint, utf8[0].fingerprint); + } + #[test] fn a_scanners_own_content_and_groups_are_respected() { let dir = std::env::temp_dir().join(format!("cs-fp-{}", uuid::Uuid::new_v4())); diff --git a/compliance-agent/src/pipeline/git.rs b/compliance-agent/src/pipeline/git.rs index 2b63130..08a7b47 100644 --- a/compliance-agent/src/pipeline/git.rs +++ b/compliance-agent/src/pipeline/git.rs @@ -495,7 +495,18 @@ impl GitOps { _ => "", }; - let content = std::str::from_utf8(line.content()).unwrap_or(""); + // A diff line is UTF-8 or, from an older tool, Windows-1252 + // (single-byte, so a line decodes on its own). UTF-16 files are + // binary to git and have no lines here. + let bytes = line.content(); + let decoded; + let content = match std::str::from_utf8(bytes) { + Ok(text) => text, + Err(_) => { + decoded = compliance_core::encoding::decode(bytes.to_vec()).unwrap_or_default(); + decoded.as_str() + } + }; diff_file.hunks.push_str(prefix); diff_file.hunks.push_str(content); @@ -919,4 +930,38 @@ mod tests { .expect_err("private origin must be refused"); assert!(err.to_string().contains("10.0.0.5"), "{err}"); } + + #[test] + fn a_windows_1252_line_shows_in_the_diff() { + // Arrange: a file committed, then a line with "für" as Windows-1252 + // writes it (0xFC) added in a second commit. + let dir = source_repo(); + let repo = git2::Repository::open(&dir).unwrap(); + let old = repo.head().unwrap().peel_to_commit().unwrap(); + std::fs::write( + dir.join("README.md"), + b"pump controller\n// f\xFCr Halle 2\n", + ) + .unwrap(); + let mut index = repo.index().unwrap(); + index.add_path(Path::new("README.md")).unwrap(); + index.write().unwrap(); + let tree = repo.find_tree(index.write_tree().unwrap()).unwrap(); + let sig = git2::Signature::now("t", "t@example.com").unwrap(); + let new = repo + .commit(Some("HEAD"), &sig, &sig, "note", &tree, &[&old]) + .unwrap(); + + // Act + let diff = GitOps::get_diff_content(&dir, &old.id().to_string(), &new.to_string()).unwrap(); + std::fs::remove_dir_all(&dir).unwrap(); + + // Assert: the added line is there, decoded. + assert_eq!(diff.len(), 1); + assert!( + diff[0].hunks.contains("+// für Halle 2"), + "{}", + diff[0].hunks + ); + } } diff --git a/compliance-agent/src/pipeline/patterns.rs b/compliance-agent/src/pipeline/patterns.rs index bede7f9..1d6c16a 100644 --- a/compliance-agent/src/pipeline/patterns.rs +++ b/compliance-agent/src/pipeline/patterns.rs @@ -186,9 +186,17 @@ fn scan_with_patterns( .unwrap_or("") .to_string(); - let content = match std::fs::read_to_string(path) { - Ok(c) => c, - Err(_) => continue, // skip binary files + // Only files a pattern looks at are read at all. + if !patterns.iter().any(|p| p.file_extensions.contains(&ext)) { + continue; + } + // UTF-8, UTF-16 with a BOM, or Windows-1252; a binary is skipped. + let content = match compliance_core::encoding::read_source(path) { + Ok(text) => text, + Err(error) => { + tracing::debug!(file = %path.display(), %error, "pattern scan: file not readable"); + continue; + } }; let relative_path = path @@ -417,4 +425,30 @@ mod tests { assert!(!pattern.file_extensions.contains(&"rs".to_string())); assert!(!pattern.file_extensions.contains(&"py".to_string())); } + + // --- file decoding --- + + #[test] + fn a_windows_1252_file_is_scanned_not_skipped() { + // Arrange: a C# file written by an older tool, "Größe" as 0xF6 0xDF. + let dir = std::env::temp_dir().join(format!("cs-pat-{}", uuid::Uuid::new_v4())); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("Log.cs"), b"// Gr\xF6\xDFe\nLog(email);\n").unwrap(); + let rule = PatternRule { + id: "pii".into(), + title: "t".into(), + description: "d".into(), + pattern: compile_regex(r"Log\(email\)"), + severity: Severity::Medium, + file_extensions: vec!["cs".into()], + }; + + // Act + let findings = scan_with_patterns(&dir, "repo", &[rule], ScanType::Gdpr, "t").unwrap(); + let _ = std::fs::remove_dir_all(&dir); + + // Assert: found on its line. + assert_eq!(findings.len(), 1); + assert_eq!(findings[0].line_number, Some(2)); + } } diff --git a/compliance-agent/src/pipeline/plc/mod.rs b/compliance-agent/src/pipeline/plc/mod.rs index 6095fab..c1b7b51 100644 --- a/compliance-agent/src/pipeline/plc/mod.rs +++ b/compliance-agent/src/pipeline/plc/mod.rs @@ -60,7 +60,7 @@ pub(crate) struct PlcFile { /// Read every PLC source file under `root` (Structured Text, and PLCopen XML /// exports) into its POUs. Files with no POU are left out. /// -/// Each file is decoded by [`compliance_graph::encoding::read_source`]: +/// Each file is decoded by [`compliance_core::encoding::read_source`]: /// CODESYS and TIA exports are often Windows-1252 or UTF-16. Files still not /// readable as text are logged as one warning per tree. pub(crate) fn read_tree(root: &Path) -> Vec { @@ -84,7 +84,7 @@ pub(crate) fn read_tree(root: &Path) -> Vec { if !is_st && !is_xml { continue; } - let content = match compliance_graph::encoding::read_source(path) { + let content = match compliance_core::encoding::read_source(path) { Ok(text) => text, Err(error) => { // A binary `.project` is CODESYS's native format, which @@ -210,7 +210,7 @@ pub fn native_projects(root: &Path) -> Vec { .to_ascii_lowercase(); let native = match ext.as_str() { // Decoded as [`read_tree`] reads it: a UTF-16 export is no native one. - "project" => !compliance_graph::encoding::read_source(path) + "project" => !compliance_core::encoding::read_source(path) .is_ok_and(|text| looks_like_xml(&text)), "projectarchive" => sbom::check_archive(path).is_ok(), _ => false, diff --git a/compliance-agent/src/pipeline/source_text.rs b/compliance-agent/src/pipeline/source_text.rs index c35630f..aa501a4 100644 --- a/compliance-agent/src/pipeline/source_text.rs +++ b/compliance-agent/src/pipeline/source_text.rs @@ -20,7 +20,7 @@ pub fn relative_path(root: &Path, path: &str) -> String { } /// The whole text of `root/rel`, decoded by -/// [`compliance_graph::encoding::read_source`]. `None` when the file is +/// [`compliance_core::encoding::read_source`]. `None` when the file is /// unreadable or the path would leave `root`: scanner output is not trusted /// to stay inside the tree. pub fn read_text(root: &Path, rel: &str) -> Option { @@ -33,7 +33,7 @@ pub fn read_text(root: &Path, rel: &str) -> Option { return None; } // UTF-16 with a BOM and Windows-1252 too, as the code graph reads them. - compliance_graph::encoding::read_source(&root.join(rel_path)).ok() + compliance_core::encoding::read_source(&root.join(rel_path)).ok() } /// Lines `start..=end` (1-based, inclusive) of `root/rel`, capped at diff --git a/compliance-core/Cargo.toml b/compliance-core/Cargo.toml index 3945761..6620022 100644 --- a/compliance-core/Cargo.toml +++ b/compliance-core/Cargo.toml @@ -45,6 +45,8 @@ serde = { workspace = true } serde_json = { workspace = true } chrono = { workspace = true } thiserror = { workspace = true } +# Decoding source files: BOM sniffing, UTF-16, Windows-1252 +encoding_rs = { workspace = true } sha2 = { workspace = true } hex = { workspace = true } uuid = { workspace = true } diff --git a/compliance-graph/src/encoding.rs b/compliance-core/src/encoding.rs similarity index 90% rename from compliance-graph/src/encoding.rs rename to compliance-core/src/encoding.rs index cb75553..3f445c4 100644 --- a/compliance-graph/src/encoding.rs +++ b/compliance-core/src/encoding.rs @@ -72,7 +72,7 @@ pub fn read_source(path: &Path) -> Result { /// # Examples /// /// ``` -/// use compliance_graph::encoding::decode; +/// use compliance_core::encoding::decode; /// /// // "€" is 0x80 in Windows-1252. /// assert_eq!(decode(b"// 5 \x80".to_vec()).ok().as_deref(), Some("// 5 €")); @@ -108,7 +108,23 @@ pub fn decode(mut bytes: Vec) -> Result { #[cfg(test)] mod tests { use super::*; - use crate::test_tree::utf16; + + /// `text` as UTF-16 with its BOM, in the byte order asked for. + fn utf16(text: &str, little_endian: bool) -> Vec { + let bom: [u8; 2] = if little_endian { + [0xFF, 0xFE] + } else { + [0xFE, 0xFF] + }; + let units = text.encode_utf16().flat_map(|unit| { + if little_endian { + unit.to_le_bytes() + } else { + unit.to_be_bytes() + } + }); + bom.into_iter().chain(units).collect() + } #[test] fn utf8_without_a_bom_is_kept_as_it_is() { @@ -164,7 +180,7 @@ mod tests { #[test] fn a_missing_file_is_an_io_error() { - let missing = std::env::temp_dir().join("compliance-graph-no-such-file.cs"); + let missing = std::env::temp_dir().join("compliance-core-no-such-file.cs"); assert!(matches!(read_source(&missing), Err(SourceTextError::Io(_)))); } } diff --git a/compliance-core/src/lib.rs b/compliance-core/src/lib.rs index e85c2e0..3ccfb96 100644 --- a/compliance-core/src/lib.rs +++ b/compliance-core/src/lib.rs @@ -4,6 +4,7 @@ pub mod control_check; pub mod csaf_docs; pub mod csaf_ingest; pub mod db; +pub mod encoding; pub mod enisa_docs; pub mod error; pub mod exec_policy; diff --git a/compliance-graph/Cargo.toml b/compliance-graph/Cargo.toml index 00212f8..3273526 100644 --- a/compliance-graph/Cargo.toml +++ b/compliance-graph/Cargo.toml @@ -15,8 +15,6 @@ tokio = { workspace = true } mongodb = { workspace = true } thiserror = { workspace = true } -# Decoding source files: BOM sniffing, UTF-16, Windows-1252 -encoding_rs = { workspace = true } # Tree-sitter parsing tree-sitter = "0.24" diff --git a/compliance-graph/src/graph/chunking.rs b/compliance-graph/src/graph/chunking.rs index 87e0175..6706865 100644 --- a/compliance-graph/src/graph/chunking.rs +++ b/compliance-graph/src/graph/chunking.rs @@ -30,7 +30,7 @@ pub fn extract_chunks( for node in nodes { let file = repo_path.join(&node.file_path); // Decoded as the graph's parser read it, so every node has its lines. - let source = match crate::encoding::read_source(&file) { + let source = match compliance_core::encoding::read_source(&file) { Ok(s) => s, Err(_) => continue, }; diff --git a/compliance-graph/src/lib.rs b/compliance-graph/src/lib.rs index 78ce9da..ed5ef15 100644 --- a/compliance-graph/src/lib.rs +++ b/compliance-graph/src/lib.rs @@ -1,7 +1,6 @@ #![allow(clippy::only_used_in_recursion)] #![allow(clippy::too_many_arguments)] -pub mod encoding; pub mod graph; pub mod parsers; pub mod search; diff --git a/compliance-graph/src/parsers/registry.rs b/compliance-graph/src/parsers/registry.rs index 1534ad5..de2117c 100644 --- a/compliance-graph/src/parsers/registry.rs +++ b/compliance-graph/src/parsers/registry.rs @@ -91,7 +91,7 @@ impl ParserRegistry { /// Parse all supported files in a directory tree. /// - /// Each file is decoded by [`crate::encoding::read_source`] (UTF-8, + /// Each file is decoded by [`compliance_core::encoding::read_source`] (UTF-8, /// UTF-16 with a BOM, Windows-1252); a file still not readable as text /// is counted, not parsed. /// @@ -205,7 +205,7 @@ impl ParserRegistry { // Use relative path from base let rel_path = path.strip_prefix(base).unwrap_or(&path); - let source = match crate::encoding::read_source(&path) { + let source = match compliance_core::encoding::read_source(&path) { Ok(text) => text, Err(error) => { debug!(file = %rel_path.display(), %error, "Source file not readable"); diff --git a/werkbank-exec/src/plc/mod.rs b/werkbank-exec/src/plc/mod.rs index 476a6d5..219200d 100644 --- a/werkbank-exec/src/plc/mod.rs +++ b/werkbank-exec/src/plc/mod.rs @@ -96,7 +96,8 @@ pub fn extract_program(root: &Path) -> Option { if !is_st && !is_xml { continue; } - let Ok(content) = std::fs::read_to_string(path) else { + // UTF-8, UTF-16 with a BOM, or Windows-1252, as PLC tools write them. + let Ok(content) = compliance_core::encoding::read_source(path) else { continue; }; let name = path @@ -334,6 +335,20 @@ mod tests { assert_eq!(prog2.file_name, "proj.xml"); } + #[test] + fn extract_reads_a_windows_1252_st_program() { + let s = Scratch::new(); + // A comment with "Pumpe für" as Windows-1252 writes it: 0xFC for "ü". + std::fs::write( + s.0.join("main.st"), + b"(* Pumpe f\xFCr Halle 2 *)\nPROGRAM Main\nEND_PROGRAM\nCONFIGURATION C\nEND_CONFIGURATION\n", + ) + .expect("w"); + let prog = extract_program(&s.0).expect("program"); + assert_eq!(prog.file_name, "main.st"); + assert!(prog.source.contains("Pumpe für")); + } + #[test] fn extract_returns_none_without_control_logic() { let s = Scratch::new();