test(corpus): add commit-linked local regression reports

This commit is contained in:
Momoko-Ayase committed 2026-11-05 22:15:09 +08:00
1 parent 3fff15ed9a
commit e0dc177885
7 files changed
+3079

No files matched your search

Generated
+3
View File
@@ -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",
]
+3
View File
@@ -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
+130
View File
@@ -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 <sha>
//! 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<PathBuf> = None;
let mut report: Option<PathBuf> = None;
let mut commit: Option<String> = None;
let mut emit_roots: Vec<PathBuf> = Vec::new();
let mut android_apps: Vec<PathBuf> = Vec::new();
let mut manifest_out: Option<PathBuf> = 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."
);
}
+454
View File
@@ -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<CaseSpec>, 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<String> = 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"))
);
}
+180
View File
@@ -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<CaseSpec>) -> 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");
}
}
+216
View File
@@ -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<u8> {
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<u8> {
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<u8> {
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<u8>)> {
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<u8> {
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<u8> {
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());
}
}
File diff suppressed because it is too large. Load diff