Compare commits

...
1 Commits
Author SHA1 Message Date
sharangandClaude Opus 5.5 ca66b9a7b1 fix(scan): read UTF-16 and Windows-1252 files in the remaining readers (t84) (#942)
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 3s
CI / Deploy Docs (push) Skipped
CI / Deploy MCP (push) Successful in 51s
CI / Deploy Dashboard (push) Successful in 5m8s
CI / Deploy Agent (push) Successful in 7m21s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 09:58:55 +00:00
20 changed files with 178 additions and 28 deletions

No files matched your search

Generated
+1 -1
View File
@@ -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",
+1 -1
View File
@@ -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::<Vec<_>>().join("\n");
+1 -1
View File
@@ -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<CandidateRegion> {
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;
+20 -1
View File
@@ -156,7 +156,8 @@ pub fn retrieve(repo_path: &Path, terms: &[&str], excluded: &[String]) -> Vec<Ca
if !meta.is_file() || meta.len() > 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()));
+1 -1
View File
@@ -861,7 +861,7 @@ fn read_surrounding_context(finding: &Finding) -> Option<String> {
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);
+2 -2
View File
@@ -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<String> {
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
@@ -148,7 +148,7 @@ pub fn detect(root: &Path, repo_id: &str) -> Vec<SbomEntry> {
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;
+22 -1
View File
@@ -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()));
+46 -1
View File
@@ -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
);
}
}
+37 -3
View File
@@ -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));
}
}
+3 -3
View File
@@ -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<PlcFile> {
@@ -84,7 +84,7 @@ pub(crate) fn read_tree(root: &Path) -> Vec<PlcFile> {
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<String> {
.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,
+2 -2
View File
@@ -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<String> {
@@ -33,7 +33,7 @@ pub fn read_text(root: &Path, rel: &str) -> Option<String> {
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
+2
View File
@@ -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 }
@@ -72,7 +72,7 @@ pub fn read_source(path: &Path) -> Result<String, SourceTextError> {
/// # 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<u8>) -> Result<String, SourceTextError> {
#[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<u8> {
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(_))));
}
}
+1
View File
@@ -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;
-2
View File
@@ -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"
+1 -1
View File
@@ -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,
};
-1
View File
@@ -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;
+2 -2
View File
@@ -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");
+16 -1
View File
@@ -96,7 +96,8 @@ pub fn extract_program(root: &Path) -> Option<PlcProgram> {
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();