use std::fs;
use std::io;
use std::path::Path;
use thiserror::Error;
use crate::bundle::MANIFEST;
use crate::manifest::{sha256_hex, Manifest};
#[derive(Debug, Error)]
pub enum VerifyError {
#[error("{file}: the manifest could not be read: {source}")]
ManifestIo {
file: std::path::PathBuf,
source: io::Error,
},
#[error("{file}: the manifest could not be read: {source}")]
ManifestDecode {
file: std::path::PathBuf,
source: serde_json::Error,
},
#[error("{file}: the manifest lists it, the bundle does not have it")]
Missing {
file: String,
},
#[error("{file}: sha256 is {found}, the manifest says {listed}")]
Hash {
file: String,
found: String,
listed: String,
},
#[error("{file}: {found} data rows, the manifest says {listed}")]
Rows {
file: String,
found: usize,
listed: usize,
},
}
pub fn verify(dir: &Path) -> Result<(), VerifyError> {
let path = dir.join(MANIFEST);
let text = fs::read_to_string(&path).map_err(|source| VerifyError::ManifestIo {
file: path.clone(),
source,
})?;
let manifest = Manifest::from_json(&text)
.map_err(|source| VerifyError::ManifestDecode { file: path, source })?;
for entry in &manifest.files {
fault(dir, entry)?;
}
Ok(())
}
fn fault(dir: &Path, entry: &crate::manifest::FileEntry) -> Result<(), VerifyError> {
let path = dir.join(&entry.name);
let bytes = fs::read(&path).map_err(|_| VerifyError::Missing {
file: entry.name.clone(),
})?;
let found = sha256_hex(&bytes);
if found != entry.sha256 {
return Err(VerifyError::Hash {
file: entry.name.clone(),
found,
listed: entry.sha256.clone(),
});
}
let counted = data_rows(&String::from_utf8_lossy(&bytes));
if counted != entry.rows {
return Err(VerifyError::Rows {
file: entry.name.clone(),
found: counted,
listed: entry.rows,
});
}
Ok(())
}
fn data_rows(text: &str) -> usize {
text.lines()
.skip(1)
.filter(|line| !line.trim().is_empty())
.count()
}
#[cfg(test)]
mod tests {
use std::fs;
use super::*;
fn write_bundle(dir: &Path) {
fs::create_dir_all(dir).unwrap();
fs::write(dir.join("meters.csv"), "id,watts\n1,60\n").unwrap();
let spec = crate::FileSpec {
path: dir.join("meters.csv"),
keep_columns: vec!["id".to_owned(), "watts".to_owned()],
};
crate::bundle(
&[spec],
dir,
std::collections::BTreeMap::new(),
"2026-01-01T00:00:00Z",
&[],
)
.unwrap();
}
#[test]
fn a_bundle_the_way_it_was_written_verifies() {
let home = crate::bundle::unique_directory();
write_bundle(&home);
verify(&home).unwrap_or_else(|error| panic!("the bundle verifies: {error}"));
}
#[test]
fn a_tampered_byte_makes_verify_fail_naming_that_file() {
let home = crate::bundle::unique_directory();
write_bundle(&home);
let path = home.join("meters.csv");
let text = fs::read_to_string(&path).unwrap();
fs::write(&path, text.replace("60", "61")).unwrap();
let error = verify(&home).expect_err("the file's bytes changed");
assert!(
matches!(error, VerifyError::Hash { ref file, .. } if file == "meters.csv"),
"got {error}"
);
assert!(error.to_string().contains("meters.csv"), "got {error}");
}
#[test]
fn a_file_the_manifest_lists_but_the_bundle_does_not_hold_is_named() {
let home = crate::bundle::unique_directory();
write_bundle(&home);
fs::remove_file(home.join("meters.csv")).unwrap();
let error = verify(&home).expect_err("the file is gone");
assert!(
matches!(error, VerifyError::Missing { ref file } if file == "meters.csv"),
"got {error}"
);
}
#[test]
fn a_changed_row_count_is_named() {
let home = crate::bundle::unique_directory();
write_bundle(&home);
let path = home.join("meters.csv");
let header = fs::read_to_string(&path)
.unwrap()
.lines()
.next()
.unwrap()
.to_owned();
fs::write(&path, format!("{header}\n")).unwrap();
let manifest_path = home.join("manifest.json");
let manifest = fs::read_to_string(&manifest_path).unwrap();
let listed = recorded_sha(&manifest);
let found = crate::manifest::sha256_hex(&fs::read(&path).unwrap());
fs::write(&manifest_path, manifest.replace(&listed, &found)).unwrap();
let error = verify(&home).expect_err("the row count changed");
assert!(
matches!(error, VerifyError::Rows { ref file, found: 0, listed: 1 } if file == "meters.csv"),
"got {error}"
);
}
fn recorded_sha(manifest: &str) -> String {
let start = manifest.find("\"sha256\":\"").unwrap() + "\"sha256\":\"".len();
let end = manifest[start..].find('"').unwrap() + start;
manifest[start..end].to_owned()
}
#[test]
fn data_rows_do_not_count_the_header_or_a_trailing_blank_line() {
assert_eq!(data_rows("id\n1\n2\n"), 2);
assert_eq!(data_rows("id\n"), 0);
assert_eq!(data_rows(""), 0);
}
#[test]
fn text_that_is_not_a_manifest_is_refused() {
let home = crate::bundle::unique_directory();
fs::create_dir_all(&home).unwrap();
fs::write(home.join("manifest.json"), "{}").unwrap();
let error = verify(&home).expect_err("an empty object is not a manifest");
assert!(
matches!(error, VerifyError::ManifestDecode { .. }),
"got {error}"
);
}
#[test]
fn a_missing_manifest_is_refused() {
let home = crate::bundle::unique_directory();
fs::create_dir_all(&home).unwrap();
let error = verify(&home).expect_err("there is no manifest");
assert!(
matches!(error, VerifyError::ManifestIo { .. }),
"got {error}"
);
}
}