Skip to main content

stegobench_cli/
lib.rs

1// Author:  Daniel Iwugo
2// Comment: Christ is King
3// SPDX-License-Identifier: AGPL-3.0-or-later
4// Copyright (C) 2026 Daniel Iwugo
5//! Library half of the `stegobench` command, split out purely so `build.rs`
6//! can import the command definition and generate man pages from the same
7//! source the binary parses against. There is no other reason for a lib
8//! target here; the behaviour lives in the binary.
9
10/// The registry id of the corpus this binary carries a copy of.
11///
12/// Here rather than in `main.rs` because both halves need it: the binary
13/// writes the corpus out and `needs` has to stop telling the reader that
14/// obtaining it is theirs to arrange.
15pub const STARTER_ID: &str = "stegobench-starter";
16
17/// A path as somewhere a reader could go, rather than as it was typed.
18///
19/// `doctor` prints where its registry and its fixtures came from, and a
20/// relative answer is not one: `fixtures  fixtures` repeats its own key and
21/// tells nobody which directory on this machine was read. Resolved against
22/// the working directory without touching the filesystem, so a path that has
23/// since been removed still prints as the place it was looked for, and no
24/// platform gains a verbatim prefix it did not have.
25pub fn resolved_path(path: &std::path::Path) -> std::path::PathBuf {
26    std::path::absolute(path).unwrap_or_else(|_| path.to_path_buf())
27}
28
29/// An IO error as a sentence, without the operating system's error number.
30///
31/// `os error 2` names nothing a reader can act on and reads as a crash rather
32/// than an answer, which is the whole of why it never reaches a user here.
33///
34/// Here rather than in `main.rs` because `report` needs the same rendering:
35/// it is the one command whose own error type carried a `std::io::Error`
36/// straight into its message, and `stegobench report /tmp/nope` answered with
37/// `(os error 2)` while every other command had been saying "nothing is
38/// there" for as long as this function has existed.
39pub fn plain_io(e: &std::io::Error) -> String {
40    match e.kind() {
41        std::io::ErrorKind::NotFound => "nothing is there".to_string(),
42        std::io::ErrorKind::PermissionDenied => "permission was refused".to_string(),
43        _ => {
44            let text = e.to_string();
45            match text.split_once(" (os error") {
46                Some((head, _)) => head.to_string(),
47                None => text,
48            }
49        }
50    }
51}
52
53/// Seconds as something a person can judge a decision against.
54///
55/// Here rather than in `main.rs` because `plan` and `score` have to agree. One
56/// estimates a run before it starts and the other corrects that estimate from
57/// what the run then measures, and two renderings of one duration would have
58/// the correction read as a disagreement about the format.
59pub fn human_duration(seconds: f64) -> String {
60    if seconds < 90.0 {
61        return format!("{seconds:.0} seconds");
62    }
63    if seconds < 5_400.0 {
64        return format!("{:.0} minutes", seconds / 60.0);
65    }
66    format!("{:.1} hours", seconds / 3_600.0)
67}
68
69/// Why a detector would not be run here, in the words `score` reports it in,
70/// or `None` when it would run.
71///
72/// One function rather than one per command, because `plan` once answered
73/// this question by not asking it: a seven detector plan estimated a run that
74/// `score` then did with four, overstating the job and saying nothing at all
75/// about the three hard blockers. A pre-flight that disagrees with the run it
76/// previews is worse than no pre-flight.
77///
78/// `examine` shares it for the same reason. Asking only whether the code is
79/// present would have started a tool it had no command to drive, once per
80/// image, and recorded nothing against every one of them.
81use std::path::PathBuf;
82use stegobench_plugin::availability;
83use stegobench_plugin::availability::Presence;
84
85/// PRESENT IS NOT THE SAME AS DRIVABLE, AND `score` USED TO TREAT IT AS THE
86/// SAME.
87///
88/// Availability answers whether the code is on this machine. An entry with no
89/// invoke block passes that and still says nothing about what command to
90/// launch, so there is nothing to run. `doctor` has reported this since it
91/// shipped and `score` did not: the run announced "1 of 1 that can run here",
92/// started the tool once per image, recorded "entry declares no invoke block"
93/// against every one of them, and then refused with "the corpus holds 0 clean
94/// and 0 stego image(s)" over a corpus holding six and twelve. A gap in this
95/// project's own registry was reported as a fault in the user's corpus. It is
96/// a skip.
97///
98/// ASKED BEFORE THE PRESENCE CHECK RATHER THAN INSIDE THE PRESENT ARM, WHICH
99/// IS A CHANGE FROM WHAT THIS COMMENT USED TO ARGUE. The old order answered an
100/// entry that was neither installed nor drivable with the install step, on the
101/// grounds that it was the half the reader could act on. It is not: installing
102/// a tool whose entry says nothing about what command to launch buys a reader
103/// a download and the same refusal afterwards, and for one registered entry
104/// that download is nine gigabytes. Drivability is a property of the entry, so
105/// it is terminal, and `needs::of_tool` decides it in the same position for
106/// the same reason. One rule, asked one way, because two commands reading one
107/// registry and disagreeing about whether an entry is usable is the defect a
108/// journey found here.
109pub fn unavailable_reason(
110    entry: &stegobench_core::registry::Entry,
111    adapter_roots: &[PathBuf],
112) -> Option<String> {
113    if !crate::needs::can_be_driven(entry) {
114        return Some(crate::needs::undrivable_because(entry));
115    }
116    match availability::check(entry, adapter_roots).presence {
117        Presence::Present { .. } => None,
118        Presence::Unsupported { reason } => Some(format!("cannot run on this machine: {reason}")),
119        Presence::Absent { reason } => Some(format!(
120            "is registered but is not on this machine: {}",
121            plainer(&reason)
122        )),
123        Presence::Unknown { reason } => Some(format!(
124            "whether it can run here could not be established: {reason}"
125        )),
126    }
127}
128
129/// Image file extensions, lowercased, that a person is likely to have a folder
130/// of. Not the set the scorer supports: this is a heuristic for recognising
131/// "somebody's pictures", so it is deliberately wider.
132///
133/// Shared, because two commands now answer a question about the same folder:
134/// `score` uses it to recognise that somebody has pointed it at their own
135/// pictures, and `examine` uses it to decide which files in a directory it
136/// was handed are the images. Two lists would let the refusal and the
137/// expansion disagree about what an image is.
138pub const LOOKS_LIKE_AN_IMAGE: &[&str] = &[
139    "png", "jpg", "jpeg", "tif", "tiff", "bmp", "webp", "gif", "pgm", "ppm", "heic",
140];
141
142/// The cheapest concrete way to get one working detector, or `None` when the
143/// registry offers no answer.
144///
145/// RAISED BY A JOURNEY, 2026-10-02, AND IT WAS THE WHOLE JOURNEY.
146///
147/// A reader who had never heard the word steganography found `examine` in
148/// seconds, understood what the answer was worth in five minutes, and then
149/// could not run anything, because nothing is installed on a fresh machine
150/// and nothing anywhere said which of seven detectors to install or that one
151/// would be enough. They picked one by guessing. `doctor` lists every missing
152/// tool in registry order, which puts a 9 GB image above the 287 MB one, and
153/// they said they would have given up at the 9 GB line.
154///
155/// So this answers "which one, and what do I type", and it is derived from
156/// the registry rather than written down: a hard coded recommendation would
157/// name a tool somebody later removes, and a hard coded size would drift from
158/// the entry that declares it. Smallest first, because the barrier a beginner
159/// actually hits is the download.
160pub fn smallest_way_in(reg: &stegobench_core::registry::Registry) -> Option<String> {
161    use stegobench_core::registry::Kind;
162
163    let mut candidates: Vec<(u64, &str, &str)> = reg
164        .entries
165        .values()
166        .filter(|e| e.kind == Kind::Detector)
167        .filter_map(|e| {
168            let image = e.image.as_ref()?;
169            // Only an entry that declares its size can be called the
170            // smallest, and only a pinned reference is a thing to recommend
171            // pulling. Both are already required of every entry here; the
172            // filter is so that a future entry missing one is skipped rather
173            // than recommended on a guess.
174            Some((image.size_mb?, e.name.as_str(), image.reference.as_str()))
175        })
176        .collect();
177    // Sorted by size, then by name, so two runs over one registry recommend
178    // the same tool rather than whichever the map iterated first.
179    candidates.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.cmp(b.1)));
180
181    let (mb, name, reference) = candidates.first()?;
182    Some(format!(
183        "To ask anything about an image you need ONE detector, not all of \
184         them. The smallest is {name}, about {mb} MB:\n  \
185         docker pull {reference}\n  \
186         then: stegobench examine <your image> --detector {name}"
187    ))
188}
189
190/// Any `@sha256:<64 hex>` in a sentence, cut to its first eight characters.
191///
192/// For PROSE only. A journey called the unavailable line "a wall of hash":
193/// the full digest sits in the middle of a sentence a beginner is trying to
194/// read, and eight characters is enough to recognise it by. The pasteable
195/// command keeps its full digest, because a truncated pull command is worse
196/// than a long one.
197pub fn shorten_digests(text: &str) -> String {
198    let mut out = String::with_capacity(text.len());
199    let mut rest = text;
200    while let Some(at) = rest.find("@sha256:") {
201        let (before, from) = rest.split_at(at);
202        out.push_str(before);
203        let digest: String = from["@sha256:".len()..]
204            .chars()
205            .take_while(|c| c.is_ascii_hexdigit())
206            .collect();
207        if digest.len() == 64 {
208            out.push_str("@sha256:");
209            out.push_str(&digest[..8]);
210            out.push_str("...");
211        } else {
212            // Not a full digest, so not the thing this is for. Left exactly
213            // as it was rather than half shortened.
214            out.push_str("@sha256:");
215            out.push_str(&digest);
216        }
217        rest = &from["@sha256:".len() + digest.len()..];
218    }
219    out.push_str(rest);
220    out
221}
222
223/// The same reason, with the two phrases a journey flagged as jargon put in
224/// words somebody who has never configured a shell can act on.
225///
226/// Only the wording changes. "not on PATH" is a true statement about the
227/// reader's environment and means nothing to somebody who does not know they
228/// have one, and it was shown to exactly that reader on 2026-10-02.
229fn plainer(reason: &str) -> String {
230    if let Some(program) = reason.strip_suffix(" is not on PATH") {
231        return format!(
232            "the program `{program}` is not installed, or is not anywhere \
233             this can find it"
234        );
235    }
236    reason.to_string()
237}
238
239pub mod cli;
240pub mod examine;
241pub mod fetch;
242pub mod fixtures;
243pub mod help_topics;
244pub mod metrics;
245pub mod needs;
246pub mod registry;
247pub mod report;
248pub mod score;
249
250#[cfg(test)]
251mod novice_findings {
252    use super::*;
253
254    /// The recommendation is derived from the registry, so it cannot name a
255    /// tool somebody removed or a size that drifted from the entry.
256    #[test]
257    fn the_smallest_detector_is_the_one_recommended() {
258        let reg =
259            stegobench_core::registry::Registry::load(std::path::Path::new("plugins/registry"))
260                .or_else(|_| {
261                    stegobench_core::registry::Registry::load(std::path::Path::new(
262                        "../../plugins/registry",
263                    ))
264                })
265                .expect("the shipped registry loads");
266
267        let way = smallest_way_in(&reg).expect("the shipped registry has a sized detector");
268
269        // Whatever it names must actually be the smallest sized detector in
270        // the registry, computed here independently of the function.
271        use stegobench_core::registry::Kind;
272        let mut sizes: Vec<(u64, &str)> = reg
273            .entries
274            .values()
275            .filter(|e| e.kind == Kind::Detector)
276            .filter_map(|e| Some((e.image.as_ref()?.size_mb?, e.name.as_str())))
277            .collect();
278        sizes.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.cmp(b.1)));
279        let (mb, name) = sizes[0];
280        assert!(
281            way.contains(name),
282            "names something other than {name}: {way}"
283        );
284        assert!(way.contains(&mb.to_string()), "does not say {mb} MB: {way}");
285
286        // And it has to be actionable, which was the whole finding: the
287        // reader had to guess both which tool and that a download was the
288        // problem.
289        assert!(way.contains("docker pull"), "{way}");
290        assert!(way.contains("--detector"), "{way}");
291        assert!(way.contains("ONE detector"), "{way}");
292    }
293
294    #[test]
295    fn a_registry_with_no_sized_detector_recommends_nothing_rather_than_guessing() {
296        let empty = stegobench_core::registry::Registry::default();
297        assert!(smallest_way_in(&empty).is_none());
298    }
299
300    #[test]
301    fn a_full_digest_in_prose_is_cut_and_a_short_one_is_left_alone() {
302        let full = format!("docker pull repo/name@sha256:{}", "a".repeat(64));
303        let cut = shorten_digests(&full);
304        assert!(cut.ends_with("@sha256:aaaaaaaa..."), "{cut}");
305        assert!(!cut.contains(&"a".repeat(64)));
306
307        // Not a full digest, so not the thing this is for: left exactly as
308        // it was rather than half shortened.
309        let short = "repo/name@sha256:abc";
310        assert_eq!(shorten_digests(short), short);
311
312        // Nothing to do.
313        assert_eq!(shorten_digests("no digest here"), "no digest here");
314
315        // Two of them in one sentence, and the text around them survives.
316        let two = format!(
317            "first a@sha256:{} then b@sha256:{} end",
318            "b".repeat(64),
319            "c".repeat(64)
320        );
321        let cut = shorten_digests(&two);
322        assert_eq!(
323            cut, "first a@sha256:bbbbbbbb... then b@sha256:cccccccc... end",
324            "{cut}"
325        );
326    }
327
328    #[test]
329    fn the_path_jargon_becomes_something_a_beginner_can_act_on() {
330        let plain = plainer("stegcore is not on PATH");
331        assert!(plain.contains("`stegcore`"), "{plain}");
332        assert!(plain.contains("not installed"), "{plain}");
333        assert!(
334            !plain.contains("PATH"),
335            "still names the reader's shell: {plain}"
336        );
337
338        // Any other reason is passed through untouched; only the one phrase a
339        // journey flagged is rewritten.
340        assert_eq!(
341            plainer("not pulled. docker pull x"),
342            "not pulled. docker pull x"
343        );
344    }
345}