use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;
fn crate_dir() -> &'static Path {
Path::new(env!("CARGO_MANIFEST_DIR"))
}
fn program() -> &'static str {
env!("CARGO_BIN_EXE_legit-hamming")
}
#[cfg(target_os = "linux")]
mod accept {
use std::fs;
use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};
use std::process::{Command, Output, Stdio};
use std::time::{Duration, Instant, SystemTime};
use legit_hamming::{Records, Value, snapshot};
use serde_json::Value as Json;
use super::{crate_dir, program};
use crate::support::TempDir;
const SET: &str = "images-pdq";
const ID: &str = "2026-12-02T12-00-00Z";
fn script() -> PathBuf {
crate_dir().join("deploy/legit-hamming-accept")
}
struct Root(TempDir);
impl Root {
fn new() -> Self {
let root = Self(TempDir::new());
fs::create_dir_all(root.inbox()).expect("the inbox");
fs::create_dir_all(root.set()).expect("the set directory");
root.settings("");
root
}
fn path(&self) -> &Path {
&self.0.0
}
fn inbox(&self) -> PathBuf {
self.path().join("inbox").join(SET)
}
fn set(&self) -> PathBuf {
self.path().join("sets").join(SET)
}
fn staging(&self) -> PathBuf {
self.path().join("staging").join(SET)
}
fn rejected(&self) -> PathBuf {
self.path().join("rejected").join(SET)
}
fn conf(&self) -> PathBuf {
self.path().join("accept.conf")
}
fn lock(&self) -> PathBuf {
self.path().join("accept.lock")
}
fn settings(&self, extra: &str) {
let text = format!(
"ROOT={}\nSETS=\"{SET}\"\nBIN={}\nVERIFY_USER=\"\"\nLOCK={}\nQUIET_SECONDS=0\n{extra}\n",
self.path().display(),
program(),
self.lock().display()
);
fs::write(self.conf(), text).expect("the settings");
fs::set_permissions(self.conf(), fs::Permissions::from_mode(0o644)).expect("mode 0644");
}
fn run(&self) -> Output {
self.command().output().expect("bash runs the script")
}
fn command(&self) -> Command {
let mut command = Command::new("bash");
command
.arg(script())
.env("LEGIT_HAMMING_ACCEPT_CONF", self.conf())
.stdin(Stdio::null());
command
}
fn accept(&self) -> String {
succeeded(&self.run())
}
fn upload<V: Value>(&self, name: &str, records: &Records<V>, current: Option<&str>) -> PathBuf {
let dir = self.inbox().join(name);
snapshot::write(&dir, records, 100).expect("the snapshot is written");
if let Some(current) = current {
fs::write(dir.join("CURRENT"), format!("{current}\n")).expect("its CURRENT");
}
dir
}
fn status(&self) -> Json {
let text =
fs::read_to_string(self.path().join("status").join(format!("{SET}.json"))).expect("a status file");
serde_json::from_str(&text).expect("the status file is JSON")
}
fn reason(&self, name: &str) -> Json {
let text = fs::read_to_string(self.rejected().join(format!("{name}.reason.json"))).expect("a reason file");
serde_json::from_str(&text).expect("the reason file is JSON")
}
fn current(&self) -> Option<String> {
let path = self.set().join("CURRENT");
assert!(!path.is_symlink(), "the set's CURRENT is never a link");
fs::read_to_string(path).ok().map(|text| text.trim_end().to_owned())
}
}
fn succeeded(output: &Output) -> String {
let stdout = String::from_utf8_lossy(&output.stdout).into_owned();
assert_eq!(
output.status.code(),
Some(0),
"the script exits 0: {stdout}{}",
String::from_utf8_lossy(&output.stderr)
);
stdout
}
fn names(dir: &Path) -> Vec<String> {
let mut names: Vec<String> = fs::read_dir(dir)
.map(|entries| {
entries
.map(|entry| entry.expect("an entry").file_name().into_string().expect("UTF-8"))
.collect()
})
.unwrap_or_default();
names.sort();
names
}
fn wide(seed: u64) -> Records<[u64; 4]> {
Records::from_records(
(0..300u64).map(|i| (i * 3 + 1, [i ^ seed, i.wrapping_mul(0x9e37_79b9_7f4a_7c15), !i, seed])),
)
.expect("ids rise")
}
fn narrow(seed: u64) -> Records<u64> {
Records::from_records((0..300u64).map(|i| (i * 2 + 1, i.wrapping_mul(0x9e37_79b9_7f4a_7c15) ^ seed)))
.expect("ids rise")
}
fn age(path: &Path, when: SystemTime) {
if path.is_dir() {
for entry in fs::read_dir(path).expect("a directory") {
age(&entry.expect("an entry").path(), when);
}
}
fs::File::open(path)
.expect("opened")
.set_modified(when)
.expect("the time is set");
}
fn a_year_ago() -> SystemTime {
SystemTime::now() - Duration::from_secs(365 * 24 * 3600)
}
#[test]
fn the_tools_the_accept_script_needs_are_installed() {
let check = Command::new("bash")
.args([
"-c",
"command -v flock && command -v timeout && command -v stat && command -v find",
])
.output()
.expect("bash runs");
assert!(
check.status.success(),
"bash, flock, timeout, stat and find are installed"
);
let version = Command::new("find").arg("--version").output().expect("find runs");
assert!(
String::from_utf8_lossy(&version.stdout).contains("GNU findutils"),
"find is GNU find"
);
let scratch = TempDir::new();
fs::create_dir_all(&scratch.0).expect("a directory");
fs::write(scratch.0.join("new"), "").expect("a file");
let newer = Command::new("find")
.arg(&scratch.0)
.args(["-newerct", "-60 seconds", "-name", "new"])
.output()
.expect("find runs");
assert!(
String::from_utf8_lossy(&newer.stdout).contains("new"),
"find has -newerct"
);
let stat = Command::new("stat")
.args(["-c", "%a %d"])
.arg(&scratch.0)
.output()
.expect("stat runs");
assert!(stat.status.success(), "stat takes -c");
}
#[test]
fn the_accept_script_parses() {
let output = Command::new("bash")
.arg("-n")
.arg(script())
.output()
.expect("bash runs");
assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr));
let mode = fs::metadata(script()).expect("the script").permissions().mode();
assert_eq!(mode & 0o111, 0o111, "the script is executable");
}
#[test]
fn a_finished_upload_is_verified_moved_and_named_in_current() {
let root = Root::new();
let records = wide(1);
root.upload(ID, &records, Some(ID));
let stdout = root.accept();
assert!(stdout.contains(&format!("accepted {SET}/{ID}")), "{stdout}");
let snapshot = root.set().join(ID);
assert!(snapshot.join("MANIFEST.json").is_file(), "the snapshot is in the set");
assert!(!snapshot.join("CURRENT").exists(), "its own CURRENT is gone");
assert_eq!(root.current().as_deref(), Some(ID), "the set's CURRENT names it");
assert!(!root.set().join("CURRENT.new").exists(), "no CURRENT.new is left");
assert_eq!(names(&root.inbox()), Vec::<String>::new(), "the inbox is empty");
assert_eq!(names(&root.staging()), Vec::<String>::new(), "staging is empty");
let status = root.status();
assert_eq!(
(
&status["set"],
&status["current"],
&status["accepted"],
&status["rejected"],
&status["pending"]
),
(
&Json::from(SET),
&Json::from(ID),
&Json::from(1),
&Json::from(0),
&Json::from(0)
)
);
assert!(
status["at"].as_str().is_some_and(|at| at.ends_with('Z')),
"status has its time"
);
let verify = Command::new(program())
.arg("verify")
.arg(&snapshot)
.output()
.expect("verify runs");
assert_eq!(
verify.status.code(),
Some(0),
"{}",
String::from_utf8_lossy(&verify.stdout)
);
let value = records.value(5);
let hex = (0..4).fold(String::new(), |hex, word| hex + &format!("{:016x}", value.word(word)));
let request =
format!("{{\"format\":1,\"index\":\"{SET}\",\"width\":256,\"radius\":0,\"values\":[\"{hex}\"]}}\n");
let mut query = Command::new(program())
.arg("query")
.arg("--index")
.arg(format!("{SET}={}", root.set().display()))
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn()
.expect("query runs");
std::io::Write::write_all(&mut query.stdin.take().expect("stdin"), request.as_bytes()).expect("written");
let output = query.wait_with_output().expect("query ends");
assert_eq!(output.status.code(), Some(0));
let result: Json = serde_json::from_slice(&output.stdout).expect("a result line");
assert_eq!(result["snapshot"], ID);
let matches = result["queries"][0]["matches"].as_array().expect("matches");
assert!(
matches.iter().any(|found| found["id"] == records.id(5).expect("ids")),
"the stored value is found: {result}"
);
}
#[test]
fn an_upload_without_current_or_still_changing_waits_in_the_inbox() {
let root = Root::new();
let dir = root.upload(ID, &wide(2), None);
root.accept();
assert!(
dir.join("MANIFEST.json").is_file(),
"an upload with no CURRENT is left alone"
);
assert_eq!(root.status()["pending"], 1);
assert_eq!(root.current(), None);
fs::write(dir.join("CURRENT"), format!("{ID}\n")).expect("CURRENT");
root.settings("QUIET_SECONDS=3600");
root.accept();
assert!(
dir.join("CURRENT").is_file(),
"an upload changed within the quiet time is left alone"
);
assert_eq!(root.status()["pending"], 1);
assert_eq!(names(&root.set()), Vec::<String>::new(), "nothing was taken");
}
#[test]
fn an_unfinished_upload_with_nothing_new_is_dropped() {
let root = Root::new();
let dir = root.upload(ID, &wide(3), None);
root.settings("STALE_MINUTES=0");
let stdout = root.accept();
assert!(!dir.exists(), "the unfinished upload is gone");
assert!(stdout.contains("dropped"), "{stdout}");
assert_eq!(root.status()["pending"], 0);
assert_eq!(root.status()["rejected"], 0);
}
#[test]
fn a_current_naming_another_directory_is_rejected() {
let root = Root::new();
root.upload("served", &wide(4), Some("served"));
root.accept();
root.upload(ID, &wide(5), Some("another"));
let stdout = root.accept();
assert!(stdout.contains(&format!("rejected {SET}/{ID}")), "{stdout}");
assert!(
root.rejected().join(ID).join("MANIFEST.json").is_file(),
"it is kept among the rejected"
);
let reason = root.reason(ID);
assert_eq!(reason["name"], ID);
assert_eq!(reason["reason"], "CURRENT does not name its own directory");
assert!(reason["at"].as_str().is_some_and(|at| at.ends_with('Z')));
assert_eq!(
root.current().as_deref(),
Some("served"),
"the set's CURRENT is unchanged"
);
assert!(!root.set().join(ID).exists());
let status = root.status();
assert_eq!(
(&status["accepted"], &status["rejected"]),
(&Json::from(1), &Json::from(1))
);
assert_eq!(status["last_rejected"], ID);
}
#[test]
fn a_snapshot_verify_refuses_is_rejected_with_its_message_in_valid_json() {
let root = Root::new();
let dir = root.upload(ID, &wide(6), Some(ID));
let part = dir.join("part-00001.bin");
let mut bytes = fs::read(&part).expect("a part");
bytes[17] ^= 0x40;
fs::write(&part, bytes).expect("damaged");
root.accept();
assert!(root.rejected().join(ID).is_dir(), "it is rejected");
let reason = root.reason(ID);
let text = reason["reason"].as_str().expect("a reason");
assert!(text.starts_with("verify failed:"), "{text}");
assert!(text.contains('"'), "verify's own message is quoted: {text}");
assert_eq!(root.current(), None, "nothing is served");
assert_eq!(names(&root.set()), Vec::<String>::new());
}
#[test]
fn links_files_and_directories_where_only_plain_files_belong_are_refused() {
let root = Root::new();
let outside = root.path().join("outside");
fs::create_dir_all(&outside).expect("a directory outside the inbox");
fs::write(outside.join("kept"), "not the uploader's").expect("a file outside");
let linked = root.upload("part-linked", &wide(7), Some("part-linked"));
fs::rename(linked.join("part-00000.bin"), outside.join("part-00000.bin")).expect("moved away");
std::os::unix::fs::symlink(outside.join("part-00000.bin"), linked.join("part-00000.bin")).expect("a link");
let beside = root.upload("link-beside", &wide(8), Some("link-beside"));
std::os::unix::fs::symlink(outside.join("kept"), beside.join("extra")).expect("a link");
let nested = root.upload("nested", &wide(9), Some("nested"));
fs::create_dir(nested.join("deeper")).expect("a subdirectory");
std::os::unix::fs::symlink(&outside, root.inbox().join("top-link")).expect("a link");
fs::write(root.inbox().join("top-file"), "a file").expect("a file");
root.settings("KEEP_REJECTED=5");
root.accept();
for name in ["part-linked", "link-beside", "nested"] {
let reason = root.reason(name);
assert_eq!(
reason["reason"], "it holds something that is not a plain file",
"{name}"
);
}
assert_eq!(
names(&root.inbox()),
Vec::<String>::new(),
"the top-level link and file are removed"
);
assert_eq!(
fs::read_to_string(outside.join("kept")).expect("kept"),
"not the uploader's"
);
assert!(
outside.join("part-00000.bin").is_file(),
"a link's target is never touched"
);
assert_eq!(root.current(), None);
assert_eq!(root.status()["rejected"], 3);
}
#[test]
fn a_name_already_accepted_is_rejected_and_the_served_one_kept() {
let root = Root::new();
root.upload(ID, &wide(10), Some(ID));
root.accept();
let manifest = fs::read(root.set().join(ID).join("MANIFEST.json")).expect("the manifest");
root.upload(ID, &wide(11), Some(ID));
root.accept();
assert_eq!(
root.reason(ID)["reason"],
"a snapshot of that name was already accepted"
);
assert_eq!(
fs::read(root.set().join(ID).join("MANIFEST.json")).expect("the manifest"),
manifest
);
assert_eq!(root.current().as_deref(), Some(ID));
let status = root.status();
assert_eq!(
(&status["accepted"], &status["rejected"]),
(&Json::from(1), &Json::from(1))
);
}
#[test]
fn bad_and_reserved_names_are_rejected() {
let root = Root::new();
root.upload(ID, &wide(12), Some(ID));
root.accept();
for name in [".hidden", "CURRENT", "x.reason.json"] {
root.upload(name, &wide(13), Some(name));
}
root.settings("KEEP_REJECTED=5");
root.accept();
assert_eq!(names(&root.inbox()), Vec::<String>::new());
assert!(root.set().join("CURRENT").is_file(), "the set's CURRENT stays a file");
assert_eq!(root.current().as_deref(), Some(ID));
assert_eq!(names(&root.set()), [ID, "CURRENT"]);
let rejected: Vec<String> = names(&root.rejected())
.into_iter()
.filter(|name| !name.ends_with(".json"))
.collect();
assert_eq!(rejected.len(), 3, "{rejected:?}");
for name in rejected {
assert!(
name.starts_with("bad-name-"),
"a bad name is never used as a path: {name}"
);
assert_eq!(
root.reason(&name)["reason"],
"the directory name is not a valid snapshot name"
);
}
assert_eq!(root.status()["rejected"], 3);
}
#[test]
fn pruning_keeps_the_newest_two_accepted_and_rejected() {
let root = Root::new();
for name in ["s1", "s2", "s3"] {
root.upload(
name,
&narrow(name.len() as u64 + u64::from(name.as_bytes()[1])),
Some(name),
);
root.accept();
}
assert_eq!(names(&root.set()), ["CURRENT", "s2", "s3"]);
assert_eq!(root.current().as_deref(), Some("s3"));
for name in ["r1", "r2", "r3"] {
root.upload(name, &narrow(7), Some("elsewhere"));
root.accept();
}
assert_eq!(
names(&root.rejected()),
["r2", "r2.reason.json", "r3", "r3.reason.json"],
"the oldest rejection and its reason file are gone"
);
let status = root.status();
assert_eq!(
(&status["accepted"], &status["rejected"]),
(&Json::from(3), &Json::from(3))
);
}
#[test]
fn pruning_counts_from_acceptance_not_from_upload_times() {
let root = Root::new();
root.upload("a", &narrow(1), Some("a"));
root.accept();
let b = root.upload("b", &narrow(2), Some("b"));
age(&b, a_year_ago());
root.accept();
let c = root.upload("c", &narrow(3), Some("c"));
age(&c, a_year_ago());
root.accept();
assert_eq!(root.current().as_deref(), Some("c"));
assert_eq!(
names(&root.set()),
["CURRENT", "b", "c"],
"A, accepted first, is the one removed"
);
let first = root.upload("r1", &narrow(4), Some("elsewhere"));
drop(first);
root.accept();
for name in ["r2", "r3"] {
let dir = root.upload(name, &narrow(5), Some("elsewhere"));
age(&dir, a_year_ago());
root.accept();
}
assert_eq!(
names(&root.rejected()),
["r2", "r2.reason.json", "r3", "r3.reason.json"],
"R1, rejected first, is the one removed"
);
}
#[test]
fn pruning_never_removes_the_snapshot_served() {
let root = Root::new();
let by_hand = root.set().join("by-hand");
fs::create_dir(&by_hand).expect("a directory");
fs::File::open(&by_hand)
.expect("opened")
.set_modified(SystemTime::now() + Duration::from_secs(3600))
.expect("the time is set");
root.upload(ID, &narrow(6), Some(ID));
root.settings("KEEP_ACCEPTED=1");
root.accept();
assert_eq!(root.current().as_deref(), Some(ID));
assert_eq!(
names(&root.set()),
[ID, "CURRENT"],
"the one served is kept, whatever the times"
);
}
#[test]
fn a_current_that_cannot_be_replaced_keeps_what_it_named_and_prunes_nothing() {
let root = Root::new();
root.upload("a", &narrow(7), Some("a"));
root.accept();
fs::create_dir(root.set().join("CURRENT.new")).expect("a directory");
root.upload("b", &narrow(8), Some("b"));
root.settings("KEEP_ACCEPTED=1");
let stdout = root.accept();
assert!(!stdout.contains("accepted"), "{stdout}");
assert_eq!(
root.current().as_deref(),
Some("a"),
"CURRENT still names what it named"
);
assert!(
root.set().join("a/MANIFEST.json").is_file(),
"the snapshot served is not pruned"
);
assert!(!root.set().join("b").exists(), "the unnamed snapshot left the set");
assert_eq!(
root.reason("b")["reason"],
"the set's CURRENT could not be replaced; what it named is still served"
);
let status = root.status();
assert_eq!(
(&status["current"], &status["accepted"], &status["rejected"]),
(&Json::from("a"), &Json::from(1), &Json::from(1))
);
fs::remove_dir(root.set().join("CURRENT.new")).expect("removed");
root.upload("b", &narrow(8), Some("b"));
root.accept();
assert_eq!(root.current().as_deref(), Some("b"));
assert_eq!(names(&root.set()), ["CURRENT", "b"]);
}
#[test]
fn a_current_that_is_a_directory_is_never_entered() {
let root = Root::new();
fs::create_dir(root.set().join("CURRENT")).expect("a directory");
root.upload(ID, &narrow(9), Some(ID));
root.accept();
assert_eq!(
names(&root.set().join("CURRENT")),
Vec::<String>::new(),
"nothing was moved into it"
);
assert!(!root.set().join("CURRENT.new").exists(), "no CURRENT.new is left");
assert!(!root.set().join(ID).exists());
assert_eq!(
root.reason(ID)["reason"],
"the set's CURRENT could not be replaced; what it named is still served"
);
}
#[test]
fn an_upload_swapped_for_a_link_just_before_the_move_is_removed_and_its_target_untouched() {
let root = Root::new();
root.upload("served", &wide(18), Some("served"));
root.accept();
let victim = root.path().join("victim");
fs::create_dir(&victim).expect("the victim directory");
fs::write(victim.join("secret"), "root's").expect("its file");
fs::set_permissions(victim.join("secret"), fs::Permissions::from_mode(0o600)).expect("mode 0600");
fs::set_permissions(&victim, fs::Permissions::from_mode(0o700)).expect("mode 0700");
let upload = root.upload(ID, &wide(19), Some(ID));
let real = Command::new("bash")
.args(["-c", "command -v mv"])
.output()
.expect("bash runs");
let real = String::from_utf8(real.stdout).expect("UTF-8").trim().to_owned();
assert!(real.starts_with('/'), "the real mv is found: {real}");
let bin = root.path().join("bin");
fs::create_dir(&bin).expect("a directory for the wrapper");
let wrapper = bin.join("mv");
fs::write(
&wrapper,
format!(
"#!/bin/bash\nif [ \"$2\" = '{upload}' ] && [ \"$3\" = '{staged}' ]; then\n \
rm -rf -- \"$2\" && ln -s -- '{victim}' \"$2\" || exit 99\nfi\nexec '{real}' \"$@\"\n",
upload = upload.display(),
staged = root.staging().join(ID).display(),
victim = victim.display(),
),
)
.expect("the wrapper");
fs::set_permissions(&wrapper, fs::Permissions::from_mode(0o755)).expect("executable");
let path = format!("{}:{}", bin.display(), std::env::var("PATH").unwrap_or_default());
let stdout = succeeded(&root.command().env("PATH", path).output().expect("bash runs the script"));
let mode = |path: &Path| fs::symlink_metadata(path).expect("there").permissions().mode() & 0o7777;
assert_eq!(
format!("{:o}", mode(&victim)),
"700",
"the victim directory's mode is unchanged"
);
assert_eq!(
format!("{:o}", mode(&victim.join("secret"))),
"600",
"its file's mode is unchanged"
);
assert_eq!(
fs::read_to_string(victim.join("secret")).expect("still there"),
"root's"
);
assert!(
stdout.contains(&format!("removed {SET}/{ID}: not a directory")),
"{stdout}"
);
assert!(!stdout.contains("accepted"), "{stdout}");
assert_eq!(
root.current().as_deref(),
Some("served"),
"the set's CURRENT is as it was"
);
assert_eq!(names(&root.set()), ["CURRENT", "served"], "nothing was accepted");
assert_eq!(names(&root.staging()), Vec::<String>::new(), "staging is empty");
assert_eq!(names(&root.inbox()), Vec::<String>::new(), "the link left the inbox");
let status = root.status();
assert_eq!(
(&status["accepted"], &status["rejected"]),
(&Json::from(1), &Json::from(0))
);
}
#[test]
fn a_link_left_in_staging_is_removed_never_rejected_and_its_target_untouched() {
let root = Root::new();
let target = root.path().join("target");
fs::create_dir(&target).expect("a directory outside");
fs::write(target.join("kept"), "not the script's").expect("a file");
age(&target, a_year_ago());
fs::set_permissions(&target, fs::Permissions::from_mode(0o700)).expect("mode 0700");
let before = fs::metadata(&target).expect("the target").modified().expect("a time");
fs::create_dir_all(root.staging()).expect("staging");
std::os::unix::fs::symlink(&target, root.staging().join(ID)).expect("a link in staging");
let stdout = root.accept();
let after = fs::metadata(&target).expect("the target");
assert_eq!(
after.modified().expect("a time"),
before,
"the target's time is unchanged"
);
assert_eq!(
format!("{:o}", after.permissions().mode() & 0o7777),
"700",
"the target's mode is unchanged"
);
assert_eq!(
fs::read_to_string(target.join("kept")).expect("still there"),
"not the script's"
);
assert!(
stdout.contains(&format!("removed {SET}/{ID}: a symbolic link, not rejected")),
"{stdout}"
);
assert_eq!(names(&root.staging()), Vec::<String>::new(), "staging is empty");
assert_eq!(names(&root.rejected()), Vec::<String>::new(), "nothing was rejected");
assert_eq!(root.status()["rejected"], 0);
}
#[test]
fn a_snapshot_left_in_staging_is_rejected() {
let root = Root::new();
let left = root.staging().join(ID);
fs::create_dir_all(&left).expect("a directory in staging");
fs::write(left.join("part-00000.bin"), [0u8; 16]).expect("a part");
let stdout = root.accept();
assert!(stdout.contains("interrupted"), "{stdout}");
assert_eq!(root.reason(ID)["reason"], "interrupted while it was being checked");
assert_eq!(names(&root.staging()), Vec::<String>::new());
assert_eq!(root.current(), None, "it is never served");
}
#[test]
fn settings_that_others_can_write_or_that_are_wrong_stop_the_script() {
let root = Root::new();
let dir = root.upload(ID, &wide(14), Some(ID));
fs::set_permissions(root.conf(), fs::Permissions::from_mode(0o666)).expect("mode 0666");
let output = root.run();
assert_eq!(output.status.code(), Some(2));
assert!(String::from_utf8_lossy(&output.stderr).contains("writable"));
assert!(dir.join("CURRENT").is_file(), "nothing moved");
assert!(!root.path().join("status").exists(), "nothing written");
for (setting, message) in [
("QUIET_SECONDS=soon", "must be a number"),
("KEEP_ACCEPTED=0", "at least 1"),
("BIN=/nonexistent/legit-hamming", "no program"),
("ROOT=relative", "ROOT must be"),
] {
root.settings(setting);
let output = root.run();
assert_eq!(output.status.code(), Some(2), "{setting}");
assert!(String::from_utf8_lossy(&output.stderr).contains(message), "{setting}");
assert!(dir.join("CURRENT").is_file(), "nothing moved with {setting}");
}
fs::remove_file(root.conf()).expect("removed");
assert_eq!(root.run().status.code(), Some(2), "no settings file");
}
#[test]
fn a_set_name_that_is_not_an_index_name_is_skipped() {
let root = Root::new();
root.upload(ID, &wide(15), Some(ID));
root.settings(&format!("SETS=\"Bad Name * {SET}\""));
let stdout = root.accept();
assert!(stdout.contains("skipped set Bad: not an index name"), "{stdout}");
assert!(stdout.contains("skipped set Name: not an index name"), "{stdout}");
assert!(
stdout.contains("skipped set *: not an index name"),
"never expanded as a pattern: {stdout}"
);
assert_eq!(root.current().as_deref(), Some(ID), "the valid set is still served");
}
#[test]
fn a_set_whose_inbox_is_missing_is_skipped() {
let root = Root::new();
root.settings(&format!("SETS=\"missing {SET}\""));
root.upload(ID, &wide(16), Some(ID));
let stdout = root.accept();
assert!(stdout.contains("skipped set missing"), "{stdout}");
assert_eq!(root.current().as_deref(), Some(ID));
}
#[test]
fn a_run_while_another_holds_the_lock_does_nothing() {
let root = Root::new();
let dir = root.upload(ID, &wide(17), Some(ID));
let mut holder = Command::new("flock")
.arg(root.lock())
.args(["sleep", "5"])
.spawn()
.expect("flock runs");
let deadline = Instant::now() + Duration::from_secs(5);
while Command::new("flock")
.arg("-n")
.arg(root.lock())
.arg("true")
.status()
.expect("flock runs")
.success()
{
assert!(Instant::now() < deadline, "the lock is taken");
std::thread::sleep(Duration::from_millis(20));
}
let output = root.run();
let _ = holder.kill();
let _ = holder.wait();
assert_eq!(output.status.code(), Some(0));
assert!(dir.join("CURRENT").is_file(), "the upload stays in the inbox");
assert_eq!(root.current(), None);
}
#[test]
fn a_lock_that_is_a_link_stops_the_script_and_its_target_is_untouched() {
let root = Root::new();
let dir = root.upload(ID, &wide(20), Some(ID));
let target = root.path().join("not-a-lock");
fs::write(&target, "kept").expect("a file");
std::os::unix::fs::symlink(&target, root.lock()).expect("a link where the lock goes");
let output = root.run();
assert_eq!(output.status.code(), Some(2));
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(stderr.contains("is a symbolic link"), "{stderr}");
assert_eq!(
fs::read_to_string(&target).expect("still there"),
"kept",
"never truncated"
);
assert!(root.lock().is_symlink(), "the link is left as it was");
assert!(dir.join("CURRENT").is_file(), "nothing moved");
assert!(!root.path().join("status").exists(), "nothing written");
}
}
fn unit(path: &Path) -> Vec<(String, String)> {
fs::read_to_string(path)
.expect("a unit file")
.lines()
.map(str::trim)
.filter(|line| !(line.is_empty() || line.starts_with('#') || line.starts_with(';') || line.starts_with('[')))
.map(|line| {
let (key, value) = line.split_once('=').expect("a key=value line");
(key.trim().to_owned(), value.trim().to_owned())
})
.collect()
}
fn values<'a>(unit: &'a [(String, String)], key: &str) -> Vec<&'a str> {
unit.iter()
.filter(|(name, _)| name == key)
.map(|(_, value)| value.as_str())
.collect()
}
fn one<'a>(unit: &'a [(String, String)], key: &str) -> &'a str {
let found = values(unit, key);
assert_eq!(found.len(), 1, "one {key}=");
found[0]
}
fn flag_value<'a>(command: &'a str, flag: &str) -> Option<&'a str> {
let words: Vec<&str> = command.split_whitespace().collect();
words
.iter()
.position(|word| *word == flag)
.and_then(|at| words.get(at + 1).copied())
}
fn names_flag(help: &str, flag: &str) -> bool {
help.match_indices(flag).any(|(at, _)| {
let whole = |c: Option<char>| c.is_none_or(|c| !(c.is_ascii_alphanumeric() || c == '-'));
whole(help[..at].chars().next_back()) && whole(help[at + flag.len()..].chars().next())
})
}
fn unit_files() -> Vec<PathBuf> {
let mut files = Vec::new();
let mut directories = vec![crate_dir().join("deploy/systemd")];
while let Some(directory) = directories.pop() {
for entry in fs::read_dir(&directory).expect("a directory") {
let path = entry.expect("an entry").path();
if path.is_dir() {
directories.push(path);
} else {
files.push(path);
}
}
}
files.sort();
files
}
#[test]
fn every_unit_runs_the_program_with_flags_it_knows() {
let help = Command::new(program())
.args(["serve", "--help"])
.output()
.expect("the help");
assert_eq!(help.status.code(), Some(0));
let help = String::from_utf8(help.stdout).expect("UTF-8");
let byte_flags = [
"--max-result-bytes",
"--max-options-bytes",
"--max-log-bytes",
"--max-fetch-bytes",
"--max-text-bytes",
"--max-pixels",
];
let files = unit_files();
assert_eq!(files.len(), 4, "{files:?}");
let mut serving = 0;
for path in &files {
let unit = unit(path);
let name = path.file_name().expect("a name").to_string_lossy();
for command in values(&unit, "ExecStart")
.into_iter()
.filter(|command| !command.is_empty())
{
if name == "legit-hamming-accept.service" {
assert_eq!(command, "/usr/local/sbin/legit-hamming-accept");
continue;
}
serving += 1;
assert!(
command.starts_with("/usr/local/bin/legit-hamming serve "),
"{name}: {command}"
);
let words: Vec<&str> = command.split_whitespace().collect();
for (at, word) in words.iter().enumerate().filter(|(_, word)| word.starts_with("--")) {
let flag = word.split('=').next().expect("a flag");
assert!(names_flag(&help, flag), "{name}: `{flag}` is not a flag of serve");
if byte_flags.contains(&flag) {
let value = word
.split_once('=')
.map_or_else(|| words.get(at + 1).copied().unwrap_or(""), |(_, value)| value);
assert!(
!value.is_empty() && value.bytes().all(|b| b.is_ascii_digit()),
"{name}: {flag} {value} in plain digits"
);
}
}
let stop: u64 = one(&unit, "TimeoutStopSec").parse().expect("seconds");
assert!(
stop >= 30 + 10,
"{name}: TimeoutStopSec covers the 30 s shutdown grace and a margin"
);
let runtime = one(&unit, "RuntimeDirectory");
let stats = flag_value(command, "--stats-file").expect("a stats file");
assert!(
stats.starts_with(&format!("/run/{runtime}/")),
"{name}: the stats file is in the runtime directory"
);
}
}
assert_eq!(serving, 2, "two worker units");
}
#[test]
fn the_fixed_and_dynamic_user_units_differ_only_in_the_user_and_the_state_directory() {
let systemd = crate_dir().join("deploy/systemd");
let fixed = unit(&systemd.join("legit-hamming.service"));
let dynamic = unit(&systemd.join("legit-hamming.dynamic-user.service"));
assert_eq!(values(&dynamic, "DynamicUser"), ["yes"]);
assert!(values(&dynamic, "User").is_empty());
assert_eq!(values(&fixed, "User"), ["legit-hamming"]);
assert!(values(&fixed, "DynamicUser").is_empty());
let state = one(&fixed, "StateDirectory");
assert_eq!(one(&dynamic, "StateDirectory"), state);
let fixed_start = one(&fixed, "ExecStart");
let dynamic_start = one(&dynamic, "ExecStart");
assert_eq!(
flag_value(fixed_start, "--state-dir"),
Some(format!("/var/lib/{state}").as_str())
);
assert_eq!(
flag_value(dynamic_start, "--state-dir"),
Some(format!("/var/lib/private/{state}").as_str())
);
fn other(command: &str) -> Vec<&str> {
let words: Vec<&str> = command.split_whitespace().collect();
let at = words
.iter()
.position(|word| *word == "--state-dir")
.expect("--state-dir");
[&words[..=at], &words[at + 2..]].concat()
}
assert_eq!(
other(fixed_start),
other(dynamic_start),
"every other word of ExecStart= is the same"
);
let without = |unit: &[(String, String)]| -> Vec<(String, String)> {
unit.iter()
.filter(|(key, _)| !["User", "Group", "DynamicUser", "ExecStart"].contains(&key.as_str()))
.cloned()
.collect()
};
assert_eq!(without(&fixed), without(&dynamic));
}
fn deploy_files() -> Vec<PathBuf> {
let mut files = Vec::new();
let mut directories = vec![crate_dir().join("deploy")];
while let Some(directory) = directories.pop() {
for entry in fs::read_dir(&directory).expect("a directory") {
let path = entry.expect("an entry").path();
if path.is_dir() {
directories.push(path);
} else {
files.push(path);
}
}
}
files.sort();
files
}
fn whole_word(text: &str, word: &str) -> bool {
text.match_indices(word).any(|(at, _)| {
let boundary = |c: Option<char>| c.is_none_or(|c| !(c.is_alphanumeric() || c == '_' || c == '-'));
boundary(text[..at].chars().next_back()) && boundary(text[at + word.len()..].chars().next())
})
}
fn private_addresses(text: &str) -> Vec<String> {
let blocks = [
[["10", "0", "0", "0"].join("."), "/8".to_owned()].concat(),
[["172", "16", "0", "0"].join("."), "/12".to_owned()].concat(),
[["192", "168", "0", "0"].join("."), "/16".to_owned()].concat(),
[["100", "64", "0", "0"].join("."), "/10".to_owned()].concat(),
];
let bytes = text.as_bytes();
let mut found = Vec::new();
let mut at = 0;
while at < bytes.len() {
if !bytes[at].is_ascii_digit() || (at > 0 && (bytes[at - 1].is_ascii_digit() || bytes[at - 1] == b'.')) {
at += 1;
continue;
}
let end = at
+ bytes[at..]
.iter()
.take_while(|b| b.is_ascii_digit() || **b == b'.')
.count();
let run = text[at..end].trim_end_matches('.');
let octets: Vec<u32> = run.split('.').map_while(|octet| octet.parse().ok()).collect();
if run.split('.').count() == 4 && octets.len() == 4 && octets.iter().all(|octet| *octet <= 255) {
let [a, b, ..] = [octets[0], octets[1], octets[2], octets[3]];
let private = a == 10
|| (a == 172 && (16..=31).contains(&b))
|| (a == 192 && b == 168)
|| (a == 100 && (64..=127).contains(&b));
if private && !blocks.iter().any(|block| text[at..].starts_with(block.as_str())) {
found.push(run.to_owned());
}
}
at = end.max(at + 1);
}
found
}
fn leaks(text: &str, in_deploy: bool) -> Vec<String> {
let mut found: Vec<String> = private_addresses(text)
.into_iter()
.map(|address| format!("the address {address}"))
.collect();
let lower = text.to_lowercase();
if lower.contains(&[".ts", ".net"].concat()) {
found.push("a tailnet name".to_owned());
}
for home in [["/Us", "ers/"].concat(), ["/ho", "me/"].concat()] {
if text
.match_indices(&home)
.any(|(at, _)| text[at + home.len()..].starts_with(|c: char| c.is_ascii_alphanumeric()))
{
found.push(format!("a path under {home}"));
}
}
let body = ["AA", "AA"].concat();
for prefix in [
["ssh-", "ed25519"].concat(),
["ssh-", "rsa"].concat(),
["ecdsa-", "sha2"].concat(),
] {
for (at, _) in text.match_indices(&prefix) {
let rest = &text[at + prefix.len()..];
let key = rest
.split_whitespace()
.find(|word| !word.starts_with('-') || word.len() > 30)
.unwrap_or("");
if key.starts_with(&body)
|| rest
.split_whitespace()
.next()
.is_some_and(|word| word.starts_with(&body))
{
found.push(format!("a {prefix} key"));
}
}
}
let fingerprint = ["SHA", "256:"].concat();
for (at, _) in text.match_indices(&fingerprint) {
let run = text[at + fingerprint.len()..]
.bytes()
.take_while(|b| b.is_ascii_alphanumeric() || b"+/=".contains(b))
.count();
if run >= 20 {
found.push("a key fingerprint".to_owned());
}
}
for (at, _) in text.match_indices('@') {
let local = text[..at]
.chars()
.rev()
.take_while(|c| c.is_ascii_alphanumeric() || "._%+-".contains(*c))
.count();
let domain: String = text[at + 1..]
.chars()
.take_while(|c| c.is_ascii_alphanumeric() || ".-".contains(*c))
.collect();
let domain = domain.trim_end_matches(['.', '-']).to_lowercase();
let tld = domain.rsplit('.').next().unwrap_or("");
let address =
local > 0 && domain.contains('.') && tld.len() >= 2 && tld.chars().all(|c| c.is_ascii_alphabetic());
if address && domain != "example.com" && !domain.ends_with(".example.com") {
found.push(format!("an e-mail address at {domain}"));
}
}
for word in [
["med", "ia"].concat(),
["ban", "ned"].concat(),
["known", "-bad"].concat(),
] {
if whole_word(&lower, &word) {
found.push(format!("the word {word}"));
}
}
for word in [["TO", "DO"].concat(), ["FIX", "ME"].concat()] {
if whole_word(text, &word) {
found.push(format!("a {word} marker"));
}
}
if in_deploy {
let mut run = 0;
for byte in text.bytes() {
run = if byte.is_ascii_hexdigit() { run + 1 } else { 0 };
if run == 32 {
found.push("32 or more hexadecimal digits in a row".to_owned());
}
}
}
found
}
#[test]
fn the_leak_check_finds_what_it_looks_for() {
let address = ["192", "168", "1", "20"].join(".");
assert_eq!(
leaks(&format!("bind {address}"), false),
[format!("the address {address}")]
);
let block = [["10", "0", "0", "0"].join("."), "/8".to_owned()].concat();
assert!(leaks(&format!("refuses {block}, and 192.0.2.10 and 1.10.0.1.2"), false).is_empty());
assert_eq!(
leaks(
&format!("ssh-ed25519 {}C3NzaC1lZDI1NTE5 someone", ["AA", "AA"].concat()),
false
)
.len(),
1
);
assert!(
leaks(
"ssh-ed25519 REPLACE_WITH_THE_EXPORTER_PUBLIC_KEY images-pdq-exporter",
false
)
.is_empty()
);
assert_eq!(
leaks(
&format!("{}ABCDEFGHIJKLMNOPQRSTUVWXYZ012", ["SHA", "256:"].concat()),
false
)
.len(),
1
);
assert_eq!(leaks(&["someone@", "mail.test.org"].concat(), false).len(), 1);
assert!(leaks("someone@images.example.com and redis://:x@127.0.0.1:6390", false).is_empty());
assert_eq!(leaks(&["/ho", "me/someone/x"].concat(), false).len(), 1);
assert_eq!(leaks(&["the ", "med", "ia server"].concat(), false).len(), 1);
assert!(leaks("the median", false).is_empty());
let hex = "0123456789abcdef".repeat(2);
assert_eq!(leaks(&hex, true).len(), 1);
assert!(leaks(&hex, false).is_empty());
}
#[test]
fn the_readme_and_the_examples_name_nothing_private_or_secret() {
let readme = fs::read_to_string(crate_dir().join("README.md")).expect("the README");
assert_eq!(leaks(&readme, false), Vec::<String>::new(), "README.md");
let files = deploy_files();
assert_eq!(files.len(), 10, "{files:?}");
for path in files {
let text = fs::read_to_string(&path).expect("a UTF-8 file");
assert_eq!(leaks(&text, true), Vec::<String>::new(), "{}", path.display());
let first = text.lines().nth(usize::from(text.starts_with("#!"))).unwrap_or("");
assert!(first.starts_with('#'), "{} starts with a comment", path.display());
assert!(
text.contains("See Deploying in the crate's README"),
"{} points to Deploying",
path.display()
);
}
}
#[test]
fn the_readme_and_the_examples_name_each_other() {
let readme = fs::read_to_string(crate_dir().join("README.md")).expect("the README");
let named: Vec<&str> = readme
.match_indices("deploy/")
.filter(|(at, _)| {
readme[..*at]
.chars()
.next_back()
.is_none_or(|c| !(c.is_ascii_alphanumeric() || "_-./".contains(c)))
})
.map(|(at, _)| {
let length = readme[at..]
.bytes()
.take_while(|b| b.is_ascii_alphanumeric() || b"._/-".contains(b))
.count();
readme[at..at + length].trim_end_matches('.')
})
.collect();
assert!(!named.is_empty(), "the README names the examples");
for path in &named {
assert!(
crate_dir().join(path).exists(),
"the README names {path}, which isn't there"
);
}
for path in deploy_files() {
let relative = path
.strip_prefix(crate_dir())
.expect("in the crate")
.to_string_lossy()
.into_owned();
assert!(named.contains(&relative.as_str()), "the README doesn't name {relative}");
}
}