Craft Anything: understand how any software works, and craft your own.
Rust
Report folders that couldn't be listed in archive and JS app evidence (#459)
NetterSilver28df99e06682
diff --git a/crates/engine/src/tools/artifact_tools.rs b/crates/engine/src/tools/artifact_tools.rsindex e5d52334..68b3014b 100644--- a/crates/engine/src/tools/artifact_tools.rs+++ b/crates/engine/src/tools/artifact_tools.rs@@ -100,7 +100,25 @@ pub(crate) struct Walked {pub links: Vec<String>,pub ignored: usize,pub truncated: bool,- pub errors: Vec<String>,+ /// Folders below the root that couldn't be listed, as (relative path, reason) (#294).+ pub unlisted: Vec<(String, String)>,+}++/// A limitation naming the folders that couldn't be listed, as (path, reason), if any (#294).+pub(crate) fn unlisted_limitation(unlisted: &[(String, String)]) -> Option<Limitation> {+ if unlisted.is_empty() {+ return None;+ }+ let first = unlisted.iter().take(5).map(|(rel, e)| format!("{rel} ({e})")).collect::<Vec<_>>().join(", ");+ let more = unlisted.len().saturating_sub(5);+ Some(Limitation::new(+ "unlisted_folders",+ format!(+ "{} folder(s) couldn't be listed, so what they hold is missing: {first}{}",+ unlisted.len(),+ if more > 0 { format!(" and {more} more") } else { String::new() }+ ),+ ))}pub(crate) struct WalkOptions<'a> {@@ -114,6 +132,7 @@ pub(crate) struct WalkOptions<'a> {}/// Walk a folder without following symbolic links. Bounded by file count and depth.+/// A root that can't be listed is an error; a folder below it that can't be is in `unlisted`.pub(crate) fn walk_dir(root: &Path, opts: &WalkOptions<'_>, cancel: &CancelToken) -> Result<Walked, ToolError> {let mut out = Walked::default();let mut ignore = craft_anything_analysis::js_source::Ignore::default();@@ -128,10 +147,9 @@ pub(crate) fn walk_dir(root: &Path, opts: &WalkOptions<'_>, cancel: &CancelToken}let entries = match std::fs::read_dir(&dir) {Ok(e) => e,+ Err(e) if rel.is_empty() => return Err(ToolError::io(dir.display(), e)),Err(e) => {- if out.errors.len() < 100 {- out.errors.push(format!("{}: {e}", dir.display()));- }+ out.unlisted.push((rel, e.to_string()));continue;}};@@ -391,6 +409,12 @@ fn default_max_total() -> u64 {/// Build an inventory of a path (file or folder).pub(crate) fn inventory_path(path: &Path, limits: InvLimits, cancel: &CancelToken) -> Result<(Inventory, Subject), ToolError> {+ inventory_path_unlisted(path, limits, cancel).map(|(inv, subject, _)| (inv, subject))+}++/// [`inventory_path`], also returning the folders that couldn't be listed, as (path, reason).+#[allow(clippy::type_complexity)]+fn inventory_path_unlisted(path: &Path, limits: InvLimits, cancel: &CancelToken) -> Result<(Inventory, Subject, Vec<(String, String)>), ToolError> {let meta = std::fs::metadata(path).map_err(|e| ToolError::io(path.display(), e))?;let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| path.display().to_string());let check = || cancel.is_cancelled();@@ -400,7 +424,8 @@ pub(crate) fn inventory_path(path: &Path, limits: InvLimits, cancel: &CancelTokewalk_dir(path, &WalkOptions { max_files: limits.max_entries, max_depth: 64, skip_dir: &skip, gitignore: false, include_hidden: true }, cancel)?;let mut inv = Inventorier::new(&name, "directory", limits, &check);for d in &walked.dirs {- inv.add_marker(d, "directory", 0, None);+ let failed = walked.unlisted.iter().find(|(rel, _)| rel == d);+ inv.add_marker(d, "directory", 0, failed.map(|(_, e)| format!("couldn't be listed: {e}")));}for l in &walked.links {inv.add_marker(l, "link", 0, Some("symbolic link (not followed)".into()));@@ -424,11 +449,13 @@ pub(crate) fn inventory_path(path: &Path, limits: InvLimits, cancel: &CancelTokelet mut out = inv.finish();out.truncated |= walked.truncated;let id = out.content_id();- return Ok((out, Subject { kind: "directory".into(), sha256: Some(id.trim_start_matches("inv_").to_string()), name: Some(name) }));+ let subject = Subject { kind: "directory".into(), sha256: Some(id.trim_start_matches("inv_").to_string()), name: Some(name) };+ return Ok((out, subject, walked.unlisted));}let bytes = read_capped(path, limits.max_total_bytes.min(crate::target::MAX_TARGET_BYTES))?;let kind = craft_anything_analysis::js_inventory::sniff_kind(&bytes, &name);let mut inv = Inventorier::new(&name, kind, limits, &check);+ let mut unlisted = Vec::new();match kind {"zip" | "apk" | "ipa" | "jar" | "hap" | "msix" | "asar" => {inv.add_archive("", &bytes, kind, 0).map_err(|_| ToolError::cancelled())?;@@ -442,6 +469,7 @@ pub(crate) fn inventory_path(path: &Path, limits: InvLimits, cancel: &CancelToke&WalkOptions { max_files: limits.max_entries, max_depth: 64, skip_dir: &skip, gitignore: false, include_hidden: true },cancel,)?;+ unlisted.extend(walked.unlisted.into_iter().map(|(rel, e)| (format!("{name}.unpacked/{rel}"), e)));for f in walked.files.iter().take(limits.max_entries) {if let Ok(b) = std::fs::read(&f.abs) {inv.add_file(&format!("{name}.unpacked/{}", f.rel), &b, 0).map_err(|_| ToolError::cancelled())?;@@ -452,7 +480,7 @@ pub(crate) fn inventory_path(path: &Path, limits: InvLimits, cancel: &CancelToke}_ => inv.add_file(&name, &bytes, 0).map_err(|_| ToolError::cancelled())?,}- Ok((inv.finish(), Subject { kind: kind.into(), sha256: Some(sha256_hex(&bytes)), name: Some(name) }))+ Ok((inv.finish(), Subject { kind: kind.into(), sha256: Some(sha256_hex(&bytes)), name: Some(name) }, unlisted))}fn target_path(ctx: &Ctx<'_>, p: Option<&str>) -> Result<PathBuf, ToolError> {@@ -511,7 +539,7 @@ fn core_archive_show(ctx: &mut Ctx<'_>, params: Value) -> Result<ToolOutput, Toolet path = target_path(ctx, p.path.as_deref())?;let limits = show_limits(p.max_depth, p.max_entries, p.max_total_bytes);ctx.report(None, format!("Inventorying {}", path.display()));- let (inv, subject) = inventory_path(&path, limits, &ctx.cancel)?;+ let (inv, subject, unlisted) = inventory_path_unlisted(&path, limits, &ctx.cancel)?;let blocking = inv.contradictions.iter().any(|c| c.get("reason").and_then(Value::as_str).is_some_and(|r| r.contains("integrity") || r.contains("CRC")));if blocking && p.if_tampered == IntegrityPolicy::Fail {return Err(integrity_error(&inv));@@ -537,7 +565,12 @@ fn core_archive_show(ctx: &mut Ctx<'_>, params: Value) -> Result<ToolOutput, Too"A size, count or depth limit stopped the inventory early; raise max_entries, max_total_bytes or max_depth to see more.",));}+ lims.extend(unlisted_limitation(&unlisted));lims.push(Limitation::new("no_disk_images", "Disk images (DMG), installers (PKG/MSI) and compressed tarballs are listed as single files, not opened."));+ let mut coverage = Coverage::page(page.len() as u64, total as u64, p.offset as u64);+ if !unlisted.is_empty() {+ coverage.status = craft_anything_evidence::CoverageStatus::Partial;+ }let ev = EvidenceBuilder::new("core_archive_show", subject, env(ctx)).params(json!({"path": path, "if_tampered": p.if_tampered == IntegrityPolicy::Fail, "offset": p.offset, "limit": limit, "max_depth": limits.max_depth, "max_entries": limits.max_entries, "max_total_bytes": limits.max_total_bytes})).result(json!({@@ -551,7 +584,7 @@ fn core_archive_show(ctx: &mut Ctx<'_>, params: Value) -> Result<ToolOutput, Too.confidence(Confidence::Observed).authority(Authority::OriginalFiles).limitations(lims)- .coverage(Coverage::page(page.len() as u64, total as u64, p.offset as u64))+ .coverage(coverage).location(Location::new("path", path.display().to_string())).build()?;Ok(ToolOutput::evidence(ev))@@ -906,4 +939,34 @@ mod tests {assert_eq!(safe_components("./a//b").unwrap(), vec!["a", "b"]);assert!(safe_components("").is_err());}++ /// #294: a folder that couldn't be listed looked like an ordinary empty folder.+ #[cfg(unix)]+ #[test]+ fn a_folder_that_cant_be_listed_is_marked_and_leaves_coverage_partial() {+ use std::os::unix::fs::PermissionsExt;+ let dir = tempfile::tempdir().unwrap();+ let bundle = dir.path().join("bundle");+ let closed = bundle.join("closed");+ std::fs::create_dir_all(&closed).unwrap();+ std::fs::write(closed.join("hidden.js"), "console.log('hidden');\n").unwrap();+ std::fs::write(bundle.join("visible.js"), "console.log('visible');\n").unwrap();+ let e = Engine::new(crate::testing::session());+ let readable = call(&e, "core_archive_show", json!({"path": bundle})).unwrap();+ std::fs::set_permissions(&closed, std::fs::Permissions::from_mode(0o000)).unwrap();+ if std::fs::read_dir(&closed).is_ok() {+ std::fs::set_permissions(&closed, std::fs::Permissions::from_mode(0o755)).unwrap();+ return; // Run as root: nothing is unreadable.+ }+ let child = call(&e, "core_archive_show", json!({"path": bundle}));+ let root = call(&e, "core_archive_show", json!({"path": closed}));+ std::fs::set_permissions(&closed, std::fs::Permissions::from_mode(0o755)).unwrap();+ let v = child.unwrap();+ assert_eq!(v["coverage"]["status"], "partial", "{v}");+ assert!(v["limitations"].as_array().unwrap().iter().any(|l| l["code"] == "unlisted_folders"), "{v}");+ let entry = v["result"]["entries"].as_array().unwrap().iter().find(|x| x["path"] == "closed").cloned().unwrap();+ assert!(entry["note"].as_str().is_some_and(|n| n.contains("couldn't be listed")), "{v}");+ assert!(root.is_err(), "a root folder that can't be listed is an error, not an empty inventory");+ assert_eq!(call(&e, "core_archive_show", json!({"path": bundle})).unwrap()["result"], readable["result"]);+ }}diff --git a/crates/engine/src/tools/js_tools.rs b/crates/engine/src/tools/js_tools.rsindex 189a11f3..e42334df 100644--- a/crates/engine/src/tools/js_tools.rs+++ b/crates/engine/src/tools/js_tools.rs@@ -166,14 +166,17 @@ impl Budget {}}-/// Read an input into files for the analyser. Returns the input, its subject and integrity problems.-pub(crate) fn load_app_input(ctx: &Ctx<'_>, p: &AnalyzeParams) -> Result<(AppInput, Subject, Vec<String>), ToolError> {+/// Read an input into files for the analyser. Returns the input, its subject, integrity problems+/// and the folders that couldn't be listed, as (path, reason).+#[allow(clippy::type_complexity)]+pub(crate) fn load_app_input(ctx: &Ctx<'_>, p: &AnalyzeParams) -> Result<(AppInput, Subject, Vec<String>, Vec<(String, String)>), ToolError> {let path = abs_path(&p.input_path, "input_path")?;let meta = std::fs::metadata(&path).map_err(|e| ToolError::io(path.display(), e))?;let label = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| path.display().to_string());let mut budget = Budget { files: 0, bytes: 0, max_files: p.max_files.max(1), max_bytes: p.max_total_bytes, max_file: p.max_file_bytes, skipped: 0 };let mut input = AppInput { label: label.clone(), ..Default::default() };let mut integrity = Vec::new();+ let mut unlisted = Vec::new();let format = match p.format {InputFormat::Auto if meta.is_dir() => InputFormat::Directory,InputFormat::Auto => {@@ -202,6 +205,7 @@ pub(crate) fn load_app_input(ctx: &Ctx<'_>, p: &AnalyzeParams) -> Result<(AppInpif walked.truncated {input.notes.push("the folder listing was cut short by the file-count or depth limit".into());}+ unlisted.extend(walked.unlisted.iter().cloned());// A packaged app folder: analyse its app.asar when there is no package.json of its own.let has_pkg = walked.files.iter().any(|f| f.rel == "package.json" || (f.rel.ends_with("/package.json") && !f.rel.contains("node_modules/")));let asars: Vec<&super::artifact_tools::WalkedFile> = walked.files.iter().filter(|f| f.rel.ends_with("app.asar")).collect();@@ -212,9 +216,10 @@ pub(crate) fn load_app_input(ctx: &Ctx<'_>, p: &AnalyzeParams) -> Result<(AppInplet mut q = p.clone();q.input_path = a.abs.display().to_string();q.format = InputFormat::Asar;- let (mut inp, subj, integ) = load_app_input(ctx, &q)?;+ let (mut inp, subj, integ, mut gaps) = load_app_input(ctx, &q)?;inp.notes.push(format!("analysed {} found inside the folder", a.rel));- return Ok((inp, subj, integ));+ unlisted.append(&mut gaps);+ return Ok((inp, subj, integ, unlisted));}let mut listing_hash = Vec::new();for f in &walked.files {@@ -324,6 +329,7 @@ pub(crate) fn load_app_input(ctx: &Ctx<'_>, p: &AnalyzeParams) -> Result<(AppInplet skip = |_: &str| false;let walked =walk_dir(&ep, &WalkOptions { max_files: p.max_files, max_depth: 48, skip_dir: &skip, gitignore: false, include_hidden: false }, &ctx.cancel)?;+ unlisted.extend(walked.unlisted.iter().map(|(rel, e)| (format!("{base}/{rel}"), e.clone())));for f in &walked.files {let rel = format!("{base}/{}", f.rel);input.listing.push((rel.clone(), f.size));@@ -342,7 +348,7 @@ pub(crate) fn load_app_input(ctx: &Ctx<'_>, p: &AnalyzeParams) -> Result<(AppInpif budget.skipped > 0 {input.notes.push(format!("{} file(s) were listed but not read because of the size or count limits", budget.skipped));}- Ok((input, subject, integrity))+ Ok((input, subject, integrity, unlisted))}fn read_head(path: &Path) -> Result<Vec<u8>, ToolError> {@@ -359,7 +365,7 @@ fn read_head(path: &Path) -> Result<Vec<u8>, ToolError> {pub(crate) type Analyzed = (AppGraph, Subject, Vec<Limitation>, (u64, u64));pub(crate) fn analyze_to_graph(ctx: &Ctx<'_>, p: &AnalyzeParams) -> Result<Analyzed, ToolError> {- let (input, subject, integrity) = load_app_input(ctx, p)?;+ let (input, subject, integrity, unlisted) = load_app_input(ctx, p)?;if !integrity.is_empty() && p.if_tampered == IntegrityPolicy::Fail {return Err(ToolError::new(ErrorCode::FileHashMismatch,@@ -376,6 +382,7 @@ pub(crate) fn analyze_to_graph(ctx: &Ctx<'_>, p: &AnalyzeParams) -> Result<Analyfor path in &integrity {lims.push(Limitation::new("integrity_mismatch", format!("{path} does not match its ASAR integrity hash")));}+ lims.extend(super::artifact_tools::unlisted_limitation(&unlisted));lims.push(Limitation::new("static_only","Static reading only: code built at run time (eval, computed requires, remote content) is invisible; IPC pairs need literal channel names.",@@ -416,13 +423,15 @@ fn js_app_map(ctx: &mut Ctx<'_>, params: Value) -> Result<ToolOutput, ToolError>o.insert("summary".into(), json!(summary));}let complete_modules = p.offset == 0 && p.limit >= total_modules;+ // A folder that couldn't be listed holds files never counted, so the count can't be complete (#294).+ let unlisted = lims.iter().any(|l| l.code == "unlisted_folders");let mut b = EvidenceBuilder::new("js_app_map", subject, env(ctx)).params(json!({"input_path": p.input_path, "include_node_modules": p.include_node_modules, "max_nodes": p.max_nodes, "offset": p.offset, "limit": p.limit, "source_paths": p.source_paths})).result(result).summary(summary).confidence(Confidence::Derived).limitations(lims)- .coverage(if complete_modules { Coverage { status: if read >= listed { craft_anything_evidence::CoverageStatus::Complete } else { craft_anything_evidence::CoverageStatus::Partial }, examined: Some(read), total: Some(listed), next_offset: None } } else { Coverage::page(p.limit.min(total_modules.saturating_sub(p.offset)) as u64, total_modules as u64, p.offset as u64) })+ .coverage(if complete_modules { Coverage { status: if read >= listed && !unlisted { craft_anything_evidence::CoverageStatus::Complete } else { craft_anything_evidence::CoverageStatus::Partial }, examined: Some(read), total: Some(listed), next_offset: None } } else { Coverage::page(p.limit.min(total_modules.saturating_sub(p.offset)) as u64, total_modules as u64, p.offset as u64) }).location(Location::new("path", p.input_path.clone()));if !complete_modules {b = b.limitation(Limitation::new("paged_modules", "Only one page of module summaries is included; tools that take this evidence need every module, so pass the input path to them or use offset=0 with a limit above modules_total."));@@ -642,4 +651,56 @@ mod tests {let err = call(&e, "js_runtime_code_match", json!({"static_evidence": [{"evidence": tampered}], "runtime_scripts": [{"url": "x"}]})).unwrap_err();assert_eq!(err.code, craft_anything_evidence::ErrorCode::EvidenceHashMismatch);}++ /// #294: a folder that couldn't be listed made a smaller graph that looked complete.+ #[cfg(unix)]+ #[test]+ fn a_folder_that_cant_be_listed_is_said_and_leaves_coverage_partial() {+ use std::os::unix::fs::PermissionsExt;+ let dir = tempfile::tempdir().unwrap();+ let bundle = dir.path().join("bundle");+ let closed = bundle.join("closed");+ std::fs::create_dir_all(&closed).unwrap();+ std::fs::write(closed.join("hidden.js"), "console.log('hidden');\n").unwrap();+ std::fs::write(bundle.join("visible.js"), "console.log('visible');\n").unwrap();+ let main = dir.path().join("main.js");+ std::fs::write(&main, "console.log('main');\n").unwrap();+ let extras = dir.path().join("extras");+ std::fs::create_dir_all(extras.join("closed")).unwrap();+ std::fs::write(extras.join("closed/extra.js"), "console.log('extra');\n").unwrap();+ let e = Engine::new(crate::testing::session());+ let modules = |v: &Value| v["result"]["modules"].as_array().unwrap().iter().map(|m| m["path"].as_str().unwrap().to_string()).collect::<Vec<_>>();+ let readable = call(&e, "js_app_map", json!({"input_path": bundle})).unwrap();+ assert_eq!(modules(&readable), ["closed/hidden.js", "visible.js"]);+ let with_extra = json!({"input_path": main, "source_paths": [extras]});+ assert_eq!(modules(&call(&e, "js_app_map", with_extra.clone()).unwrap()).len(), 2);++ let deny = |p: &std::path::Path| std::fs::set_permissions(p, std::fs::Permissions::from_mode(0o000)).unwrap();+ let allow = |p: &std::path::Path| std::fs::set_permissions(p, std::fs::Permissions::from_mode(0o755)).unwrap();+ deny(&closed);+ if std::fs::read_dir(&closed).is_ok() {+ allow(&closed);+ return; // Run as root: nothing is unreadable.+ }+ let child = call(&e, "js_app_map", json!({"input_path": bundle}));+ let root = call(&e, "js_app_map", json!({"input_path": closed}));+ allow(&closed);+ deny(&extras.join("closed"));+ let extra_child = call(&e, "js_app_map", with_extra.clone());+ allow(&extras.join("closed"));+ deny(&extras);+ let extra_root = call(&e, "js_app_map", with_extra.clone());+ allow(&extras);++ for v in [child.unwrap(), extra_child.unwrap()] {+ assert_eq!(v["coverage"]["status"], "partial", "{v}");+ let lim = v["limitations"].as_array().unwrap().iter().find(|l| l["code"] == "unlisted_folders").cloned();+ assert!(lim.is_some_and(|l| l["message"].as_str().unwrap().contains("closed")), "{v}");+ }+ assert!(root.is_err(), "a root folder that can't be listed is an error, not an empty graph");+ assert!(extra_root.is_err(), "so is an extra source folder that can't be listed");+ let forced = call(&e, "js_app_map", json!({"input_path": main, "format": "directory"}));+ assert!(forced.is_err(), "a regular file read as a folder is an error: {forced:?}");+ assert_eq!(call(&e, "js_app_map", json!({"input_path": bundle})).unwrap()["result"], readable["result"]);+ }}