From e0dc177885e4a027704f9d9b5f9f134f8a99e1e1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=B6=BE=E7=80=AC=E6=A1=83=E6=A1=83?= Date: Thu, 5 Nov 2026 22:15:09 +0800 Subject: [PATCH] test(corpus): add commit-linked local regression reports --- Cargo.lock | 3 + senbei-cli/Cargo.toml | 3 + senbei-cli/examples/corpus_harness.rs | 130 ++ senbei-cli/tests/corpus_harness.rs | 454 +++++ senbei-cli/tests/corpus_harness_panics.rs | 180 ++ senbei-cli/tests/support/fixtures.rs | 216 +++ senbei-cli/tests/support/harness.rs | 2093 +++++++++++++++++++++ 7 files changed, 3079 insertions(+) create mode 100644 senbei-cli/examples/corpus_harness.rs create mode 100644 senbei-cli/tests/corpus_harness.rs create mode 100644 senbei-cli/tests/corpus_harness_panics.rs create mode 100644 senbei-cli/tests/support/fixtures.rs create mode 100644 senbei-cli/tests/support/harness.rs diff --git a/Cargo.lock b/Cargo.lock index 77aa7ee..c23a682 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -424,9 +424,12 @@ dependencies = [ name = "senbei-cli" version = "1.3.4" dependencies = [ + "anyhow", "senbei-engine", "senbei-io", "senbei-metadata", + "serde", + "serde_json", "sha2", "tempfile", ] diff --git a/senbei-cli/Cargo.toml b/senbei-cli/Cargo.toml index b2941a6..cd8e840 100644 --- a/senbei-cli/Cargo.toml +++ b/senbei-cli/Cargo.toml @@ -16,7 +16,10 @@ senbei-io.workspace = true senbei-engine.workspace = true [dev-dependencies] +anyhow.workspace = true senbei-io.workspace = true senbei-metadata.workspace = true +serde.workspace = true +serde_json.workspace = true sha2.workspace = true tempfile.workspace = true diff --git a/senbei-cli/examples/corpus_harness.rs b/senbei-cli/examples/corpus_harness.rs new file mode 100644 index 0000000..1c80a63 --- /dev/null +++ b/senbei-cli/examples/corpus_harness.rs @@ -0,0 +1,130 @@ +//! Local, manifest-driven corpus harness. +//! +//! Run with an explicit manifest: +//! +//! ```text +//! cargo run --release --example corpus_harness -- --manifest corpus.json +//! cargo run --release --example corpus_harness -- --manifest corpus.json \ +//! --report target/corpus-report.json --commit +//! cargo run --release --example corpus_harness -- --emit-manifest ../samples \ +//! --android-app ../android/com.example.app --manifest-out target/corpus.json +//! ``` +//! +//! Exit status is 0 only when every case passes. The report goes to stdout by +//! default; `--report` writes it atomically. Nothing is uploaded, no input or +//! golden is modified, and restored bytes live only in a temporary directory. +//! +//! The manifest schema is documented in `senbei-cli/tests/support/harness.rs` +//! (the `SCHEMA`/`Manifest`/`CaseSpec` types and the module header). + +#[path = "../tests/support/harness.rs"] +mod harness; + +use std::path::PathBuf; +use std::process::ExitCode; + +fn main() -> ExitCode { + let mut args = std::env::args().skip(1); + let mut manifest: Option = None; + let mut report: Option = None; + let mut commit: Option = None; + let mut emit_roots: Vec = Vec::new(); + let mut android_apps: Vec = Vec::new(); + let mut manifest_out: Option = None; + + while let Some(arg) = args.next() { + match arg.as_str() { + "-h" | "--help" => { + print_help(); + return ExitCode::SUCCESS; + } + "--manifest" => match args.next() { + Some(value) => manifest = Some(PathBuf::from(value)), + None => return usage("--manifest requires a path"), + }, + "--report" => match args.next() { + Some(value) => report = Some(PathBuf::from(value)), + None => return usage("--report requires a path"), + }, + "--commit" => match args.next() { + Some(value) => commit = Some(value), + None => return usage("--commit requires a value"), + }, + "--emit-manifest" => match args.next() { + Some(value) => emit_roots.push(PathBuf::from(value)), + None => return usage("--emit-manifest requires a directory"), + }, + "--android-app" => match args.next() { + Some(value) => android_apps.push(PathBuf::from(value)), + None => return usage("--android-app requires a directory"), + }, + "--manifest-out" => match args.next() { + Some(value) => manifest_out = Some(PathBuf::from(value)), + None => return usage("--manifest-out requires a path"), + }, + other => return usage(&format!("unknown argument {other:?}")), + } + } + + if !emit_roots.is_empty() || !android_apps.is_empty() { + let Some(out) = manifest_out else { + return usage("--emit-manifest/--android-app require --manifest-out"); + }; + match harness::emit_manifest(&emit_roots, &android_apps, &out) { + Ok(count) => { + println!("wrote {count} case(s) to {}", out.display()); + ExitCode::SUCCESS + } + Err(error) => { + eprintln!("error: {error}"); + ExitCode::from(1) + } + } + } else { + let Some(manifest) = manifest else { + return usage("--manifest is required"); + }; + let options = harness::RunOptions { + commit, + cwd: std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")), + }; + let report_data = harness::run(&manifest, &options); + let text = match serde_json::to_string_pretty(&report_data) { + Ok(text) => text, + Err(error) => { + eprintln!("error: serialize report: {error}"); + return ExitCode::from(1); + } + }; + if let Some(path) = report { + if let Err(error) = harness::write_atomic(&path, text.as_bytes()) { + eprintln!("error: write report {}: {error}", path.display()); + return ExitCode::from(1); + } + } else { + println!("{text}"); + } + if report_data.passed() { + ExitCode::SUCCESS + } else { + ExitCode::from(1) + } + } +} + +fn usage(message: &str) -> ExitCode { + eprintln!("error: {message}"); + print_help(); + ExitCode::from(2) +} + +fn print_help() { + println!( + "corpus_harness --manifest FILE [--report FILE] [--commit SHA]\n\ + corpus_harness --emit-manifest DIR [--emit-manifest DIR]... \ + [--android-app DIR]... --manifest-out FILE\n\ + \n\ + Explicit manifest cases only: no folder walk is performed unless an\n\ + android-app case supplies its app folder, and junctions are skipped." + ); +} diff --git a/senbei-cli/tests/corpus_harness.rs b/senbei-cli/tests/corpus_harness.rs new file mode 100644 index 0000000..a060207 --- /dev/null +++ b/senbei-cli/tests/corpus_harness.rs @@ -0,0 +1,454 @@ +//! Integration tests for the manifest-driven corpus harness. +//! +//! These exercise the harness itself with generated fixtures only: a +//! Crackproof-shaped PE, synthetic v31 metadata, an ELF probe, and a small app +//! tree. No real corpus, product name, or golden binary is involved. +//! +//! Run just this file with: +//! +//! ```text +//! cargo test --release -p senbei-cli --test corpus_harness +//! ``` +//! +//! The example binary (`cargo run --release --example corpus_harness -- +//! --manifest FILE`) is the user-facing entry point; its module header +//! documents the JSON schema. + +#[path = "support/fixtures.rs"] +mod fixtures; +#[path = "support/harness.rs"] +mod harness; + +use std::path::{Path, PathBuf}; + +use harness::{CaseSpec, Defaults, Kind, Manifest, RunOptions}; +use sha2::{Digest, Sha256}; + +fn write_manifest(dir: &Path, cases: Vec, defaults: Defaults) -> PathBuf { + let manifest = Manifest { + schema: harness::SCHEMA.to_owned(), + name: Some("test".to_owned()), + base_dir: None, + defaults, + cases, + }; + let path = dir.join("manifest.json"); + std::fs::write(&path, serde_json::to_vec_pretty(&manifest).unwrap()).unwrap(); + path +} + +fn case(id: &str, kind: Kind, input: &str) -> CaseSpec { + CaseSpec { + id: id.to_owned(), + kind, + input: PathBuf::from(input), + companion: None, + golden: None, + golden_sha256: None, + sha256: None, + metadata_sha256: None, + expect_failure: None, + expect_suspect: None, + allow_missing_golden: None, + allow_suspect: None, + allow_empty: None, + entries: None, + } +} + +fn sha256_hex(bytes: &[u8]) -> String { + let mut digest = Sha256::new(); + digest.update(bytes); + digest + .finalize() + .iter() + .map(|byte| format!("{byte:02x}")) + .collect() +} + +fn options() -> RunOptions { + RunOptions { + commit: Some("test-commit".to_owned()), + cwd: std::env::temp_dir(), + } +} + +fn write(dir: &Path, name: &str, bytes: &[u8]) -> PathBuf { + let path = dir.join(name); + std::fs::write(&path, bytes).unwrap(); + path +} + +#[test] +fn synthetic_metadata_passes_against_a_golden_and_reports_hashes() { + let dir = tempfile::tempdir().unwrap(); + let obfuscated = fixtures::obfuscated_metadata(); + let clean = fixtures::clean_metadata(); + write(dir.path(), "input.dat", &obfuscated); + write(dir.path(), "input.golden.dat", &clean); + let mut spec = case("metadata", Kind::Metadata, "input.dat"); + spec.golden = Some(PathBuf::from("input.golden.dat")); + let manifest = write_manifest(dir.path(), vec![spec], Defaults::default()); + + let report = harness::run(&manifest, &options()); + assert!( + report.passed(), + "{}", + serde_json::to_string_pretty(&report).unwrap() + ); + assert_eq!(report.summary.total, 1); + assert_eq!(report.summary.passed, 1); + let output = &report.cases[0].outputs[0]; + assert_eq!(output.sha256.as_deref(), Some(sha256_hex(&clean).as_str())); + assert_eq!(output.remapped, Some(5)); + assert_eq!(output.bytes, Some(clean.len() as u64)); + assert_eq!(report.git.head.as_deref(), Some("test-commit")); + assert_eq!(report.git.head_source, "caller"); + assert_eq!(report.git.dirty, None, "no repo discovered in temp dir"); + assert!(!report.manifest.sha256.is_empty()); +} + +#[test] +fn golden_length_difference_is_a_truthful_failure() { + let dir = tempfile::tempdir().unwrap(); + let clean = fixtures::clean_metadata(); + write(dir.path(), "input.dat", &fixtures::obfuscated_metadata()); + write(dir.path(), "input.golden.dat", &clean[..clean.len() - 4]); + let mut spec = case("stale", Kind::Metadata, "input.dat"); + spec.golden = Some(PathBuf::from("input.golden.dat")); + let manifest = write_manifest(dir.path(), vec![spec], Defaults::default()); + + let report = harness::run(&manifest, &options()); + assert!(!report.passed()); + let case = &report.cases[0]; + assert!( + case.failures + .iter() + .any(|failure| failure.contains("length")) + ); + assert_eq!(report.summary.golden_mismatches, 1); +} + +#[test] +fn missing_golden_and_missing_manifest_fail_without_panicking() { + let dir = tempfile::tempdir().unwrap(); + write(dir.path(), "input.dat", &fixtures::obfuscated_metadata()); + let mut spec = case("missing", Kind::Metadata, "input.dat"); + spec.golden = Some(PathBuf::from("does-not-exist.golden.dat")); + let manifest = write_manifest(dir.path(), vec![spec], Defaults::default()); + + let report = harness::run(&manifest, &options()); + assert!(!report.passed()); + assert!( + report.cases[0] + .failures + .iter() + .any(|f| f.contains("golden is missing")) + ); + + let absent = dir.path().join("absent.json"); + let report = harness::run(&absent, &options()); + assert!(!report.passed()); + assert!(report.manifest_errors[0].contains("read manifest")); + + let malformed = write(dir.path(), "malformed.json", b"{ not json"); + let report = harness::run(&malformed, &options()); + assert!(!report.passed()); + assert!(report.manifest_errors[0].contains("parse manifest")); +} + +#[test] +fn non_empty_manifest_and_complete_expectations_are_required() { + let dir = tempfile::tempdir().unwrap(); + write(dir.path(), "input.dat", &fixtures::obfuscated_metadata()); + let empty = write_manifest(dir.path(), Vec::new(), Defaults::default()); + let report = harness::run(&empty, &options()); + assert!(!report.passed()); + assert!( + report + .manifest_errors + .iter() + .any(|e| e.contains("no cases")) + ); + + let bare = write_manifest( + dir.path(), + vec![case("bare", Kind::Metadata, "input.dat")], + Defaults::default(), + ); + let report = harness::run(&bare, &options()); + assert!(!report.passed()); + assert_eq!(report.cases[0].outcome, "invalid_case"); + assert!( + report.cases[0] + .failures + .iter() + .any(|failure| failure.contains("no expected output")) + ); + + let mut opt_out = case("opt-out", Kind::Metadata, "input.dat"); + opt_out.allow_missing_golden = Some(true); + let manifest = write_manifest(dir.path(), vec![opt_out], Defaults::default()); + let report = harness::run(&manifest, &options()); + assert!( + report.passed(), + "{}", + serde_json::to_string_pretty(&report).unwrap() + ); + assert_eq!(report.cases[0].outputs[0].status, "ok"); + assert_eq!(report.cases[0].outputs[0].expected_sha256, None); +} + +#[test] +fn malformed_metadata_fixtures_fail_truthfully_and_never_panic() { + let dir = tempfile::tempdir().unwrap(); + let mut cases = Vec::new(); + for (name, bytes) in fixtures::malformed_metadata_probes() { + write(dir.path(), &format!("{name}.dat"), &bytes); + let mut spec = case(name, Kind::Metadata, &format!("{name}.dat")); + spec.expect_failure = Some(true); + cases.push(spec); + } + let manifest = write_manifest(dir.path(), cases, Defaults::default()); + let report = harness::run(&manifest, &options()); + assert!( + report.passed(), + "{}", + serde_json::to_string_pretty(&report).unwrap() + ); + assert_eq!(report.summary.expected_failures, report.summary.total); + assert_eq!(report.summary.panics, 0); +} + +#[test] +fn expected_failure_never_hides_a_missing_input() { + // A provisioning error is not a restoration-stage failure. If the input + // does not exist, the case must fail even with expect_failure set. + let dir = tempfile::tempdir().unwrap(); + let mut spec = case("gone", Kind::Metadata, "absent.dat"); + spec.expect_failure = Some(true); + let manifest = write_manifest(dir.path(), vec![spec], Defaults::default()); + let report = harness::run(&manifest, &options()); + assert!(!report.passed()); + assert_eq!(report.cases[0].outcome, "invalid_case"); + assert!( + report.cases[0] + .failures + .iter() + .any(|f| f.contains("not a file")) + ); +} + +#[test] +fn expected_failure_never_hides_an_io_error_after_validation() { + // Validation sees a file, then the read fails (simulated with a path that + // is a file at validation time and unreadable at run time is hard on + // Windows, so instead assert the read-error path directly through a + // directory-shaped companion, which validates only as a file). + let dir = tempfile::tempdir().unwrap(); + write(dir.path(), "input.dat", &fixtures::obfuscated_metadata()); + let mut spec = case("io", Kind::Metadata, "input.dat"); + spec.expect_failure = Some(true); + // A companion is not read for metadata, but an unreadable companion on a + // PE case is an I/O error; use a directory that exists. + spec.companion = Some(PathBuf::from("a-directory")); + std::fs::create_dir(dir.path().join("a-directory")).unwrap(); + let manifest = write_manifest(dir.path(), vec![spec], Defaults::default()); + let report = harness::run(&manifest, &options()); + // Validation requires the companion to be a file, so this is invalid_case. + assert!(!report.passed()); + assert!(report.cases[0].outcome == "invalid_case"); +} + +#[test] +fn expected_failure_does_not_inflate_the_restored_count() { + let dir = tempfile::tempdir().unwrap(); + write(dir.path(), "input.dat", &fixtures::obfuscated_metadata()); + // One real success and one genuinely failing (non-metadata) input whose + // failure is declared. `passed` counts both; `restored` only the success. + write(dir.path(), "broken.dat", b"not metadata"); + let mut expected = case("expected", Kind::Metadata, "broken.dat"); + expected.expect_failure = Some(true); + let mut success = case("success", Kind::Metadata, "input.dat"); + success.allow_missing_golden = Some(true); + let manifest = write_manifest(dir.path(), vec![expected, success], Defaults::default()); + let report = harness::run(&manifest, &options()); + assert!( + report.passed(), + "{}", + serde_json::to_string_pretty(&report).unwrap() + ); + assert_eq!(report.summary.total, 2); + assert_eq!(report.summary.passed, 2); + assert_eq!(report.summary.expected_failures, 1); + assert_eq!( + report.summary.restored, 1, + "the declared failure must not count as a recovery" + ); +} + +#[test] +fn expected_failure_that_succeeds_is_reported_as_unmet() { + let dir = tempfile::tempdir().unwrap(); + write(dir.path(), "input.dat", &fixtures::obfuscated_metadata()); + let mut spec = case("unmet", Kind::Metadata, "input.dat"); + spec.expect_failure = Some(true); + let manifest = write_manifest(dir.path(), vec![spec], Defaults::default()); + let report = harness::run(&manifest, &options()); + assert!(!report.passed()); + assert_eq!(report.cases[0].outcome, "expected_failure_unmet"); + assert_eq!(report.summary.expected_failures, 0); + assert_eq!(report.summary.restored, 0); +} + +#[test] +fn expected_failure_counts_as_a_pass_but_not_a_restore() { + let dir = tempfile::tempdir().unwrap(); + write(dir.path(), "input.dat", b"not metadata"); + let mut spec = case("bad", Kind::Metadata, "input.dat"); + spec.expect_failure = Some(true); + let manifest = write_manifest(dir.path(), vec![spec], Defaults::default()); + let report = harness::run(&manifest, &options()); + assert!(report.passed()); + assert_eq!(report.summary.passed, 1); + assert_eq!(report.summary.expected_failures, 1); + assert_eq!(report.summary.restored, 0, "a failure is not a restore"); +} + +#[test] +fn app_level_expected_failure_is_not_a_restore() { + let dir = tempfile::tempdir().unwrap(); + let app = dir.path().join("app"); + std::fs::create_dir_all(app.join("lib/arm64-v8a")).unwrap(); + // ELF magic but not a protected library: the walk finds nothing, which is + // a provisioning error unless the case declares it. + std::fs::write(app.join("lib/arm64-v8a/libx.so"), b"\x7fELF").unwrap(); + let mut spec = case("app", Kind::AndroidApp, "app"); + spec.allow_empty = Some(true); + spec.expect_failure = Some(true); + let manifest = write_manifest(dir.path(), vec![spec], Defaults::default()); + let report = harness::run(&manifest, &options()); + assert!( + report.passed(), + "{}", + serde_json::to_string_pretty(&report).unwrap() + ); + assert_eq!(report.cases[0].outcome, "expected_failure"); + assert_eq!(report.summary.restored, 0); + assert_eq!(report.summary.expected_failures, 1); +} + +#[test] +fn unknown_manifest_fields_and_bad_schemas_are_rejected() { + let dir = tempfile::tempdir().unwrap(); + let text = + r#"{"schema":"wrong","cases":[{"id":"x","kind":"metadata","input":"a","surprise":1}]}"#; + let path = write(dir.path(), "manifest.json", text.as_bytes()); + let report = harness::run(&path, &options()); + assert!(!report.passed()); + assert!(report.manifest_errors[0].contains("parse manifest")); +} + +#[test] +fn undetected_pe_with_expected_failure_passes_truthfully() { + let dir = tempfile::tempdir().unwrap(); + write(dir.path(), "plain.exe", &fixtures::synthetic_plain_pe()); + let mut spec = case("plain", Kind::Pe, "plain.exe"); + spec.expect_failure = Some(true); + let manifest = write_manifest(dir.path(), vec![spec], Defaults::default()); + let report = harness::run(&manifest, &options()); + assert!( + report.passed(), + "{}", + serde_json::to_string_pretty(&report).unwrap() + ); + assert_eq!(report.cases[0].outcome, "expected_failure"); + assert!(report.cases[0].outputs[0].error.is_some()); +} + +#[test] +fn undetected_pe_without_expected_failure_is_an_unpack_failure() { + let dir = tempfile::tempdir().unwrap(); + write(dir.path(), "plain.exe", &fixtures::synthetic_plain_pe()); + let mut spec = case("plain", Kind::Pe, "plain.exe"); + spec.golden_sha256 = Some(sha256_hex(b"anything")); + let manifest = write_manifest(dir.path(), vec![spec], Defaults::default()); + let report = harness::run(&manifest, &options()); + assert!(!report.passed()); + assert_eq!(report.cases[0].outcome, "unpack_failed"); +} + +#[test] +fn emit_manifest_is_bounded_and_excludes_goldens_and_junctions() { + let dir = tempfile::tempdir().unwrap(); + write( + dir.path(), + "app.exe", + &fixtures::synthetic_crackproof_pe(false, false), + ); + write(dir.path(), "app.golden.exe", b"golden"); + write(dir.path(), "notes.txt", b"not a target"); + write(dir.path(), "plain.exe", &fixtures::synthetic_plain_pe()); + write( + dir.path(), + "global-metadata.dat", + &fixtures::obfuscated_metadata(), + ); + let out = dir.path().join("emitted.json"); + let count = harness::emit_manifest(&[dir.path().to_path_buf()], &[], &out).unwrap(); + assert_eq!(count, 2, "only the detected PE and the metadata blob"); + + let emitted: Manifest = serde_json::from_slice(&std::fs::read(&out).unwrap()).unwrap(); + let inputs: Vec = emitted + .cases + .iter() + .map(|case| case.input.display().to_string()) + .collect(); + assert!(inputs.iter().any(|input| input == "app.exe")); + assert!(inputs.iter().any(|input| input == "global-metadata.dat")); + assert!(!inputs.iter().any(|input| input.contains("golden"))); + assert!(!inputs.iter().any(|input| input.contains("notes.txt"))); + assert!(!inputs.iter().any(|input| input.contains("plain.exe"))); + let app = emitted + .cases + .iter() + .find(|case| case.input.ends_with("app.exe")) + .unwrap(); + assert_eq!(app.golden.as_deref(), Some(Path::new("app.golden.exe"))); +} + +#[test] +fn emit_manifest_requires_at_least_one_input() { + let dir = tempfile::tempdir().unwrap(); + std::fs::write(dir.path().join("nothing.txt"), b"x").unwrap(); + let out = dir.path().join("emitted.json"); + assert!(harness::emit_manifest(&[dir.path().to_path_buf()], &[], &out).is_err()); +} + +#[test] +fn android_app_case_resolves_entries_and_rejects_escapes() { + let dir = tempfile::tempdir().unwrap(); + let app = dir.path().join("app"); + std::fs::create_dir_all(app.join("lib/arm64-v8a")).unwrap(); + std::fs::write(app.join("lib/arm64-v8a/libx.so"), b"\x7fELF").unwrap(); + std::fs::write(dir.path().join("outside.so"), b"\x7fELF").unwrap(); + + let mut spec = case("app", Kind::AndroidApp, "app"); + spec.entries = Some(vec![harness::EntrySpec { + path: PathBuf::from("../outside.so"), + sha256: None, + golden: None, + golden_sha256: None, + metadata_sha256: None, + expect_failure: None, + }]); + let manifest = write_manifest(dir.path(), vec![spec], Defaults::default()); + let report = harness::run(&manifest, &options()); + assert!(!report.passed()); + assert!( + report.cases[0].outputs[0].entries[0] + .failures + .iter() + .any(|failure| failure.contains("escapes") || failure.contains("resolve")) + ); +} diff --git a/senbei-cli/tests/corpus_harness_panics.rs b/senbei-cli/tests/corpus_harness_panics.rs new file mode 100644 index 0000000..a4f026d --- /dev/null +++ b/senbei-cli/tests/corpus_harness_panics.rs @@ -0,0 +1,180 @@ +//! Focused tests for how the harness classifies surfaced engine panics. +//! +//! The engine converts a caught panic into `UnpackError::InternalPanic`; the +//! harness's outer `catch_unwind_quiet` therefore sees an ordinary `Err`. A +//! declared `expect_failure` must not swallow that: a panic is a defect. +//! +//! These tests use typed synthetic errors, so they need no protected input. +//! They pin the classifier and the report wiring, not the engine itself. + +#[path = "support/fixtures.rs"] +mod fixtures; +#[path = "support/harness.rs"] +mod harness; + +use std::path::{Path, PathBuf}; + +use harness::{CaseSpec, Defaults, Kind, Manifest, RunOptions}; + +fn internal_panic() -> senbei_engine::UnpackError { + senbei_engine::UnpackError::InternalPanic { + message: "synthetic".to_owned(), + file: "synthetic.rs".to_owned(), + line: 1, + column: 1, + } +} + +fn stage5_not_found() -> senbei_engine::UnpackError { + senbei_engine::UnpackError::Stage5MarkerNotFound +} + +#[test] +fn classifier_detects_direct_and_nested_internal_panics() { + assert!(harness::surfaced_internal_panic(&internal_panic())); + + let nested = senbei_engine::UnpackError::PipelineFallbackFailed { + dll: Box::new(stage5_not_found()), + exe: Box::new(internal_panic()), + }; + assert!(harness::surfaced_internal_panic(&nested)); + + let nested_dll = senbei_engine::UnpackError::PipelineFallbackFailed { + dll: Box::new(internal_panic()), + exe: Box::new(stage5_not_found()), + }; + assert!(harness::surfaced_internal_panic(&nested_dll)); + + let deep = senbei_engine::UnpackError::PipelineFallbackFailed { + dll: Box::new(nested), + exe: Box::new(stage5_not_found()), + }; + assert!(harness::surfaced_internal_panic(&deep)); +} + +#[test] +fn classifier_leaves_ordinary_restore_errors_alone() { + assert!(!harness::surfaced_internal_panic(&stage5_not_found())); + let ordinary_fallback = senbei_engine::UnpackError::PipelineFallbackFailed { + dll: Box::new(senbei_engine::UnpackError::NotCrackproof), + exe: Box::new(stage5_not_found()), + }; + assert!(!harness::surfaced_internal_panic(&ordinary_fallback)); +} + +#[test] +fn classifier_sees_a_panic_wrapped_in_anyhow_context() { + let wrapped = anyhow::Error::new(internal_panic()).context("restore protected library"); + assert!(harness::surfaced_internal_panic_in(&wrapped)); + let ordinary = anyhow::Error::new(stage5_not_found()).context("restore protected library"); + assert!(!harness::surfaced_internal_panic_in(&ordinary)); +} + +fn write_manifest(dir: &Path, cases: Vec) -> PathBuf { + let manifest = Manifest { + schema: harness::SCHEMA.to_owned(), + name: Some("panic-classification".to_owned()), + base_dir: None, + defaults: Defaults::default(), + cases, + }; + let path = dir.join("manifest.json"); + std::fs::write(&path, serde_json::to_vec_pretty(&manifest).unwrap()).unwrap(); + path +} + +fn case(id: &str, input: &str) -> CaseSpec { + CaseSpec { + id: id.to_owned(), + kind: Kind::Pe, + input: PathBuf::from(input), + companion: None, + golden: None, + golden_sha256: None, + sha256: None, + metadata_sha256: None, + expect_failure: None, + expect_suspect: None, + allow_missing_golden: None, + allow_suspect: None, + allow_empty: None, + entries: None, + } +} + +fn options() -> RunOptions { + RunOptions { + commit: Some("test-commit".to_owned()), + cwd: std::env::temp_dir(), + } +} + +/// The exact branch `run_pe` uses: a surfaced panic always yields outcome +/// `panic` and a failing case. A declared `expect_failure` must not change it. +#[test] +fn classify_keeps_a_surfaced_panic_failing_even_when_expected() { + for error in [ + internal_panic(), + senbei_engine::UnpackError::PipelineFallbackFailed { + dll: Box::new(stage5_not_found()), + exe: Box::new(internal_panic()), + }, + ] { + let mut output = harness::OutputReport::new("case"); + let mut report = harness::CaseReport::new_for_test("case"); + harness::classify_unpack_error(&mut output, &mut report, &error, true); + assert_eq!(output.status, "failed"); + assert_eq!(report.outcome, "panic"); + assert_eq!(report.status, "fail"); + assert!( + report.failures[0].contains("engine-internal panic surfaced"), + "{:?}", + report.failures + ); + } +} + +/// Ordinary restore-stage errors keep the existing policy. +#[test] +fn classify_keeps_normal_errors_declarable() { + let mut output = harness::OutputReport::new("case"); + let mut report = harness::CaseReport::new_for_test("case"); + harness::classify_unpack_error(&mut output, &mut report, &stage5_not_found(), true); + assert_eq!(report.outcome, "expected_failure"); + assert_eq!(report.status, "pass"); + + let mut output = harness::OutputReport::new("case"); + let mut report = harness::CaseReport::new_for_test("case"); + harness::classify_unpack_error(&mut output, &mut report, &stage5_not_found(), false); + assert_eq!(report.outcome, "unpack_failed"); + assert_eq!(report.status, "fail"); +} + +/// Report-level invariant: `summary.panics` counts exactly the cases whose +/// outcome is `panic`, and such a case can never make the run pass. +#[test] +fn report_panic_count_matches_panic_outcomes() { + let dir = tempfile::tempdir().unwrap(); + std::fs::write( + dir.path().join("input.exe"), + fixtures::synthetic_crackproof_pe(false, false), + ) + .unwrap(); + let mut spec = case("crackproof-header-only", "input.exe"); + spec.expect_failure = Some(true); + let manifest = write_manifest(dir.path(), vec![spec]); + + let report = harness::run(&manifest, &options()); + let panics = report + .cases + .iter() + .filter(|case| case.outcome == "panic") + .count(); + assert_eq!( + report.summary.panics, panics, + "summary.panics must count exactly the cases reported as panic" + ); + if panics > 0 { + assert!(!report.passed(), "a surfaced panic must fail the run"); + } +} diff --git a/senbei-cli/tests/support/fixtures.rs b/senbei-cli/tests/support/fixtures.rs new file mode 100644 index 0000000..0f07381 --- /dev/null +++ b/senbei-cli/tests/support/fixtures.rs @@ -0,0 +1,216 @@ +//! Synthetic byte fixtures shared by the local corpus harness tests and the +//! native/WASM parity test. +#![allow(dead_code)] // shared by several test targets; each uses a subset +//! +//! Everything here is generated from public format rules. No protected +//! binaries, product names, or real corpus paths appear in this file. + +/// il2cpp metadata sanity magic (`0xFAB11BAF`). +pub const METADATA_MAGIC: u32 = 0xFAB1_1BAF; +/// Structural transform version these fixtures describe. +pub const METADATA_VERSION: u32 = 31; + +const HDR_METHODS: usize = 0x30; +const HDR_TYPES: usize = 0xA0; +const HDR_IMAGES: usize = 0xA8; +const METHOD_STRIDE: usize = 0x24; +const METHOD_TOKEN_OFF: usize = 0x18; +const TYPE_STRIDE: usize = 0x58; +const TYPE_METHOD_START_OFF: usize = 0x24; +const TYPE_METHOD_COUNT_OFF: usize = 0x40; +const IMAGE_STRIDE: usize = 0x28; +const IMAGE_TYPE_START_OFF: usize = 0x08; +const IMAGE_TYPE_COUNT_OFF: usize = 0x0C; + +/// Build a structurally valid version-31 metadata image with two modules. +/// +/// Module 0 owns methods 0..2 and module 1 owns methods 2..5. Tokens are +/// written verbatim, so the caller chooses obfuscated (sparse) or canonical +/// (per-module contiguous) values. +pub fn synthetic_metadata(tokens: [u32; 5]) -> Vec { + let header = 0x100usize; + let images = header; + let image_count = 2usize; + let types = images + image_count * IMAGE_STRIDE; + let type_count = 2usize; + let methods = types + type_count * TYPE_STRIDE; + let method_count = tokens.len(); + let total = methods + method_count * METHOD_STRIDE; + let mut data = vec![0u8; total]; + + let put32 = |data: &mut [u8], offset: usize, value: u32| { + data[offset..offset + 4].copy_from_slice(&value.to_le_bytes()); + }; + let put16 = |data: &mut [u8], offset: usize, value: u16| { + data[offset..offset + 2].copy_from_slice(&value.to_le_bytes()); + }; + + put32(&mut data, 0, METADATA_MAGIC); + put32(&mut data, 4, METADATA_VERSION); + put32(&mut data, HDR_METHODS, methods as u32); + put32( + &mut data, + HDR_METHODS + 4, + (method_count * METHOD_STRIDE) as u32, + ); + put32(&mut data, HDR_TYPES, types as u32); + put32(&mut data, HDR_TYPES + 4, (type_count * TYPE_STRIDE) as u32); + put32(&mut data, HDR_IMAGES, images as u32); + put32( + &mut data, + HDR_IMAGES + 4, + (image_count * IMAGE_STRIDE) as u32, + ); + + put32(&mut data, images + IMAGE_TYPE_START_OFF, 0); + put32(&mut data, images + IMAGE_TYPE_COUNT_OFF, 1); + put32(&mut data, images + IMAGE_STRIDE + IMAGE_TYPE_START_OFF, 1); + put32(&mut data, images + IMAGE_STRIDE + IMAGE_TYPE_COUNT_OFF, 1); + + put32(&mut data, types + TYPE_METHOD_START_OFF, 0); + put16(&mut data, types + TYPE_METHOD_COUNT_OFF, 2); + put32(&mut data, types + TYPE_STRIDE + TYPE_METHOD_START_OFF, 2); + put16(&mut data, types + TYPE_STRIDE + TYPE_METHOD_COUNT_OFF, 3); + + for (index, token) in tokens.iter().enumerate() { + put32( + &mut data, + methods + index * METHOD_STRIDE + METHOD_TOKEN_OFF, + *token, + ); + } + data +} + +/// Canonical metadata: per-module tokens are already `1..=count`. +pub fn clean_metadata() -> Vec { + synthetic_metadata([ + 0x0600_0001, + 0x0600_0002, + 0x0600_0001, + 0x0600_0002, + 0x0600_0003, + ]) +} + +/// Obfuscated metadata: sparse tokens that the structural transform rewrites. +pub fn obfuscated_metadata() -> Vec { + synthetic_metadata([ + 0x0600_D49F, + 0x0600_FFFF, + 0x0600_1234, + 0x0600_ABCD, + 0x0600_5555, + ]) +} + +/// Named malformed metadata probes. Each must be rejected without a panic. +pub fn malformed_metadata_probes() -> Vec<(&'static str, Vec)> { + let base = obfuscated_metadata(); + let mut wrong_magic = base.clone(); + wrong_magic[0..4].copy_from_slice(&0xDEAD_BEEFu32.to_le_bytes()); + let mut unsupported = base.clone(); + unsupported[4..8].copy_from_slice(&30u32.to_le_bytes()); + let mut misaligned = base.clone(); + misaligned[HDR_METHODS + 4..HDR_METHODS + 8].copy_from_slice(&7u32.to_le_bytes()); + let mut out_of_range = base.clone(); + out_of_range[HDR_METHODS..HDR_METHODS + 4].copy_from_slice(&u32::MAX.to_le_bytes()); + let mut unowned = base.clone(); + unowned[types_offset() + TYPE_STRIDE + TYPE_METHOD_COUNT_OFF + ..types_offset() + TYPE_STRIDE + TYPE_METHOD_COUNT_OFF + 2] + .copy_from_slice(&2u16.to_le_bytes()); + let mut double_owned = base.clone(); + double_owned[types_offset() + TYPE_STRIDE + TYPE_METHOD_START_OFF + ..types_offset() + TYPE_STRIDE + TYPE_METHOD_START_OFF + 4] + .copy_from_slice(&1u32.to_le_bytes()); + vec![ + ("empty", Vec::new()), + ("prefix", b"MZ".to_vec()), + ("wrong_magic", wrong_magic), + ("unsupported_version", unsupported), + ("truncated_header", base[..0x20].to_vec()), + ("misaligned_methods", misaligned), + ("out_of_range_table", out_of_range), + ("unowned_method", unowned), + ("double_owned_method", double_owned), + ] +} + +fn types_offset() -> usize { + 0x100 + 2 * IMAGE_STRIDE +} + +/// Build a PE that the Crackproof detector classifies. +/// +/// Only the fields the detector reads are populated: the DOS/PE headers, the +/// COFF characteristics word, the optional-header magic, the CLR directory, +/// and the 8-dword key table at file offset 4096. +pub fn synthetic_crackproof_pe(dll: bool, managed: bool) -> Vec { + const PE_OFFSET: usize = 0x80; + const KEY_OFFSET: usize = 4096; + const KONN: u32 = 0x4E4E_4F4B; + + let mut data = vec![0u8; KEY_OFFSET + 32]; + data[0..2].copy_from_slice(b"MZ"); + data[0x3C..0x40].copy_from_slice(&(PE_OFFSET as u32).to_le_bytes()); + data[PE_OFFSET..PE_OFFSET + 4].copy_from_slice(b"PE\0\0"); + let characteristics: u16 = if dll { 0x2000 } else { 0 }; + data[PE_OFFSET + 4 + 18..PE_OFFSET + 4 + 20].copy_from_slice(&characteristics.to_le_bytes()); + data[PE_OFFSET + 20..PE_OFFSET + 22].copy_from_slice(&0xF0u16.to_le_bytes()); + data[PE_OFFSET + 24..PE_OFFSET + 26].copy_from_slice(&0x20Bu16.to_le_bytes()); + data[PE_OFFSET + 24 + 108..PE_OFFSET + 24 + 112].copy_from_slice(&16u32.to_le_bytes()); + let directories = PE_OFFSET + 24 + 112; + if managed { + data[directories + 14 * 8..directories + 14 * 8 + 4] + .copy_from_slice(&0x2000u32.to_le_bytes()); + data[directories + 14 * 8 + 4..directories + 14 * 8 + 8] + .copy_from_slice(&0x48u32.to_le_bytes()); + } + // keys[0] = 0 and keys[1] = keys[0] ^ cell, so cell = KONN makes the + // derived magic match. + data[KEY_OFFSET..KEY_OFFSET + 4].copy_from_slice(&0u32.to_le_bytes()); + data[KEY_OFFSET + 4..KEY_OFFSET + 8].copy_from_slice(&KONN.to_le_bytes()); + data +} + +/// A PE-shaped input whose derived magic is not the supported one. +pub fn synthetic_plain_pe() -> Vec { + let mut data = synthetic_crackproof_pe(false, false); + data[4096 + 4..4096 + 8].copy_from_slice(&0x1234_5678u32.to_le_bytes()); + data +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn synthetic_metadata_round_trips_through_the_parser() { + let (out, report) = senbei_metadata::deobfuscate(&obfuscated_metadata()).unwrap(); + assert_eq!(report.version, METADATA_VERSION); + assert_eq!(report.methods, 5); + assert_eq!(report.modules, 2); + assert_eq!(report.remapped, 5); + assert_eq!(out, clean_metadata()); + } + + #[test] + fn detection_fixture_matches_the_requested_kind() { + assert_eq!( + senbei_engine::detect(&synthetic_crackproof_pe(false, false)) + .map(|detected| detected.kind), + Some(senbei_engine::Kind::NativeExe) + ); + assert_eq!( + senbei_engine::detect(&synthetic_crackproof_pe(true, false)) + .map(|detected| detected.kind), + Some(senbei_engine::Kind::NativeDll) + ); + assert_eq!( + senbei_engine::detect(&synthetic_crackproof_pe(false, true)) + .map(|detected| detected.kind), + Some(senbei_engine::Kind::ManagedExe) + ); + assert!(senbei_engine::detect(&synthetic_plain_pe()).is_none()); + } +} diff --git a/senbei-cli/tests/support/harness.rs b/senbei-cli/tests/support/harness.rs new file mode 100644 index 0000000..b348bfd --- /dev/null +++ b/senbei-cli/tests/support/harness.rs @@ -0,0 +1,2093 @@ +//! Local, manifest-driven corpus harness. +//! +//! This module is compiled into `senbei-cli` integration tests and into the +//! `corpus_harness` example. It never walks a corpus on its own, never follows +//! junctions, never writes next to an input, and never uploads anything. +//! +//! # Manifest +//! +//! ```json +//! { +//! "schema": "senbei-corpus-harness/1", +//! "name": "local-corpus", +//! "base_dir": ".", +//! "defaults": { +//! "expect_failure": false, +//! "allow_missing_golden": false, +//! "allow_suspect": false, +//! "allow_empty": false +//! }, +//! "cases": [ +//! { +//! "id": "native-pe-1", +//! "kind": "pe", +//! "input": "app.exe", +//! "companion": "app.exe._", +//! "golden": "app.golden.exe" +//! }, +//! { +//! "id": "metadata-1", +//! "kind": "metadata", +//! "input": "global-metadata.dat", +//! "golden_sha256": "0123..." +//! }, +//! { +//! "id": "android-app-1", +//! "kind": "android-app", +//! "input": "app-tree" +//! } +//! ] +//! } +//! ``` +//! +//! `kind` is one of `pe`, `metadata`, `android-so`, or `android-app`. Inputs, +//! companions, goldens, and `base_dir` are resolved relative to the manifest's +//! directory unless absolute. Every non-`expect_failure` case must pin its +//! output with `golden`, `golden_sha256`, or `sha256`, or explicitly opt out +//! with `allow_missing_golden: true`. A missing golden, a mismatch, a length +//! difference, or a stale sidecar is reported as a failure; nothing is +//! regenerated. +//! +//! `android-so` and `android-app` cases also read the sidecars used by the +//! existing Android corpus (`.golden.so.sha256`, +//! `.golden.metadata.sha256`, `.restore-fails`) when no explicit +//! expectation is given. `android-app` with no `entries` performs a bounded +//! walk *inside the supplied app folder only* (no junctions, no `unpack` +//! directories) and checks every protected library it finds. Supplying +//! `entries` restricts the case to those relative files. +//! +//! # Report +//! +//! The report records the git commit used (caller-supplied or queried +//! locally), whether the worktree is dirty, the manifest SHA-256, per-case +//! byte counts/SHA-256 values, integrity findings, timings, and pass/fail +//! status. Restored bytes live in a temporary directory and are dropped. + +#![allow(dead_code)] // one module, several targets; each uses a subset + +use std::collections::BTreeSet; +use std::io::Write; +use std::path::{Path, PathBuf}; +use std::process::Command; +use std::time::{Instant, SystemTime, UNIX_EPOCH}; + +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; + +pub const SCHEMA: &str = "senbei-corpus-harness/1"; +pub const REPORT_SCHEMA: &str = "senbei-corpus-report/1"; +const MANIFEST_SCHEMA: &str = "senbei-corpus-manifest/1"; +const MAX_APP_DEPTH: usize = 32; +const MAX_APP_ENTRIES: usize = 100_000; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)] +#[serde(rename_all = "kebab-case")] +pub enum Kind { + Pe, + Metadata, + AndroidSo, + AndroidApp, +} + +impl Kind { + fn as_str(self) -> &'static str { + match self { + Self::Pe => "pe", + Self::Metadata => "metadata", + Self::AndroidSo => "android-so", + Self::AndroidApp => "android-app", + } + } +} + +#[derive(Debug, Default, Clone, Deserialize, Serialize)] +#[serde(default, deny_unknown_fields)] +pub struct Defaults { + pub expect_failure: bool, + pub allow_missing_golden: bool, + pub allow_suspect: bool, + pub allow_empty: bool, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub struct Manifest { + pub schema: String, + #[serde(default)] + pub name: Option, + #[serde(default)] + pub base_dir: Option, + #[serde(default)] + pub defaults: Defaults, + pub cases: Vec, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub struct CaseSpec { + pub id: String, + pub kind: Kind, + pub input: PathBuf, + #[serde(default)] + pub companion: Option, + #[serde(default)] + pub golden: Option, + #[serde(default)] + pub golden_sha256: Option, + #[serde(default)] + pub sha256: Option, + #[serde(default)] + pub metadata_sha256: Option, + #[serde(default)] + pub expect_failure: Option, + #[serde(default)] + pub expect_suspect: Option, + #[serde(default)] + pub allow_missing_golden: Option, + #[serde(default)] + pub allow_suspect: Option, + #[serde(default)] + pub allow_empty: Option, + #[serde(default)] + pub entries: Option>, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub struct EntrySpec { + pub path: PathBuf, + #[serde(default)] + pub sha256: Option, + #[serde(default)] + pub golden: Option, + #[serde(default)] + pub golden_sha256: Option, + #[serde(default)] + pub metadata_sha256: Option, + #[serde(default)] + pub expect_failure: Option, +} + +#[derive(Debug, Clone, Default)] +pub struct RunOptions { + /// Caller-supplied commit. A local query result is still recorded, and a + /// dirty worktree is never hidden. + pub commit: Option, + /// Directory used for `git` discovery when the manifest is outside a repo. + pub cwd: PathBuf, +} + +#[derive(Debug, Serialize)] +pub struct Report { + pub schema: &'static str, + pub generated_unix_ms: u64, + pub harness_version: String, + pub git: GitInfo, + pub manifest: ManifestInfo, + pub options: OptionsInfo, + pub cases: Vec, + pub manifest_errors: Vec, + pub summary: Summary, + pub timings: Timings, + pub status: String, +} + +impl Report { + pub fn passed(&self) -> bool { + self.status == "pass" + } +} + +#[derive(Debug, Clone, Serialize)] +pub struct GitInfo { + pub is_repo: bool, + pub worktree: Option, + pub head: Option, + pub head_source: String, + pub caller_commit: Option, + pub local_head: Option, + pub dirty: Option, + pub modified: usize, + pub untracked: usize, + pub status_count: usize, + pub status_error: Option, +} + +#[derive(Debug, Serialize)] +pub struct ManifestInfo { + pub path: String, + pub sha256: String, + pub name: Option, + pub declared_schema: String, + pub base_dir: String, + pub case_count: usize, +} + +#[derive(Debug, Serialize)] +pub struct OptionsInfo { + pub caller_commit: Option, +} + +#[derive(Debug, Default, Serialize)] +pub struct Summary { + pub total: usize, + pub passed: usize, + pub failed: usize, + pub panics: usize, + /// Declared failures that failed as expected. These are reported as + /// `passed` by the exit-status rule, but they are **not** recovery + /// successes, so they are counted separately from `restored`. + pub expected_failures: usize, + /// Cases whose operation actually produced output (or, for an Android app, + /// whose protected libraries all restored). This is the only recovery + /// count; expected failures never inflate it. + pub restored: usize, + pub integrity_failures: usize, + pub golden_mismatches: usize, + pub missing_goldens: usize, +} + +#[derive(Debug, Default, Serialize)] +pub struct Timings { + pub total_ms: u64, +} + +#[derive(Debug, Serialize)] +pub struct CaseReport { + pub id: String, + pub kind: String, + pub input: String, + pub status: String, + pub outcome: String, + pub expect_failure: bool, + pub allow_missing_golden: bool, + pub duration_ms: u64, + pub outputs: Vec, + pub failures: Vec, + pub notes: Vec, + pub error: Option, +} + +impl CaseReport { + fn new(case: &CaseSpec, base: &Path) -> Self { + Self { + id: case.id.clone(), + kind: case.kind.as_str().to_owned(), + input: resolved_display(base, &case.input), + status: "fail".to_owned(), + outcome: "not_run".to_owned(), + expect_failure: false, + allow_missing_golden: false, + duration_ms: 0, + outputs: Vec::new(), + failures: Vec::new(), + notes: Vec::new(), + error: None, + } + } + + /// Bare shell for focused classification tests (no manifest needed). + pub fn new_for_test(id: &str) -> Self { + Self { + id: id.to_owned(), + kind: "pe".to_owned(), + input: id.to_owned(), + status: "fail".to_owned(), + outcome: "not_run".to_owned(), + expect_failure: false, + allow_missing_golden: false, + duration_ms: 0, + outputs: Vec::new(), + failures: Vec::new(), + notes: Vec::new(), + error: None, + } + } + + fn fail(&mut self, outcome: &str, message: impl Into) { + self.status = "fail".to_owned(); + self.outcome = outcome.to_owned(); + self.failures.push(message.into()); + } + + fn pass(&mut self, outcome: &str) { + self.status = "pass".to_owned(); + self.outcome = outcome.to_owned(); + } +} + +#[derive(Debug, Serialize)] +pub struct OutputReport { + pub label: String, + pub status: String, + pub detected_kind: Option, + pub bytes: Option, + pub sha256: Option, + pub expected_sha256: Option, + pub expected_source: Option, + pub golden: Option, + pub golden_bytes: Option, + pub remapped: Option, + pub integrity: Option, + pub entries: Vec, + pub duration_ms: u64, + pub error: Option, + pub notes: Vec, + pub failures: Vec, +} + +impl OutputReport { + pub fn new(label: impl Into) -> Self { + Self { + label: label.into(), + status: "failed".to_owned(), + detected_kind: None, + bytes: None, + sha256: None, + expected_sha256: None, + expected_source: None, + golden: None, + golden_bytes: None, + remapped: None, + integrity: None, + entries: Vec::new(), + duration_ms: 0, + error: None, + notes: Vec::new(), + failures: Vec::new(), + } + } + + fn fail(&mut self, message: impl Into) { + self.status = "failed".to_owned(); + self.failures.push(message.into()); + } +} + +#[derive(Debug, Serialize)] +pub struct IntegrityInfo { + pub ok: bool, + pub fatal: bool, + pub issues: Vec, +} + +#[derive(Debug, Serialize)] +pub struct EntryReport { + pub input: String, + pub status: String, + pub expected_failure: bool, + pub bytes: Option, + pub sha256: Option, + pub expected_sha256: Option, + pub expected_source: Option, + pub embedded_sha256: Option, + pub embedded_expected_sha256: Option, + pub golden: Option, + pub duration_ms: u64, + pub error: Option, + pub notes: Vec, + pub failures: Vec, +} + +impl EntryReport { + fn new(input: impl Into) -> Self { + Self { + input: input.into(), + status: "failed".to_owned(), + expected_failure: false, + bytes: None, + sha256: None, + expected_sha256: None, + expected_source: None, + embedded_sha256: None, + embedded_expected_sha256: None, + golden: None, + duration_ms: 0, + error: None, + notes: Vec::new(), + failures: Vec::new(), + } + } + + fn fail(&mut self, message: impl Into) { + self.status = "failed".to_owned(); + self.failures.push(message.into()); + } + + fn pass(&mut self) { + self.status = "pass".to_owned(); + } +} + +/// Run a manifest and return the report. Manifest parse/IO failures are +/// represented in the report, never panicked. +pub fn run(manifest_path: &Path, options: &RunOptions) -> Report { + let started = Instant::now(); + let absolute = absolute_path(manifest_path); + let base = absolute + .parent() + .map(Path::to_path_buf) + .unwrap_or_else(|| PathBuf::from(".")); + let (raw, manifest_sha256) = match std::fs::read(&absolute) { + Ok(raw) => { + let digest = sha256_hex(&raw); + (Some(raw), digest) + } + Err(error) => { + return fatal_report( + &absolute, + &base, + options, + "", + Vec::new(), + format!("read manifest: {error}"), + started, + ); + } + }; + let raw = raw.unwrap_or_default(); + let manifest: Manifest = match serde_json::from_slice(&raw) { + Ok(manifest) => manifest, + Err(error) => { + return fatal_report( + &absolute, + &base, + options, + &manifest_sha256, + Vec::new(), + format!("parse manifest: {error}"), + started, + ); + } + }; + let mut manifest_errors = Vec::new(); + if manifest.schema != SCHEMA { + manifest_errors.push(format!( + "schema mismatch: manifest declares {:?}, expected {SCHEMA:?}", + manifest.schema + )); + } + if manifest.cases.is_empty() { + manifest_errors.push("manifest contains no cases".to_owned()); + } + let base_dir = manifest + .base_dir + .as_ref() + .map(|path| absolute_from(&base, path)) + .unwrap_or_else(|| base.clone()); + let base_dir = absolute_path(&base_dir); + + let mut seen = BTreeSet::new(); + let duplicate: BTreeSet = manifest + .cases + .iter() + .filter_map(|case| { + if seen.insert(case.id.clone()) { + None + } else { + Some(case.id.clone()) + } + }) + .collect(); + for id in &duplicate { + manifest_errors.push(format!("duplicate case id {id:?}")); + } + + let mut cases = Vec::with_capacity(manifest.cases.len()); + for spec in &manifest.cases { + let effective_expect_failure = spec + .expect_failure + .unwrap_or(manifest.defaults.expect_failure); + let effective_allow_missing = spec + .allow_missing_golden + .unwrap_or(manifest.defaults.allow_missing_golden); + let effective_allow_suspect = spec + .allow_suspect + .unwrap_or(manifest.defaults.allow_suspect); + let effective_allow_empty = spec.allow_empty.unwrap_or(manifest.defaults.allow_empty); + let mut report = CaseReport::new(spec, &base_dir); + report.expect_failure = effective_expect_failure; + report.allow_missing_golden = effective_allow_missing; + if duplicate.contains(&spec.id) { + report.fail("invalid_case", format!("duplicate case id {:?}", spec.id)); + cases.push(report); + continue; + } + let validation = validate_case( + spec, + &base_dir, + effective_expect_failure, + effective_allow_missing, + effective_allow_empty, + ); + if !validation.is_empty() { + report.outcome = "invalid_case".to_owned(); + report.failures.extend(validation); + cases.push(report); + continue; + } + let start = Instant::now(); + let outcome = senbei_engine::catch_unwind_quiet(|| { + run_case( + spec, + &base_dir, + effective_expect_failure, + effective_allow_missing, + effective_allow_suspect, + effective_allow_empty, + ) + }); + report.duration_ms = elapsed_ms(start); + match outcome { + Ok(result) => cases.push(result), + Err(payload) => { + report.fail("panic", format!("panic: {}", panic_message(&payload))); + report.error = Some(report.failures.join("; ")); + cases.push(report); + } + } + } + + let summary = summarize(&cases, &manifest_errors); + let status = if summary.failed == 0 && manifest_errors.is_empty() { + "pass" + } else { + "fail" + }; + let git = git_info(options, &base); + Report { + schema: REPORT_SCHEMA, + generated_unix_ms: now_ms(), + harness_version: env!("CARGO_PKG_VERSION").to_owned(), + git, + manifest: ManifestInfo { + path: absolute.display().to_string(), + sha256: manifest_sha256, + name: manifest.name.clone(), + declared_schema: manifest.schema.clone(), + base_dir: base_dir.display().to_string(), + case_count: manifest.cases.len(), + }, + options: OptionsInfo { + caller_commit: options.commit.clone(), + }, + cases, + manifest_errors, + summary, + timings: Timings { + total_ms: elapsed_ms(started), + }, + status: status.to_owned(), + } +} + +fn fatal_report( + manifest_path: &Path, + base: &Path, + options: &RunOptions, + manifest_sha256: &str, + cases: Vec, + error: String, + started: Instant, +) -> Report { + Report { + schema: REPORT_SCHEMA, + generated_unix_ms: now_ms(), + harness_version: env!("CARGO_PKG_VERSION").to_owned(), + git: git_info(options, base), + manifest: ManifestInfo { + path: manifest_path.display().to_string(), + sha256: manifest_sha256.to_owned(), + name: None, + declared_schema: String::new(), + base_dir: base.display().to_string(), + case_count: 0, + }, + options: OptionsInfo { + caller_commit: options.commit.clone(), + }, + cases, + manifest_errors: vec![error], + summary: Summary::default(), + timings: Timings { + total_ms: elapsed_ms(started), + }, + status: "fail".to_owned(), + } +} + +fn summarize(cases: &[CaseReport], manifest_errors: &[String]) -> Summary { + let mut summary = Summary { + total: cases.len(), + ..Summary::default() + }; + for case in cases { + if case.status == "pass" { + summary.passed += 1; + } else { + summary.failed += 1; + } + if case.outcome == "panic" { + summary.panics += 1; + } + if case.outcome == "expected_failure" { + summary.expected_failures += 1; + } + if case.status == "pass" && case.outcome != "expected_failure" { + summary.restored += 1; + } + if case + .failures + .iter() + .any(|failure| failure.contains("integrity") || failure.contains("suspect")) + { + summary.integrity_failures += 1; + } + if case.outcome == "golden_mismatch" { + summary.golden_mismatches += 1; + } + if case.outcome == "golden_missing" { + summary.missing_goldens += 1; + } + } + if !manifest_errors.is_empty() && summary.failed == 0 { + summary.failed = 1; + } + summary +} + +fn validate_case( + spec: &CaseSpec, + base: &Path, + expect_failure: bool, + allow_missing: bool, + allow_empty: bool, +) -> Vec { + let mut errors = Vec::new(); + if spec.id.trim().is_empty() { + errors.push("case id is empty".to_owned()); + } + let input = absolute_from(base, &spec.input); + match spec.kind { + Kind::Pe | Kind::Metadata | Kind::AndroidSo => { + if !input.is_file() { + errors.push(format!("input is not a file: {}", input.display())); + } + } + Kind::AndroidApp => { + if !input.is_dir() { + errors.push(format!("input is not a directory: {}", input.display())); + } + } + } + if let Some(companion) = &spec.companion { + let companion = absolute_from(base, companion); + if !companion.is_file() { + errors.push(format!("companion is not a file: {}", companion.display())); + } + } + if let Some(golden) = &spec.golden { + let golden = absolute_from(base, golden); + if !golden.is_file() { + errors.push(format!("golden is missing: {}", golden.display())); + } + } + for (name, value) in [ + ("golden_sha256", spec.golden_sha256.as_deref()), + ("sha256", spec.sha256.as_deref()), + ("metadata_sha256", spec.metadata_sha256.as_deref()), + ] { + if let Some(value) = value + && !is_sha256(value) + { + errors.push(format!("{name} is not a 64-hex SHA-256: {value:?}")); + } + } + if spec.entries.is_some() && spec.kind != Kind::AndroidApp { + errors.push("entries are only valid for kind android-app".to_owned()); + } + for entry in spec.entries.iter().flatten() { + for (name, value) in [ + ("sha256", entry.sha256.as_deref()), + ("golden_sha256", entry.golden_sha256.as_deref()), + ("metadata_sha256", entry.metadata_sha256.as_deref()), + ] { + if let Some(value) = value + && !is_sha256(value) + { + errors.push(format!( + "entry {:?} {name} is not a 64-hex SHA-256: {value:?}", + entry.path + )); + } + } + if entry.path.is_absolute() { + errors.push(format!( + "entry path must be relative: {}", + entry.path.display() + )); + } + } + if !expect_failure && spec.kind != Kind::AndroidApp { + let declared = + spec.golden.is_some() || spec.golden_sha256.is_some() || spec.sha256.is_some(); + if !declared && !allow_missing { + errors.push( + "no expected output declared: add golden, golden_sha256, or sha256, \ + or set allow_missing_golden" + .to_owned(), + ); + } + } + if spec.kind == Kind::AndroidApp + && spec.entries.as_ref().is_some_and(Vec::is_empty) + && !allow_empty + { + errors.push("android-app case declares an empty entries list".to_owned()); + } + errors +} + +fn run_case( + spec: &CaseSpec, + base: &Path, + expect_failure: bool, + allow_missing: bool, + allow_suspect: bool, + allow_empty: bool, +) -> CaseReport { + let mut report = CaseReport::new(spec, base); + report.expect_failure = expect_failure; + report.allow_missing_golden = allow_missing; + match spec.kind { + Kind::Pe => run_pe( + spec, + base, + &mut report, + expect_failure, + allow_missing, + allow_suspect, + ), + Kind::Metadata => run_metadata(spec, base, &mut report, expect_failure, allow_missing), + Kind::AndroidSo => run_android_so(spec, base, &mut report, expect_failure, allow_missing), + Kind::AndroidApp => run_android_app( + spec, + base, + &mut report, + expect_failure, + allow_missing, + allow_empty, + ), + } + report +} + +fn run_pe( + spec: &CaseSpec, + base: &Path, + report: &mut CaseReport, + expect_failure: bool, + allow_missing: bool, + allow_suspect: bool, +) { + let start = Instant::now(); + let mut output = OutputReport::new(spec.id.clone()); + let input = absolute_from(base, &spec.input); + let input_bytes = match std::fs::read(&input) { + Ok(bytes) => bytes, + Err(error) => { + report.fail("read_error", format!("read input: {error}")); + report.outputs.push(output); + return; + } + }; + let companion = match &spec.companion { + Some(path) => { + let path = absolute_from(base, path); + match std::fs::read(&path) { + Ok(bytes) => Some(bytes), + Err(error) => { + report.fail("read_error", format!("read companion: {error}")); + report.outputs.push(output); + return; + } + } + } + None => None, + }; + // An expected failure needs no output expectation: the failure itself is + // the assertion. Only a successful run is compared. + let expectation = if expect_failure { + None + } else { + match expectation(spec, base, allow_missing) { + Ok(expectation) => expectation, + Err(error) => { + report.fail("golden_missing", error); + report.outputs.push(output); + return; + } + } + }; + let expected = expectation.as_ref(); + match senbei_io::job::unpack_bytes(&input_bytes, companion.as_deref()) { + Ok(image) => { + output.detected_kind = Some(kind_name(image.kind).to_owned()); + output.bytes = Some(image.bytes.len() as u64); + output.sha256 = Some(sha256_hex(&image.bytes)); + output.integrity = Some(IntegrityInfo { + ok: image.integrity.ok(), + fatal: image.integrity.has_fatal(), + issues: image.integrity.issues.clone(), + }); + if expect_failure { + output.fail("expected failure, but the input unpacked"); + report.fail( + "expected_failure_unmet", + "expected failure, but the input unpacked", + ); + } else { + compare_output( + &mut output, + &image.bytes, + expected, + allow_suspect, + &image.integrity.issues, + ); + finish_case(report, &mut output, "unpacked"); + } + } + Err(error) => { + output.error = Some(error.to_string()); + classify_unpack_error(&mut output, report, &error, expect_failure); + } + } + output.duration_ms = elapsed_ms(start); + report.outputs.push(output); +} + +fn run_metadata( + spec: &CaseSpec, + base: &Path, + report: &mut CaseReport, + expect_failure: bool, + allow_missing: bool, +) { + let start = Instant::now(); + let mut output = OutputReport::new(spec.id.clone()); + let input = absolute_from(base, &spec.input); + let bytes = match std::fs::read(&input) { + Ok(bytes) => bytes, + Err(error) => { + report.fail("read_error", format!("read input: {error}")); + report.outputs.push(output); + return; + } + }; + let expectation = if expect_failure { + None + } else { + match expectation(spec, base, allow_missing) { + Ok(expectation) => expectation, + Err(error) => { + report.fail("golden_missing", error); + report.outputs.push(output); + return; + } + } + }; + let expected = expectation.as_ref(); + match senbei_metadata::deobfuscate(&bytes) { + Ok((out, result)) => { + output.bytes = Some(out.len() as u64); + output.remapped = Some(result.remapped as u64); + output.sha256 = Some(sha256_hex(&out)); + if expect_failure { + output.fail("expected failure, but the metadata transformed"); + report.fail( + "expected_failure_unmet", + "expected failure, but the metadata transformed", + ); + } else { + compare_output(&mut output, &out, expected, true, &[]); + finish_case(report, &mut output, "transformed"); + } + } + Err(error) => { + output.error = Some(error.to_string()); + if expect_failure { + output.status = "pass".to_owned(); + output.notes.push("expected failure observed".to_owned()); + report.pass("expected_failure"); + } else { + output.fail(format!("metadata transform failed: {error}")); + report.fail( + "metadata_failed", + format!("metadata transform failed: {error}"), + ); + } + } + } + output.duration_ms = elapsed_ms(start); + report.outputs.push(output); +} + +fn run_android_so( + spec: &CaseSpec, + base: &Path, + report: &mut CaseReport, + expect_failure: bool, + allow_missing: bool, +) { + let start = Instant::now(); + let mut output = OutputReport::new(spec.id.clone()); + let input = absolute_from(base, &spec.input); + let temporary = match tempfile::tempdir() { + Ok(temporary) => temporary, + Err(error) => { + report.fail( + "workspace_error", + format!("create temporary workspace: {error}"), + ); + report.outputs.push(output); + return; + } + }; + let dest = temporary.path().join("restored.so"); + let effective_expect_failure = spec + .expect_failure + .unwrap_or(expect_failure || known_failure_marker(&input)); + let (expectation, embedded_expectation) = if effective_expect_failure { + (None, None) + } else { + let expectation = match android_expectation(spec, base, &input, allow_missing, None) { + Ok(expectation) => expectation, + Err(error) => { + report.fail("golden_missing", error); + report.outputs.push(output); + return; + } + }; + let embedded_expectation = match android_embedded_expectation(spec, base, &input, None) { + Ok(expectation) => expectation, + Err(error) => { + report.fail("golden_missing", error); + report.outputs.push(output); + return; + } + }; + (expectation, embedded_expectation) + }; + let mut entry = EntryReport::new(resolved_display(base, &spec.input)); + entry.expected_failure = effective_expect_failure; + match senbei_io::android::restore_so_file(&input, &dest, false) { + Ok(embedded) => { + let restored = match std::fs::read(&dest) { + Ok(bytes) => bytes, + Err(error) => { + entry.fail(format!("read restored output: {error}")); + output.entries.push(entry); + report.fail("output_error", "read restored output"); + report.outputs.push(output); + return; + } + }; + entry.bytes = Some(restored.len() as u64); + entry.sha256 = Some(sha256_hex(&restored)); + if effective_expect_failure { + entry.fail("expected failure, but the library restored"); + report.fail( + "expected_failure_unmet", + "expected failure, but the library restored", + ); + } else { + apply_android_expectation(&mut entry, expectation.as_ref()); + if let Some(expected) = &embedded_expectation { + match &embedded { + Some(blob) => { + let actual = sha256_hex(blob); + entry.embedded_sha256 = Some(actual.clone()); + compare_hash( + &mut entry, + Some(actual.as_str()), + Some(expected), + "embedded metadata", + ); + } + None => entry.fail( + "restored library has no embedded metadata, but an expected hash was declared", + ), + } + } else if let Some(blob) = &embedded { + entry.embedded_sha256 = Some(sha256_hex(blob)); + } + if entry.failures.is_empty() { + entry.pass(); + report.pass("restored"); + } else { + report.fail("golden_mismatch", entry.failures.join("; ")); + } + } + } + Err(error) => { + entry.error = Some(error.to_string()); + if surfaced_internal_panic_in(&error) { + entry.fail(format!("engine-internal panic surfaced: {error}")); + report.fail("panic", format!("engine-internal panic surfaced: {error}")); + } else if effective_expect_failure { + entry.status = "pass".to_owned(); + entry.notes.push("expected failure observed".to_owned()); + report.pass("expected_failure"); + } else { + entry.fail(format!("restore failed: {error}")); + report.fail("restore_failed", format!("restore failed: {error}")); + } + } + } + output.entries.push(entry); + output.duration_ms = elapsed_ms(start); + report.outputs.push(output); +} + +fn run_android_app( + spec: &CaseSpec, + base: &Path, + report: &mut CaseReport, + expect_failure: bool, + allow_missing: bool, + allow_empty: bool, +) { + let start = Instant::now(); + let mut output = OutputReport::new(spec.id.clone()); + let app = absolute_from(base, &spec.input); + let app_canonical = match app.canonicalize() { + Ok(path) => path, + Err(error) => { + report.fail("read_error", format!("canonicalize app folder: {error}")); + report.outputs.push(output); + return; + } + }; + let mut targets = Vec::new(); + match &spec.entries { + Some(entries) => { + for entry in entries { + match resolve_entry(&app_canonical, &entry.path) { + Ok(path) => targets.push((path, Some(entry))), + Err(error) => { + let mut result = EntryReport::new(entry.path.display().to_string()); + result.fail(error); + output.entries.push(result); + } + } + } + } + None => match collect_protected_so(&app_canonical) { + Ok(found) => { + targets.extend(found.into_iter().map(|path| (path, None))); + } + Err(error) => { + report.fail("walk_error", error); + report.outputs.push(output); + return; + } + }, + } + if targets.is_empty() && output.entries.is_empty() && !allow_empty { + report.fail( + "no_entries", + "android-app case found no protected libraries", + ); + report.outputs.push(output); + return; + } + let temporary = match tempfile::tempdir() { + Ok(temporary) => temporary, + Err(error) => { + report.fail( + "workspace_error", + format!("create temporary workspace: {error}"), + ); + report.outputs.push(output); + return; + } + }; + for (index, (input, entry_spec)) in targets.iter().enumerate() { + let entry_start = Instant::now(); + let relative = input + .strip_prefix(&app_canonical) + .unwrap_or(input) + .display() + .to_string(); + let mut result = EntryReport::new(relative); + let dest = temporary.path().join(format!("entry-{index}.so")); + let effective_expect_failure = entry_spec + .and_then(|entry| entry.expect_failure) + .unwrap_or(expect_failure || known_failure_marker(input)); + result.expected_failure = effective_expect_failure; + // A known-failure marker is the assertion. Demanding an output hash for + // an input that is expected to fail would turn a documented gap into a + // golden-missing error. + let (expectation, embedded_expectation) = if effective_expect_failure { + (None, None) + } else { + let expectation = + match android_expectation(spec, base, input, allow_missing, *entry_spec) { + Ok(expectation) => expectation, + Err(error) => { + result.fail(error); + result.duration_ms = elapsed_ms(entry_start); + output.entries.push(result); + continue; + } + }; + let embedded_expectation = + match android_embedded_expectation(spec, base, input, *entry_spec) { + Ok(expectation) => expectation, + Err(error) => { + result.fail(error); + result.duration_ms = elapsed_ms(entry_start); + output.entries.push(result); + continue; + } + }; + (expectation, embedded_expectation) + }; + match senbei_io::android::restore_so_file(input, &dest, false) { + Ok(embedded) => { + let restored = match std::fs::read(&dest) { + Ok(bytes) => bytes, + Err(error) => { + result.fail(format!("read restored output: {error}")); + result.duration_ms = elapsed_ms(entry_start); + output.entries.push(result); + continue; + } + }; + result.bytes = Some(restored.len() as u64); + result.sha256 = Some(sha256_hex(&restored)); + if effective_expect_failure { + result.fail("expected failure, but the library restored"); + } else { + apply_android_expectation(&mut result, expectation.as_ref()); + if let Some(expected) = &embedded_expectation { + match &embedded { + Some(blob) => { + let actual = sha256_hex(blob); + result.embedded_sha256 = Some(actual.clone()); + compare_hash( + &mut result, + Some(actual.as_str()), + Some(expected), + "embedded metadata", + ); + } + None => result.fail( + "restored library has no embedded metadata, but an expected hash was declared", + ), + } + } else if let Some(blob) = &embedded { + result.embedded_sha256 = Some(sha256_hex(blob)); + } + if result.failures.is_empty() { + result.pass(); + } + } + } + Err(error) => { + result.error = Some(error.to_string()); + if surfaced_internal_panic_in(&error) { + result.fail(format!("engine-internal panic surfaced: {error}")); + result + .notes + .push("surfaced panic is not a known failure".to_owned()); + } else if effective_expect_failure { + result.status = "pass".to_owned(); + result.notes.push("known failure observed".to_owned()); + } else { + result.fail(format!("restore failed: {error}")); + } + } + } + result.duration_ms = elapsed_ms(entry_start); + output.entries.push(result); + } + let failed = output.entries.iter().any(|entry| entry.status != "pass"); + let surfaced_panic = output.entries.iter().any(|entry| { + entry + .failures + .iter() + .any(|failure| failure.contains("engine-internal panic surfaced")) + }); + output.duration_ms = elapsed_ms(start); + if failed { + let messages: Vec = output + .entries + .iter() + .flat_map(|entry| { + entry + .failures + .iter() + .map(|failure| format!("{}: {failure}", entry.input)) + }) + .collect(); + // A surfaced panic must be visible in `summary.panics`, not folded + // into an ordinary per-entry failure. + let outcome = if surfaced_panic { + "panic" + } else { + "entry_failed" + }; + report.fail(outcome, messages.join("; ")); + } else if expect_failure { + // Every entry failed as declared: the case passes, but it is an + // expected failure, not a recovery. + report.pass("expected_failure"); + } else { + report.pass("restored"); + } + report.outputs.push(output); +} + +fn finish_case(report: &mut CaseReport, output: &mut OutputReport, success: &str) { + if output.failures.is_empty() { + output.status = "ok".to_owned(); + report.pass(success); + } else { + let outcome = if output.failures.iter().any(|f| f.contains("golden")) { + "golden_mismatch" + } else if output.failures.iter().any(|f| f.contains("integrity")) { + "integrity_failed" + } else { + "failed" + }; + report.fail(outcome, output.failures.join("; ")); + } +} + +fn compare_output( + output: &mut OutputReport, + actual: &[u8], + expected: Option<&Expectation>, + allow_suspect: bool, + integrity_issues: &[String], +) { + if let Some(expected) = expected { + output.expected_sha256 = Some(expected.sha256.clone()); + output.expected_source = Some(expected.source.clone()); + output.golden = expected + .golden + .as_ref() + .map(|path| path.display().to_string()); + output.golden_bytes = expected.golden_bytes; + if let Some(bytes) = expected.golden_bytes + && bytes != actual.len() as u64 + { + output.fail(format!( + "golden length differs: got {} want {bytes}", + actual.len() + )); + } else { + let actual_sha = sha256_hex(actual); + if actual_sha != expected.sha256 { + output.fail(format!( + "golden digest differs: got {actual_sha} want {}", + expected.sha256 + )); + } + } + } + if !integrity_issues.is_empty() && !allow_suspect { + output.fail(format!( + "integrity check failed: {}", + integrity_issues.join("; ") + )); + } else if !integrity_issues.is_empty() { + output + .notes + .push("integrity warnings accepted by allow_suspect".to_owned()); + } +} + +fn apply_android_expectation(entry: &mut EntryReport, expected: Option<&Expectation>) { + let Some(expected) = expected else { + return; + }; + entry.expected_sha256 = Some(expected.sha256.clone()); + entry.expected_source = Some(expected.source.clone()); + entry.golden = expected + .golden + .as_ref() + .map(|path| path.display().to_string()); + let actual = entry.sha256.clone(); + compare_hash(entry, actual.as_deref(), Some(expected), "restored library"); +} + +fn compare_hash( + entry: &mut EntryReport, + actual: Option<&str>, + expected: Option<&Expectation>, + label: &str, +) { + let (Some(actual), Some(expected)) = (actual, expected) else { + return; + }; + if actual != expected.sha256 { + entry.fail(format!( + "{label} digest differs: got {actual} want {}", + expected.sha256 + )); + } +} + +struct Expectation { + sha256: String, + source: String, + golden: Option, + golden_bytes: Option, +} + +fn expectation( + spec: &CaseSpec, + base: &Path, + allow_missing: bool, +) -> Result, String> { + let declared = declared_hashes(spec.golden_sha256.as_deref(), spec.sha256.as_deref())?; + if let Some(golden) = &spec.golden { + let golden = absolute_from(base, golden); + let bytes = std::fs::read(&golden) + .map_err(|error| format!("read golden {}: {error}", golden.display()))?; + let actual = sha256_hex(&bytes); + if let Some(declared) = &declared + && declared != &actual + { + return Err(format!( + "manifest inconsistency: golden {} hashes to {actual}, but the manifest declares {declared}", + golden.display() + )); + } + return Ok(Some(Expectation { + sha256: actual, + source: "golden".to_owned(), + golden: Some(golden), + golden_bytes: Some(bytes.len() as u64), + })); + } + if let Some(declared) = declared { + return Ok(Some(Expectation { + sha256: declared, + source: "manifest".to_owned(), + golden: None, + golden_bytes: None, + })); + } + if allow_missing { + Ok(None) + } else { + Err("no expected output declared and allow_missing_golden is false".to_owned()) + } +} + +fn declared_hashes(a: Option<&str>, b: Option<&str>) -> Result, String> { + match (a, b) { + (Some(a), Some(b)) if a != b => Err(format!( + "conflicting expected hashes: golden_sha256 {a:?} vs sha256 {b:?}" + )), + (Some(a), _) => Ok(Some(a.to_owned())), + (None, Some(b)) => Ok(Some(b.to_owned())), + (None, None) => Ok(None), + } +} + +fn android_expectation( + spec: &CaseSpec, + base: &Path, + input: &Path, + allow_missing: bool, + entry: Option<&EntrySpec>, +) -> Result, String> { + if let Some(entry) = entry { + if let Some(golden) = &entry.golden { + return golden_expectation(base, golden, entry.golden_sha256.as_deref()); + } + if let Some(sha) = entry.golden_sha256.as_deref().or(entry.sha256.as_deref()) { + return Ok(Some(manifest_expectation(sha))); + } + } + if let Some(golden) = &spec.golden { + return golden_expectation(base, golden, spec.golden_sha256.as_deref()); + } + if let Some(declared) = declared_hashes(spec.golden_sha256.as_deref(), spec.sha256.as_deref())? + { + return Ok(Some(manifest_expectation(&declared))); + } + if let Some(sidecar) = read_sidecar(&android_sidecar(input, "so"))? { + return Ok(Some(Expectation { + sha256: sidecar, + source: "sidecar".to_owned(), + golden: None, + golden_bytes: None, + })); + } + if allow_missing { + Ok(None) + } else { + Err(format!( + "no expected restored hash and no sidecar at {}", + android_sidecar(input, "so").display() + )) + } +} + +fn android_embedded_expectation( + spec: &CaseSpec, + base: &Path, + input: &Path, + entry: Option<&EntrySpec>, +) -> Result, String> { + if let Some(entry) = entry { + if let Some(golden) = &entry.golden { + let golden = absolute_from(base, golden); + let bytes = std::fs::read(&golden) + .map_err(|error| format!("read golden {}: {error}", golden.display()))?; + let actual = sha256_hex(&bytes); + if let Some(declared) = entry.metadata_sha256.as_deref() + && declared != actual + { + return Err(format!( + "manifest inconsistency: golden {} hashes to {actual}, but the manifest declares {declared}", + golden.display() + )); + } + return Ok(Some(Expectation { + sha256: actual, + source: "golden".to_owned(), + golden: Some(golden), + golden_bytes: Some(bytes.len() as u64), + })); + } + if let Some(declared) = &entry.metadata_sha256 { + return Ok(Some(manifest_expectation(declared))); + } + } + if entry.is_none() + && let Some(declared) = &spec.metadata_sha256 + { + return Ok(Some(manifest_expectation(declared))); + } + if let Some(sidecar) = read_sidecar(&android_sidecar(input, "metadata"))? { + return Ok(Some(Expectation { + sha256: sidecar, + source: "sidecar".to_owned(), + golden: None, + golden_bytes: None, + })); + } + Ok(None) +} + +fn manifest_expectation(sha256: &str) -> Expectation { + Expectation { + sha256: sha256.to_owned(), + source: "manifest".to_owned(), + golden: None, + golden_bytes: None, + } +} + +fn golden_expectation( + base: &Path, + golden: &Path, + declared: Option<&str>, +) -> Result, String> { + let golden = absolute_from(base, golden); + let bytes = std::fs::read(&golden) + .map_err(|error| format!("read golden {}: {error}", golden.display()))?; + let actual = sha256_hex(&bytes); + if let Some(declared) = declared + && declared != actual + { + return Err(format!( + "manifest inconsistency: golden {} hashes to {actual}, but the manifest declares {declared}", + golden.display() + )); + } + Ok(Some(Expectation { + sha256: actual, + source: "golden".to_owned(), + golden: Some(golden), + golden_bytes: Some(bytes.len() as u64), + })) +} + +fn android_sidecar(input: &Path, artifact: &str) -> PathBuf { + let name = input + .file_name() + .map(|name| name.to_string_lossy().into_owned()) + .unwrap_or_default(); + let stem = name + .strip_suffix(".so") + .or_else(|| name.strip_suffix(".SO")) + .unwrap_or(&name); + input.with_file_name(format!("{stem}.golden.{artifact}.sha256")) +} + +fn known_failure_marker(input: &Path) -> bool { + let name = input + .file_name() + .map(|name| name.to_string_lossy().into_owned()) + .unwrap_or_default(); + let stem = name + .strip_suffix(".so") + .or_else(|| name.strip_suffix(".SO")) + .unwrap_or(&name); + input + .with_file_name(format!("{stem}.restore-fails")) + .is_file() +} + +fn read_sidecar(path: &Path) -> Result, String> { + match std::fs::read_to_string(path) { + Ok(text) => { + let text = text.trim().to_ascii_lowercase(); + if !is_sha256(&text) { + return Err(format!( + "sidecar {} is not a 64-hex SHA-256", + path.display() + )); + } + Ok(Some(text)) + } + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None), + Err(error) => Err(format!("read sidecar {}: {error}", path.display())), + } +} + +fn resolve_entry(app: &Path, relative: &Path) -> Result { + if relative.is_absolute() { + return Err(format!( + "entry path must be relative: {}", + relative.display() + )); + } + let candidate = app.join(relative); + let canonical = candidate + .canonicalize() + .map_err(|error| format!("resolve entry {}: {error}", candidate.display()))?; + if !canonical.starts_with(app) { + return Err(format!( + "entry escapes the app folder: {}", + relative.display() + )); + } + if !canonical.is_file() { + return Err(format!("entry is not a file: {}", relative.display())); + } + if has_reparse_component(app, &canonical) { + return Err(format!( + "entry path crosses a reparse point: {}", + relative.display() + )); + } + Ok(canonical) +} + +fn has_reparse_component(app: &Path, file: &Path) -> bool { + let mut current = app.to_path_buf(); + let Ok(relative) = file.strip_prefix(app) else { + return true; + }; + for component in relative.components() { + current.push(component); + if is_reparse_point(¤t) { + return true; + } + } + false +} + +#[cfg(windows)] +fn is_reparse_point(path: &Path) -> bool { + use std::os::windows::fs::MetadataExt; + const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x400; + std::fs::symlink_metadata(path) + .map(|metadata| metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0) + .unwrap_or(false) +} + +#[cfg(not(windows))] +fn is_reparse_point(path: &Path) -> bool { + std::fs::symlink_metadata(path) + .map(|metadata| metadata.file_type().is_symlink()) + .unwrap_or(false) +} + +fn collect_protected_so(app: &Path) -> Result, String> { + let mut found = Vec::new(); + let mut visited = 0usize; + walk_so(app, 0, &mut found, &mut visited)?; + found.sort(); + found.retain(|path| senbei_io::android::is_protected_so_file(path)); + Ok(found) +} + +fn walk_so( + directory: &Path, + depth: usize, + found: &mut Vec, + visited: &mut usize, +) -> Result<(), String> { + if depth > MAX_APP_DEPTH { + return Err(format!( + "app folder exceeds the {MAX_APP_DEPTH}-level nesting ceiling" + )); + } + let entries = std::fs::read_dir(directory) + .map_err(|error| format!("read {}: {error}", directory.display()))?; + for entry in entries { + let entry = entry.map_err(|error| format!("read directory entry: {error}"))?; + *visited += 1; + if *visited > MAX_APP_ENTRIES { + return Err(format!( + "app folder exceeds the {MAX_APP_ENTRIES}-entry ceiling" + )); + } + let path = entry.path(); + let metadata = entry + .metadata() + .map_err(|error| format!("read metadata for {}: {error}", path.display()))?; + if metadata.is_dir() { + if path + .file_name() + .is_some_and(|name| name.eq_ignore_ascii_case("unpack")) + { + continue; + } + if is_reparse_point(&path) { + continue; + } + walk_so(&path, depth + 1, found, visited)?; + } else if metadata.is_file() + && !is_reparse_point(&path) + && path + .extension() + .and_then(|ext| ext.to_str()) + .is_some_and(|ext| ext.eq_ignore_ascii_case("so")) + { + found.push(path); + } + } + Ok(()) +} + +/// Emit a manifest for explicit inputs. `roots` are scanned at their top +/// level only (no recursion); `android_apps` become `android-app` cases whose +/// walk happens later, inside the supplied folder only. +pub fn emit_manifest( + roots: &[PathBuf], + android_apps: &[PathBuf], + out: &Path, +) -> Result { + let base = roots + .first() + .map(|root| absolute_path(root)) + .unwrap_or_else(|| PathBuf::from(".")); + let mut cases = Vec::new(); + let mut seen = BTreeSet::new(); + for root in roots { + let root = absolute_path(root); + let entries = std::fs::read_dir(&root) + .map_err(|error| format!("read {}: {error}", root.display()))?; + let mut files: Vec = entries + .filter_map(|entry| entry.ok().map(|entry| entry.path())) + .filter(|path| is_regular_non_reparse_file(path)) + .collect(); + files.sort(); + for path in files { + if !is_emittable_input(&path) { + continue; + } + let name = match path.file_name().and_then(|name| name.to_str()) { + Some(name) => name.to_owned(), + None => continue, + }; + let id = name.clone(); + if !seen.insert(id.clone()) { + continue; + } + let extension = path + .extension() + .and_then(|ext| ext.to_str()) + .unwrap_or("") + .to_ascii_lowercase(); + let stem = path + .file_stem() + .and_then(|stem| stem.to_str()) + .unwrap_or_default(); + let golden = path.with_file_name(format!("{stem}.golden.{extension}")); + let companion = { + let mut companion_name = path + .file_name() + .map(|name| name.to_os_string()) + .unwrap_or_default(); + companion_name.push("._"); + let companion = path.with_file_name(companion_name); + companion.is_file().then_some(companion) + }; + let relative = path.strip_prefix(&base).unwrap_or(&path).to_path_buf(); + let kind = if extension == "dat" { + Kind::Metadata + } else { + Kind::Pe + }; + let mut case = CaseSpec { + id, + kind, + input: relative, + companion: companion + .map(|path| path.strip_prefix(&base).unwrap_or(&path).to_path_buf()), + golden: None, + golden_sha256: None, + sha256: None, + metadata_sha256: None, + expect_failure: None, + expect_suspect: None, + allow_missing_golden: None, + allow_suspect: None, + allow_empty: None, + entries: None, + }; + if golden.is_file() { + case.golden = Some(golden.strip_prefix(&base).unwrap_or(&golden).to_path_buf()); + } + cases.push(case); + } + } + for app in android_apps { + let app = absolute_path(app); + let name = app + .file_name() + .map(|name| name.to_string_lossy().into_owned()) + .unwrap_or_else(|| "android-app".to_owned()); + let mut id = format!("android-app:{name}"); + let mut suffix = 1usize; + while !seen.insert(id.clone()) { + suffix += 1; + id = format!("android-app:{name}:{suffix}"); + } + cases.push(CaseSpec { + id, + kind: Kind::AndroidApp, + input: app, + companion: None, + golden: None, + golden_sha256: None, + sha256: None, + metadata_sha256: None, + expect_failure: None, + expect_suspect: None, + allow_missing_golden: None, + allow_suspect: None, + allow_empty: None, + entries: None, + }); + } + if cases.is_empty() { + return Err("no inputs found for the emitted manifest".to_owned()); + } + let manifest = Manifest { + schema: SCHEMA.to_owned(), + name: Some(MANIFEST_SCHEMA.to_owned()), + base_dir: Some(base.clone()), + defaults: Defaults::default(), + cases, + }; + let text = serde_json::to_string_pretty(&manifest) + .map_err(|error| format!("serialize manifest: {error}"))?; + write_atomic(out, text.as_bytes()).map_err(|error| format!("write manifest: {error}"))?; + Ok(manifest.cases.len()) +} + +fn is_regular_non_reparse_file(path: &Path) -> bool { + path.is_file() && !is_reparse_point(path) +} + +fn is_emittable_input(path: &Path) -> bool { + let Some(name) = path.file_name().and_then(|name| name.to_str()) else { + return false; + }; + if name.contains(".golden.") || name.ends_with("._") { + return false; + } + let Some(extension) = path.extension().and_then(|ext| ext.to_str()) else { + return false; + }; + let extension = extension.to_ascii_lowercase(); + if extension != "exe" && extension != "dll" && extension != "dat" { + return false; + } + if extension == "dat" { + let Ok(mut file) = std::fs::File::open(path) else { + return false; + }; + let mut magic = [0u8; 4]; + use std::io::Read; + if file.read_exact(&mut magic).is_err() { + return false; + } + return u32::from_le_bytes(magic) == 0xFAB1_1BAF; + } + let Ok(mut file) = std::fs::File::open(path) else { + return false; + }; + let mut prefix = vec![0u8; 8 * 1024]; + use std::io::Read; + let read = file.read(&mut prefix).unwrap_or(0); + prefix.truncate(read); + senbei_engine::detect(&prefix).is_some() +} + +/// Write a report atomically: a uniquely named temporary in the destination +/// directory, flushed and synced, then persisted over the destination. +pub fn write_atomic(dest: &Path, bytes: &[u8]) -> std::io::Result<()> { + let parent = dest + .parent() + .filter(|parent| !parent.as_os_str().is_empty()) + .unwrap_or_else(|| Path::new(".")); + std::fs::create_dir_all(parent)?; + let mut temporary = tempfile::Builder::new() + .prefix(".senbei-harness-") + .suffix(".tmp") + .tempfile_in(parent)?; + temporary.write_all(bytes)?; + temporary.flush()?; + temporary.as_file().sync_all()?; + temporary + .persist(dest) + .map(|_| ()) + .map_err(|error| error.error) +} + +fn git_info(options: &RunOptions, manifest_base: &Path) -> GitInfo { + let mut info = GitInfo { + is_repo: false, + worktree: None, + head: options.commit.clone(), + head_source: if options.commit.is_some() { + "caller".to_owned() + } else { + "none".to_owned() + }, + caller_commit: options.commit.clone(), + local_head: None, + dirty: None, + modified: 0, + untracked: 0, + status_count: 0, + status_error: None, + }; + let Some(root) = find_git_root(manifest_base).or_else(|| find_git_root(&options.cwd)) else { + info.status_error = Some("not a git worktree (or git is unavailable)".to_owned()); + return info; + }; + info.is_repo = true; + info.worktree = Some(root.display().to_string()); + match git_capture(&root, &["rev-parse", "HEAD"]) { + Ok(head) if !head.is_empty() => { + info.local_head = Some(head.clone()); + if options.commit.is_none() { + info.head = Some(head); + info.head_source = "local".to_owned(); + } + } + Ok(_) => { + info.status_error = Some("git rev-parse HEAD returned nothing".to_owned()); + } + Err(error) => { + info.status_error = Some(error); + } + } + match git_capture(&root, &["status", "--porcelain"]) { + Ok(status) => { + let lines: Vec<&str> = status.lines().filter(|line| !line.is_empty()).collect(); + info.status_count = lines.len(); + info.dirty = Some(!lines.is_empty()); + info.untracked = lines.iter().filter(|line| line.starts_with("??")).count(); + info.modified = info.status_count - info.untracked; + } + Err(error) => { + info.status_error = Some(match info.status_error { + Some(existing) => format!("{existing}; {error}"), + None => error, + }); + } + } + info +} + +fn find_git_root(dir: &Path) -> Option { + let dir = absolute_path(dir); + let output = Command::new("git") + .arg("-C") + .arg(&dir) + .args(["rev-parse", "--show-toplevel"]) + .output() + .ok()?; + if !output.status.success() { + return None; + } + let text = String::from_utf8_lossy(&output.stdout).trim().to_owned(); + (!text.is_empty()).then(|| PathBuf::from(text)) +} + +fn git_capture(root: &Path, args: &[&str]) -> Result { + let output = Command::new("git") + .arg("-C") + .arg(root) + .args(args) + .output() + .map_err(|error| format!("run git {:?}: {error}", args))?; + if !output.status.success() { + return Err(format!( + "git {:?} failed: {}", + args, + String::from_utf8_lossy(&output.stderr).trim() + )); + } + Ok(String::from_utf8_lossy(&output.stdout).trim().to_owned()) +} + +fn kind_name(kind: senbei_engine::Kind) -> &'static str { + match kind { + senbei_engine::Kind::NativeExe => "native-exe", + senbei_engine::Kind::ManagedExe => "managed-exe", + senbei_engine::Kind::NativeDll => "native-dll", + senbei_engine::Kind::ManagedDll => "managed-dll", + } +} + +fn sha256_hex(bytes: &[u8]) -> String { + let mut digest = Sha256::new(); + digest.update(bytes); + let mut out = String::with_capacity(64); + for byte in digest.finalize() { + out.push_str(&format!("{byte:02x}")); + } + out +} + +fn is_sha256(value: &str) -> bool { + value.len() == 64 && value.bytes().all(|byte| byte.is_ascii_hexdigit()) +} + +fn resolved_display(base: &Path, path: &Path) -> String { + absolute_from(base, path).display().to_string() +} + +fn absolute_from(base: &Path, path: &Path) -> PathBuf { + if path.is_absolute() { + path.to_path_buf() + } else { + base.join(path) + } +} + +fn absolute_path(path: &Path) -> PathBuf { + if path.is_absolute() { + path.to_path_buf() + } else { + std::env::current_dir() + .map(|cwd| cwd.join(path)) + .unwrap_or_else(|_| path.to_path_buf()) + } +} + +fn elapsed_ms(start: Instant) -> u64 { + u64::try_from(start.elapsed().as_millis()).unwrap_or(u64::MAX) +} + +fn now_ms() -> u64 { + u64::try_from( + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_millis(), + ) + .unwrap_or(u64::MAX) +} + +/// True when `error` **surfaces** an engine-internal panic. +/// +/// The engine converts a caught panic into `UnpackError::InternalPanic`; the +/// outer `catch_unwind_quiet` therefore sees an ordinary `Err`, not a panic. +/// A DLL-first run that falls back to the EXE pipeline wraps both candidate +/// errors in `PipelineFallbackFailed`, so the internal panic can be nested. +/// Walk the wrapper recursively so a panic cannot masquerade as an ordinary +/// restore-stage failure (in particular under `expect_failure`). +/// +/// Scope: this detects panics the engine converted and returned. It says +/// nothing about a worker-thread panic that was swallowed by a successful +/// fallback — that state is not observable from the returned `Result`. +/// Apply the PE error policy to `error`. +/// +/// Kept separate so the panic-vs-expected-failure decision can be tested with +/// typed errors that no synthetic input reliably produces: +/// +/// * a surfaced engine panic is always outcome `panic` and always fails the +/// case, regardless of `expect_failure`; +/// * any other error is a declared `expected_failure` when requested; +/// * otherwise it is an ordinary `unpack_failed`. +pub fn classify_unpack_error( + output: &mut OutputReport, + report: &mut CaseReport, + error: &senbei_engine::UnpackError, + expect_failure: bool, +) { + if surfaced_internal_panic(error) { + // An engine panic is a defect, never a declared outcome — even when the + // case declared expect_failure. The outer catch never sees it because + // the engine converts it to an Err. + output.fail(format!("engine-internal panic surfaced: {error}")); + report.fail("panic", format!("engine-internal panic surfaced: {error}")); + } else if expect_failure { + output.status = "pass".to_owned(); + output.notes.push("expected failure observed".to_owned()); + report.pass("expected_failure"); + } else { + output.fail(format!("unpack failed: {error}")); + report.fail("unpack_failed", format!("unpack failed: {error}")); + } +} + +/// Like [`surfaced_internal_panic`], for the `anyhow` errors the Android +/// orchestration returns. Android engines do not currently convert panics into +/// a typed error (a panic reaches the outer `catch_unwind_quiet`), but if one +/// is ever wrapped in a context chain the harness must still not accept it as +/// an expected failure. +pub fn surfaced_internal_panic_in(error: &anyhow::Error) -> bool { + error.chain().any(|cause| { + cause + .downcast_ref::() + .is_some_and(surfaced_internal_panic) + }) +} + +pub fn surfaced_internal_panic(error: &senbei_engine::UnpackError) -> bool { + match error { + senbei_engine::UnpackError::InternalPanic { .. } => true, + senbei_engine::UnpackError::PipelineFallbackFailed { dll, exe } => { + surfaced_internal_panic(dll) || surfaced_internal_panic(exe) + } + _ => false, + } +} + +fn panic_message(payload: &(dyn std::any::Any + Send)) -> String { + if let Some(message) = payload.downcast_ref::<&str>() { + (*message).to_owned() + } else if let Some(message) = payload.downcast_ref::() { + message.clone() + } else { + "".to_owned() + } +}