Skip to main content

speccoder_runtime/hooks/
report.rs

1//! `speccoder hooks`: every hook with its trust and recent runs, and the
2//! three things a person does with one — trust it, test it, deliver what
3//! waits.
4
5use std::path::Path;
6
7use speccoder_core::hooks::{HookEntry, HookTested, HooksReport, Role, Runner, TrustState};
8use speccoder_core::{CommandData, CommandResult, CommandStatus};
9
10use super::{Digested, HookDef};
11
12fn toml_of(name: &str, definition: &serde_json::Value) -> String {
13    let body = toml::to_string(definition).unwrap_or_default();
14    format!("[hooks.{name}]\n{body}")
15}
16
17/// What keeps `def` from running here, with the fix.
18fn problem(def: &HookDef, root: &Path) -> Option<String> {
19    match &def.runner {
20        Runner::Url {
21            secret_env: Some(var),
22            ..
23        } if std::env::var_os(var).is_none() => Some(format!(
24            "${var} is not set: export the signing key, or drop `secret_env`"
25        )),
26        Runner::Argv(argv) => {
27            let program = argv.first()?;
28            let found = if program.contains('/') {
29                root.join(program).is_file() || Path::new(program).is_file()
30            } else {
31                std::env::var_os("PATH")
32                    .is_some_and(|p| std::env::split_paths(&p).any(|d| d.join(program).is_file()))
33            };
34            (!found).then(|| format!("`{program}` is not found: install it, or fix `argv`"))
35        }
36        Runner::Url { .. } => None,
37    }
38}
39
40/// One hook as the list shows it.
41#[must_use]
42pub fn entry(d: &Digested, root: &Path, dir: &Path) -> HookEntry {
43    let def = &d.def;
44    let state = super::trust::state(dir, &def.name, &d.digest);
45    let (role, on) = match &def.role {
46        Role::Gate { .. } => ("gate", Vec::new()),
47        Role::Observer { on } => ("observer", on.clone()),
48    };
49    HookEntry {
50        name: def.name.clone(),
51        role: role.to_owned(),
52        listens: def.listens(),
53        at: def.at(),
54        on,
55        runs: match &def.runner {
56            Runner::Argv(a) => a.join(" "),
57            Runner::Url { url, .. } => url.clone(),
58        },
59        state,
60        digest: d.digest.clone(),
61        files: d.files.clone(),
62        outside: d.outside.clone(),
63        definition: toml_of(&def.name, &def.definition),
64        trusted_definition: (state == TrustState::Changed)
65            .then(|| super::trust::last_trusted(dir, &def.name))
66            .flatten()
67            .map(|t| toml_of(&def.name, &t.definition)),
68        recent: super::runs(dir).remove(&def.name).unwrap_or_default(),
69        trust_flag: format!("--trust-hook {}={}", def.name, d.digest),
70        problem: problem(def, root),
71    }
72}
73
74fn result(message: &str, report: HooksReport, status: CommandStatus) -> CommandResult {
75    CommandResult::new("hooks", status, message).with_data(CommandData::Hooks(Box::new(report)))
76}
77
78fn read(
79    root: &Path,
80    state: &Path,
81) -> Result<(Vec<Digested>, std::path::PathBuf), Box<CommandResult>> {
82    match super::load(root) {
83        Ok(defs) => Ok((
84            defs.iter().map(|d| super::digest(d, root)).collect(),
85            super::dir(state, root),
86        )),
87        Err(e) => Err(Box::new(
88            result(
89                &e,
90                HooksReport {
91                    hooks: Vec::new(),
92                    problem: Some(e.clone()),
93                    trusted: Vec::new(),
94                    tested: None,
95                    delivered: None,
96                    pending: None,
97                },
98                CommandStatus::ConfigError,
99            )
100            .with_code("HOOK-MISCONFIGURED"),
101        )),
102    }
103}
104
105fn report_of(hooks: &[Digested], root: &Path, dir: &Path) -> HooksReport {
106    HooksReport {
107        hooks: hooks.iter().map(|d| entry(d, root, dir)).collect(),
108        problem: None,
109        trusted: Vec::new(),
110        tested: None,
111        delivered: None,
112        pending: None,
113    }
114}
115
116fn summary(r: &HooksReport) -> String {
117    let waiting = r
118        .hooks
119        .iter()
120        .filter(|h| h.state != TrustState::Trusted)
121        .count();
122    match (r.hooks.len(), waiting) {
123        (0, _) => "no hooks: add a [hooks.<name>] to speccoder.toml (docs: hooks)".to_owned(),
124        (1, 0) => "1 hook, trusted".to_owned(),
125        (n, 0) => format!("{n} hooks, all trusted"),
126        (n, w) => format!(
127            "{n} hook{} — {w} wait{} for your trust",
128            if n == 1 { "" } else { "s" },
129            if w == 1 { "s" } else { "" }
130        ),
131    }
132}
133
134/// `speccoder hooks`.
135#[must_use]
136pub fn list(root: &Path, state: &Path) -> CommandResult {
137    let (hooks, dir) = match read(root, state) {
138        Ok(h) => h,
139        Err(r) => return *r,
140    };
141    let report = report_of(&hooks, root, &dir);
142    let message = summary(&report);
143    result(&message, report, CommandStatus::Ok)
144}
145
146/// `speccoder hooks trust [<name>]`: each named hook (every one not
147/// trusted, without a name) that `confirm` agrees to, after it saw the
148/// entry. A newly trusted observer hears what happens from now on.
149pub fn trust(
150    root: &Path,
151    state: &Path,
152    name: Option<&str>,
153    via: &str,
154    confirm: &mut dyn FnMut(&HookEntry) -> bool,
155) -> CommandResult {
156    let (hooks, dir) = match read(root, state) {
157        Ok(h) => h,
158        Err(r) => return *r,
159    };
160    if let Some(n) = name
161        && !hooks.iter().any(|h| h.def.name == n)
162    {
163        return result(
164            &format!("there is no hook `{n}`"),
165            report_of(&hooks, root, &dir),
166            CommandStatus::NotFound,
167        );
168    }
169    let by = crate::approvals::who_in(root);
170    let mut trusted = Vec::new();
171    for d in hooks
172        .iter()
173        .filter(|h| name.is_none_or(|n| h.def.name == n))
174    {
175        let e = entry(d, root, &dir);
176        if e.state == TrustState::Trusted || !confirm(&e) {
177            continue;
178        }
179        super::trust::record(&dir, d, &by, via);
180        // A new observer hears what happens from now on; one trusted again
181        // after a change goes on where it was, missing nothing.
182        if d.def.at().is_none() && !super::deliver::has_cursor(&dir, &d.def.name) {
183            super::deliver::start_here(&dir, root, &d.def.name);
184        }
185        trusted.push(d.def.name.clone());
186    }
187    let mut report = report_of(&hooks, root, &dir);
188    let message = match trusted.len() {
189        0 => summary(&report),
190        _ => format!("trusted {}: it runs from now on", trusted.join(", ")),
191    };
192    report.trusted = trusted;
193    result(&message, report, CommandStatus::Ok)
194}
195
196/// Trusts `name` from an interface that showed `digest`: refused when the
197/// hook changed since.
198#[must_use]
199pub fn trust_shown(
200    root: &Path,
201    state: &Path,
202    name: &str,
203    digest: &str,
204    via: &str,
205) -> CommandResult {
206    let current = super::load(root)
207        .ok()
208        .and_then(|h| h.into_iter().find(|d| d.name == name))
209        .map(|d| super::digest(&d, root).digest);
210    if current.as_deref() != Some(digest) {
211        return CommandResult::new(
212            "hooks",
213            CommandStatus::UsageError,
214            &format!("{name} changed since it was shown: look at it again before trusting"),
215        )
216        .with_code("CALL-CHANGED");
217    }
218    // Only the bytes that were shown: changed in between, nothing is trusted.
219    trust(root, state, Some(name), via, &mut |e| e.digest == digest)
220}
221
222/// `speccoder hooks test <name>`: a gate alone on the checkout, or a sample
223/// event to an observer. Only a trusted hook runs.
224#[must_use]
225pub fn test(root: &Path, state: &Path, name: &str) -> CommandResult {
226    let (hooks, dir) = match read(root, state) {
227        Ok(h) => h,
228        Err(r) => return *r,
229    };
230    let Some(d) = hooks.iter().find(|h| h.def.name == name) else {
231        return result(
232            &format!("there is no hook `{name}`"),
233            report_of(&hooks, root, &dir),
234            CommandStatus::NotFound,
235        );
236    };
237    if super::trust::state(&dir, name, &d.digest) != TrustState::Trusted {
238        return result(
239            &format!("{name} waits for your trust: it runs only after you trusted it"),
240            report_of(&hooks, root, &dir),
241            CommandStatus::NeedsHuman,
242        )
243        .with_code("HOOK-UNTRUSTED")
244        .with_fix(vec![format!("speccoder hooks trust {name}")]);
245    }
246    let began = std::time::Instant::now();
247    let tested = if d.def.at().is_some() {
248        let g = super::gate::test(&d.def, root, state);
249        HookTested {
250            name: name.to_owned(),
251            outcome: g.outcome.as_str().to_owned(),
252            detail: g.reason,
253            duration_ms: g.duration_ms,
254        }
255    } else {
256        let sample = super::events::sample(&super::project_id(state, root));
257        let sent = super::deliver::send(&d.def, &sample, root, state);
258        let duration_ms = u64::try_from(began.elapsed().as_millis()).unwrap_or(u64::MAX);
259        super::record_run(
260            &dir,
261            name,
262            super::HookRun {
263                at: crate::attest::now_rfc3339(),
264                what: "test".to_owned(),
265                outcome: if sent.is_ok() { "delivered" } else { "failed" }.to_owned(),
266                duration_ms,
267                error: sent.as_ref().err().cloned(),
268            },
269        );
270        HookTested {
271            name: name.to_owned(),
272            outcome: if sent.is_ok() { "delivered" } else { "failed" }.to_owned(),
273            detail: Some(sent.unwrap_or_else(|e| e)),
274            duration_ms,
275        }
276    };
277    let words = match (tested.outcome.as_str(), tested.detail.as_deref()) {
278        ("passed", _) => format!("{name} would pass"),
279        ("blocked", Some(why)) => format!("{name} would block — {why}"),
280        ("delivered", Some(answer)) => format!("{name} took the sample event ({answer})"),
281        ("failed", Some(why)) => format!("{name} did not take the sample event — {why}"),
282        (o, _) => format!("{name}: {o}"),
283    };
284    let mut report = report_of(&hooks, root, &dir);
285    report.tested = Some(tested);
286    result(&words, report, CommandStatus::Ok)
287}
288
289/// `speccoder hooks deliver`: what waits for every trusted observer.
290#[must_use]
291pub fn deliver(root: &Path, state: &Path) -> CommandResult {
292    let (hooks, dir) = match read(root, state) {
293        Ok(h) => h,
294        Err(r) => return *r,
295    };
296    let done = super::deliver::pass(root, state, None);
297    let mut report = report_of(&hooks, root, &dir);
298    report.delivered = Some(done.delivered);
299    report.pending = Some(done.pending);
300    let mut message = if done.busy {
301        "another speccoder process is delivering; it takes what waits".to_owned()
302    } else {
303        format!(
304            "delivered {} event{}; {} pending",
305            done.delivered,
306            if done.delivered == 1 { "" } else { "s" },
307            done.pending
308        )
309    };
310    for (name, why) in &done.failed {
311        message.push_str(&format!("\n{name} failed: {why}"));
312    }
313    if !done.untrusted.is_empty() {
314        message.push_str(&format!(
315            "\nskipped (not trusted): {}",
316            done.untrusted.join(", ")
317        ));
318    }
319    let status = if done.failed.is_empty() {
320        CommandStatus::Ok
321    } else {
322        CommandStatus::Error
323    };
324    result(&message, report, status)
325}
326
327/// `--trust-hook name=digest`…: trusts each for its current digest only
328/// (`via = ci`).
329///
330/// # Errors
331///
332/// A refusal naming the flag that does not hold.
333pub fn apply_flags(root: &Path, state: &Path, flags: &[String]) -> Result<(), Box<CommandResult>> {
334    if flags.is_empty() {
335        return Ok(());
336    }
337    let (hooks, dir) = read(root, state)?;
338    let parsed = flags
339        .iter()
340        .map(|f| super::trust::parse_flag(f))
341        .collect::<Result<Vec<_>, _>>()
342        .map_err(|e| {
343            CommandResult::new("hooks", CommandStatus::UsageError, &e).with_code("USAGE")
344        })?;
345    super::trust::apply_flags(&dir, &hooks, &parsed, &crate::approvals::who_in(root)).map_err(
346        |e| CommandResult::new("hooks", CommandStatus::NeedsHuman, &e).with_code("HOOK-UNTRUSTED"),
347    )?;
348    for (name, _) in &parsed {
349        if hooks
350            .iter()
351            .any(|h| &h.def.name == name && h.def.at().is_none())
352            && !super::deliver::has_cursor(&dir, name)
353        {
354            super::deliver::start_here(&dir, root, name);
355        }
356    }
357    Ok(())
358}
359
360/// The notice a run gives once when observers are not trusted: they hear
361/// nothing until a person trusts them.
362#[must_use]
363pub fn untrusted_notice(root: &Path, state: &Path) -> Option<String> {
364    let (hooks, dir) = read(root, state).ok()?;
365    let waiting: Vec<&str> = hooks
366        .iter()
367        .filter(|h| h.def.at().is_none())
368        .filter(|h| super::trust::state(&dir, &h.def.name, &h.digest) != TrustState::Trusted)
369        .map(|h| h.def.name.as_str())
370        .collect();
371    (!waiting.is_empty()).then(|| {
372        format!(
373            "{} not trusted: {} nothing until you trust {} (speccoder hooks trust)",
374            waiting.join(", "),
375            if waiting.len() == 1 {
376                "it hears"
377            } else {
378                "they hear"
379            },
380            if waiting.len() == 1 { "it" } else { "them" }
381        )
382    })
383}