Skip to main content

ironwork_rt/
evidence.rs

1//! Run journals in cobolwork's evidence format (cobolwork `docs/spec/evidence.md` §4-6), so one
2//! verifier reads both tools: each record is canonical JSON hashed as
3//! SHA-256("cobolwork-evidence/v1\n" || record without "hash"), chained by `prev` and `seq`, and
4//! each closed run adds its tip to `ledger.jsonl`. Nothing written holds source text or a secret.
5
6use std::collections::BTreeMap;
7use std::fs::{self, File, OpenOptions};
8use std::io::{self, Read, Seek, SeekFrom, Write};
9use std::path::{Path, PathBuf};
10use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
11
12use crate::digest::{hex, sha256};
13
14const DOMAIN: &str = "cobolwork-evidence/v1\n";
15const ZERO: &str = "0000000000000000000000000000000000000000000000000000000000000000";
16pub const LEDGER: &str = "ledger.jsonl";
17const LOCK: &str = "ledger.lock";
18
19#[derive(Clone, Debug, PartialEq, Eq)]
20pub enum Value {
21    Null,
22    Bool(bool),
23    Int(i64),
24    Str(String),
25    Arr(Vec<Value>),
26    Obj(BTreeMap<String, Value>),
27}
28
29impl From<&str> for Value {
30    fn from(s: &str) -> Self {
31        Self::Str(s.to_string())
32    }
33}
34impl From<String> for Value {
35    fn from(s: String) -> Self {
36        Self::Str(s)
37    }
38}
39impl From<i64> for Value {
40    fn from(n: i64) -> Self {
41        Self::Int(n)
42    }
43}
44impl From<u64> for Value {
45    fn from(n: u64) -> Self {
46        Self::Int(i64::try_from(n).unwrap_or(i64::MAX))
47    }
48}
49impl From<bool> for Value {
50    fn from(b: bool) -> Self {
51        Self::Bool(b)
52    }
53}
54
55/// Builds the fields of one record: `fields([("dd", "IN".into()), ...])`.
56pub fn fields<const N: usize>(pairs: [(&str, Value); N]) -> BTreeMap<String, Value> {
57    pairs.into_iter().map(|(k, v)| (k.to_string(), v)).collect()
58}
59
60/// Strings escaped as JavaScript's JSON.stringify escapes them.
61fn escape(s: &str, out: &mut String) {
62    out.push('"');
63    for c in s.chars() {
64        match c {
65            '"' => out.push_str("\\\""),
66            '\\' => out.push_str("\\\\"),
67            '\u{8}' => out.push_str("\\b"),
68            '\u{c}' => out.push_str("\\f"),
69            '\n' => out.push_str("\\n"),
70            '\r' => out.push_str("\\r"),
71            '\t' => out.push_str("\\t"),
72            c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
73            c => out.push(c),
74        }
75    }
76    out.push('"');
77}
78
79/// Keys sorted by UTF-16 code unit, as JavaScript sorts them, at every depth; no whitespace.
80pub fn canonical(value: &Value) -> String {
81    let mut out = String::new();
82    write(value, &mut out);
83    out
84}
85
86fn write(value: &Value, out: &mut String) {
87    match value {
88        Value::Null => out.push_str("null"),
89        Value::Bool(b) => out.push_str(if *b { "true" } else { "false" }),
90        Value::Int(n) => out.push_str(&n.to_string()),
91        Value::Str(s) => escape(s, out),
92        Value::Arr(items) => {
93            out.push('[');
94            for (i, item) in items.iter().enumerate() {
95                if i > 0 {
96                    out.push(',');
97                }
98                write(item, out);
99            }
100            out.push(']');
101        }
102        Value::Obj(map) => {
103            let mut keys: Vec<&String> = map.keys().collect();
104            keys.sort_by(|a, b| a.encode_utf16().cmp(b.encode_utf16()));
105            out.push('{');
106            for (i, k) in keys.into_iter().enumerate() {
107                if i > 0 {
108                    out.push(',');
109                }
110                escape(k, out);
111                out.push(':');
112                write(&map[k], out);
113            }
114            out.push('}');
115        }
116    }
117}
118
119pub fn record_hash(record: &BTreeMap<String, Value>) -> String {
120    let mut body = record.clone();
121    body.remove("hash");
122    let mut text = String::from(DOMAIN);
123    text.push_str(&canonical(&Value::Obj(body)));
124    hex(&sha256(text.as_bytes()))
125}
126
127/// Each kind ironwork writes: the file it goes in, the fields it may carry and those it must. Each
128/// row stays within cobolwork's kinds table (fixtures/cobolwork/evidence/kinds.tsv), which its
129/// verifier holds every record to.
130const KINDS: [(&str, &str, &[&str], &[&str]); 13] = [
131    ("open", "journal", &["tool", "toolVersion", "toolRevision", "command", "argv", "roots", "platform"], &["tool", "toolVersion", "command", "argv", "roots"]),
132    ("input", "journal", &["root", "path", "sha256", "bytes"], &["root", "path", "sha256"]),
133    ("dd", "journal", &["dd", "event", "mode", "sha256", "bytes"], &["dd", "event"]),
134    ("call", "journal", &["program", "from", "sha256"], &["program"]),
135    ("abend", "journal", &["code", "file", "line"], &["code"]),
136    ("step", "journal", &["step", "pgm", "outcome"], &["step", "pgm", "outcome"]),
137    ("sink", "journal", &["sink", "file", "line", "marker", "reached", "input"], &["sink", "file", "line"]),
138    ("statement", "journal", &["file", "line", "capped"], &["file", "line"]),
139    ("output", "journal", &["name", "sha256", "bytes", "path", "stdout"], &["name", "sha256"]),
140    ("close", "journal", &["exit", "counts", "durationMs", "ledger"], &["exit"]),
141    ("genesis", "ledger", &["createdAt"], &["createdAt"]),
142    ("run", "ledger", &["run", "runChain", "runLength", "runTip"], &["run", "runChain", "runLength", "runTip"]),
143    ("lock-broken", "ledger", &["holderPid", "ageMs"], &["holderPid", "ageMs"]),
144];
145
146fn kind_fields(kind: &str) -> Option<(&'static [&'static str], &'static [&'static str])> {
147    KINDS.iter().find(|(name, ..)| *name == kind).map(|(_, _, allowed, required)| (*allowed, *required))
148}
149
150fn check(kind: &str, record: &BTreeMap<String, Value>) -> io::Result<()> {
151    let bad = |m: String| io::Error::new(io::ErrorKind::InvalidInput, m);
152    let (allowed, required) = kind_fields(kind).ok_or_else(|| bad(format!("no evidence record kind {kind}")))?;
153    for k in record.keys() {
154        if !allowed.contains(&k.as_str()) {
155            return Err(bad(format!("{kind}: no field {k}")));
156        }
157    }
158    for k in required {
159        if !record.contains_key(*k) {
160            return Err(bad(format!("{kind}: {k} is required")));
161        }
162    }
163    Ok(())
164}
165
166/// Now, as JavaScript's Date.prototype.toISOString writes it.
167pub fn iso_now() -> String {
168    let d = SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default();
169    iso(d.as_secs() as i64, d.subsec_millis())
170}
171
172pub fn iso(seconds: i64, millis: u32) -> String {
173    let c = crate::calendar::civil(seconds);
174    format!("{:04}-{:02}-{:02}T{:02}:{:02}:{:02}.{:03}Z", c.year, c.month, c.day, c.hour, c.minute, c.second, millis)
175}
176
177/// `n` unpredictable bytes from the operating system, or, where it offers none, bytes that are
178/// unique to this process and moment: a chain id must not repeat, and needs no secrecy.
179fn random(n: usize) -> Vec<u8> {
180    let mut buf = vec![0u8; n];
181    if File::open("/dev/urandom").and_then(|mut f| f.read_exact(&mut buf)).is_ok() {
182        return buf;
183    }
184    use std::hash::{BuildHasher, Hasher};
185    let d = SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default();
186    let mut keyed = std::collections::hash_map::RandomState::new().build_hasher();
187    keyed.write_u128(d.as_nanos());
188    let seed = format!("{}:{}:{:p}:{}", d.as_nanos(), std::process::id(), &buf, keyed.finish());
189    sha256(seed.as_bytes())[..n.min(32)].to_vec()
190}
191
192fn open_new(path: &Path) -> io::Result<File> {
193    let mut o = OpenOptions::new();
194    o.write(true).create_new(true);
195    #[cfg(unix)]
196    {
197        use std::os::unix::fs::OpenOptionsExt;
198        o.mode(0o600);
199    }
200    o.open(path)
201}
202
203fn refuse_link(path: &Path) -> io::Result<()> {
204    match fs::symlink_metadata(path) {
205        Ok(m) if m.file_type().is_symlink() => Err(io::Error::new(io::ErrorKind::InvalidInput, format!("{} is a symbolic link, which evidence is not written through", path.display()))),
206        _ => Ok(()),
207    }
208}
209
210/// The evidence directory with runs/ and seals/, refusing a link at any of the three, and a
211/// directory inside a tree the run reads.
212pub fn prepare(dir: &Path, reads: &[PathBuf]) -> io::Result<PathBuf> {
213    let absolute = std::path::absolute(dir)?;
214    let mut existing = absolute.clone();
215    let mut rest = Vec::new();
216    while !existing.exists() {
217        match (existing.file_name().map(|n| n.to_os_string()), existing.parent()) {
218            (Some(name), Some(parent)) => {
219                rest.push(name);
220                existing = parent.to_path_buf();
221            }
222            _ => break,
223        }
224    }
225    let mut intended = fs::canonicalize(&existing)?;
226    for name in rest.iter().rev() {
227        intended.push(name);
228    }
229    for root in reads {
230        let tree = if root.as_os_str().is_empty() { Path::new(".") } else { root };
231        if let Ok(r) = fs::canonicalize(tree)
232            && intended.starts_with(&r)
233        {
234            return Err(io::Error::new(io::ErrorKind::InvalidInput, format!("the evidence directory {} is inside {}, which this run reads", dir.display(), root.display())));
235        }
236    }
237    for p in [absolute.clone(), absolute.join("runs"), absolute.join("seals")] {
238        refuse_link(&p)?;
239        if !p.exists() {
240            fs::create_dir_all(&p)?;
241            #[cfg(unix)]
242            {
243                use std::os::unix::fs::PermissionsExt;
244                fs::set_permissions(&p, fs::Permissions::from_mode(0o700))?;
245            }
246        }
247        refuse_link(&p)?;
248    }
249    let made = fs::canonicalize(&absolute)?;
250    if made != intended {
251        return Err(io::Error::new(io::ErrorKind::InvalidInput, format!("the evidence directory {} resolved to {} while it was made", dir.display(), made.display())));
252    }
253    Ok(made)
254}
255
256struct Chain {
257    chain: String,
258    seq: i64,
259    prev: String,
260}
261
262impl Chain {
263    fn record(&mut self, kind: &str, mut fields: BTreeMap<String, Value>, at: &str) -> io::Result<String> {
264        check(kind, &fields)?;
265        fields.insert("v".into(), Value::Int(1));
266        fields.insert("chain".into(), Value::Str(self.chain.clone()));
267        fields.insert("seq".into(), Value::Int(self.seq));
268        fields.insert("at".into(), Value::Str(at.to_string()));
269        fields.insert("kind".into(), Value::Str(kind.to_string()));
270        fields.insert("prev".into(), Value::Str(self.prev.clone()));
271        let hash = record_hash(&fields);
272        fields.insert("hash".into(), Value::Str(hash.clone()));
273        self.prev = hash;
274        self.seq += 1;
275        Ok(format!("{}\n", canonical(&Value::Obj(fields))))
276    }
277}
278
279pub struct Journal {
280    pub id: String,
281    pub path: PathBuf,
282    dir: PathBuf,
283    file: File,
284    chain: Chain,
285    counts: BTreeMap<String, i64>,
286    started: Instant,
287}
288
289/// Where a closed run's tip went.
290#[derive(Debug, PartialEq, Eq)]
291pub enum Ledger {
292    Recorded,
293    Unrecorded(String),
294}
295
296impl Journal {
297    pub fn create(dir: &Path, reads: &[PathBuf], command: &str, argv: &[String], tool_version: &str) -> io::Result<Self> {
298        let dir = prepare(dir, reads)?;
299        let now = iso_now();
300        let stamp: String = now.chars().filter(|c| c.is_ascii_digit() || *c == 'T').take(15).collect();
301        let id = format!("{stamp}Z-{}", hex(&random(8)));
302        let path = dir.join("runs").join(format!("{id}.jsonl"));
303        let file = open_new(&path)?;
304        let mut journal = Self { id, path, dir, file, chain: Chain { chain: hex(&random(16)), seq: 0, prev: ZERO.into() }, counts: BTreeMap::new(), started: Instant::now() };
305        let roots = reads.iter().map(|r| Value::Str(r.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default())).collect();
306        journal.append_at(
307            "open",
308            fields([
309                ("tool", "ironwork".into()),
310                ("toolVersion", tool_version.into()),
311                ("command", command.into()),
312                ("argv", Value::Arr(argv.iter().map(|a| Value::Str(a.clone())).collect())),
313                ("roots", Value::Arr(roots)),
314                ("platform", std::env::consts::OS.into()),
315            ]),
316            &now,
317        )?;
318        Ok(journal)
319    }
320
321    fn append_at(&mut self, kind: &str, fields: BTreeMap<String, Value>, at: &str) -> io::Result<()> {
322        let line = self.chain.record(kind, fields, at)?;
323        self.file.write_all(line.as_bytes())?;
324        *self.counts.entry(kind.to_string()).or_default() += 1;
325        Ok(())
326    }
327
328    /// The hash of the last record written.
329    pub fn tip(&self) -> &str {
330        &self.chain.prev
331    }
332
333    pub fn append(&mut self, kind: &str, fields: BTreeMap<String, Value>) -> io::Result<()> {
334        self.append_at(kind, fields, &iso_now())
335    }
336
337    /// Writes close, then the ledger record carrying this journal's tip.
338    pub fn close(mut self, exit: Option<i64>) -> io::Result<Ledger> {
339        let lock = self.dir.join(LOCK);
340        let held = take_lock(&lock, LOCK_WAIT);
341        let counts = self.counts.iter().map(|(k, v)| (k.clone(), Value::Int(*v))).collect();
342        let ledger = if held.is_ok() { "recorded" } else { "unrecorded" };
343        let duration = i64::try_from(self.started.elapsed().as_millis()).unwrap_or(i64::MAX);
344        self.append("close", fields([("exit", exit.map_or(Value::Null, Value::Int)), ("counts", Value::Obj(counts)), ("durationMs", Value::Int(duration)), ("ledger", ledger.into())]))?;
345        self.file.sync_all()?;
346        let broken = match held {
347            Ok(broken) => broken,
348            Err(reason) => return Ok(Ledger::Unrecorded(reason)),
349        };
350        let result = append_ledger(&self.dir, &self.id, &self.chain, broken);
351        let _ = fs::remove_file(&lock);
352        match result {
353            Ok(()) => Ok(Ledger::Recorded),
354            Err(e) => Ok(Ledger::Unrecorded(e.to_string())),
355        }
356    }
357}
358
359const LOCK_WAIT: Duration = Duration::from_secs(5);
360const LOCK_STALE_MS: i64 = 60_000;
361
362/// A lock that was broken: the pid it names, if it names one, and its age.
363struct Broken {
364    pid: Option<i64>,
365    age_ms: i64,
366}
367
368/// The ledger lock, broken as cobolwork breaks it (cobolwork `docs/spec/evidence.md` §6): a lock
369/// older than a minute whose holder is not running. It is aged from the time it holds or, holding
370/// none, from its modification time. The break goes into the ledger.
371fn take_lock(path: &Path, wait: Duration) -> Result<Option<Broken>, String> {
372    let deadline = Instant::now() + wait;
373    loop {
374        match open_new(path) {
375            Ok(mut f) => {
376                let _ = writeln!(f, "{} {}", std::process::id(), now_ms());
377                return Ok(None);
378            }
379            Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {
380                if let Some(seen) = read_lock(path)
381                    && seen.stale()
382                    && break_stale(path, &seen)
383                {
384                    return Ok(Some(Broken { pid: seen.pid, age_ms: seen.age_ms }));
385                }
386                if Instant::now() >= deadline {
387                    return Err("the ledger lock could not be had".into());
388                }
389                std::thread::sleep(Duration::from_millis(25));
390            }
391            Err(e) => return Err(e.to_string()),
392        }
393    }
394}
395
396fn now_ms() -> i64 {
397    i64::try_from(SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default().as_millis()).unwrap_or(i64::MAX)
398}
399
400/// A lock as read: its contents, its file's identity, the pid it names and its age.
401struct SeenLock {
402    text: Vec<u8>,
403    file: u64,
404    pid: Option<i64>,
405    age_ms: i64,
406}
407
408fn file_id(meta: &fs::Metadata) -> u64 {
409    #[cfg(unix)]
410    {
411        std::os::unix::fs::MetadataExt::ino(meta)
412    }
413    #[cfg(not(unix))]
414    {
415        let _ = meta;
416        0
417    }
418}
419
420fn read_lock(path: &Path) -> Option<SeenLock> {
421    let meta = fs::symlink_metadata(path).ok()?;
422    let text = fs::read(path).ok()?;
423    let mut numbers = String::from_utf8_lossy(&text).split_whitespace().map(|w| w.parse::<i64>().ok().filter(|n| *n > 0)).collect::<Vec<_>>().into_iter();
424    let pid = numbers.next().flatten();
425    let since = numbers.next().flatten();
426    let age_ms = match (pid, since) {
427        (Some(_), Some(since)) => now_ms().saturating_sub(since),
428        _ => meta.modified().ok().and_then(|t| t.elapsed().ok()).map_or(0, |d| i64::try_from(d.as_millis()).unwrap_or(i64::MAX)),
429    };
430    Some(SeenLock { text, file: file_id(&meta), pid, age_ms })
431}
432
433impl SeenLock {
434    fn stale(&self) -> bool {
435        self.age_ms > LOCK_STALE_MS && !self.pid.is_some_and(running)
436    }
437}
438
439/// Whether process `pid` is running; where that cannot be told, it is taken as not running.
440fn running(pid: i64) -> bool {
441    #[cfg(target_os = "linux")]
442    {
443        Path::new("/proc").join(pid.to_string()).exists()
444    }
445    #[cfg(all(unix, not(target_os = "linux")))]
446    {
447        std::process::Command::new("ps").args(["-p", &pid.to_string(), "-o", "pid="]).output().is_ok_and(|o| o.status.success() && !o.stdout.trim_ascii().is_empty())
448    }
449    #[cfg(not(unix))]
450    {
451        let _ = pid;
452        false
453    }
454}
455
456/// Replaces the stale lock `seen` with this writer's own. Breakers hold `ledger.lock.break` while
457/// they break, so one breaks at a time, and rename it over the lock only while the lock is still
458/// the file judged stale: a lock a peer took since is never moved. Returns whether this writer
459/// holds the lock.
460fn break_stale(path: &Path, seen: &SeenLock) -> bool {
461    let claim = path.with_file_name(format!("{LOCK}.break"));
462    let Ok(mut f) = open_new(&claim) else {
463        if read_lock(&claim).is_some_and(|left| left.stale()) {
464            let _ = fs::remove_file(&claim);
465        }
466        return false;
467    };
468    let _ = writeln!(f, "{} {}", std::process::id(), now_ms());
469    drop(f);
470    if read_lock(path).is_some_and(|current| current.file == seen.file && current.text == seen.text) && fs::rename(&claim, path).is_ok() {
471        return true;
472    }
473    let _ = fs::remove_file(&claim);
474    false
475}
476
477/// The last line of the ledger, or None for an empty or absent one; an unterminated last line is
478/// refused rather than extended.
479fn ledger_tail(path: &Path) -> io::Result<Option<String>> {
480    // nosemgrep: rust.actix.path-traversal.tainted-path.tainted-path -- the ledger path the run was given
481    let mut f = match File::open(path) {
482        Ok(f) => f,
483        Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(None),
484        Err(e) => return Err(e),
485    };
486    let size = f.metadata()?.len();
487    if size == 0 {
488        return Ok(None);
489    }
490    let window = size.min(65536);
491    f.seek(SeekFrom::Start(size - window))?;
492    let mut buf = Vec::new();
493    f.take(window).read_to_end(&mut buf)?;
494    let text = String::from_utf8_lossy(&buf);
495    let body = text.strip_suffix('\n').ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "ledger.jsonl ends in a partial line"))?;
496    match body.rsplit_once('\n') {
497        Some((_, last)) => Ok(Some(last.to_string())),
498        None if window < size => Err(io::Error::new(io::ErrorKind::InvalidData, "the ledger's last line is longer than any ledger record")),
499        None => Ok(Some(body.to_string())),
500    }
501}
502
503/// The value of a top-level string or integer field in one canonical record line.
504fn field_of(line: &str, key: &str) -> Option<String> {
505    let needle = format!("\"{key}\":");
506    let at = line.find(&needle)? + needle.len();
507    let rest = &line[at..];
508    if let Some(s) = rest.strip_prefix('"') {
509        return s.find('"').map(|end| s[..end].to_string());
510    }
511    Some(rest.chars().take_while(|c| c.is_ascii_digit()).collect())
512}
513
514fn append_ledger(dir: &Path, run: &str, journal: &Chain, broken: Option<Broken>) -> io::Result<()> {
515    let path = dir.join(LEDGER);
516    refuse_link(&path)?;
517    let mut chain = match ledger_tail(&path)? {
518        Some(line) => {
519            let bad = || io::Error::new(io::ErrorKind::InvalidData, "the ledger's last line is not a ledger record");
520            let hex_of = |key: &str, len: usize| field_of(&line, key).filter(|v| v.len() == len && v.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)));
521            let seq: i64 = field_of(&line, "seq").and_then(|s| s.parse().ok()).ok_or_else(bad)?;
522            Chain { chain: hex_of("chain", 32).ok_or_else(bad)?, seq: seq + 1, prev: hex_of("hash", 64).ok_or_else(bad)? }
523        }
524        None => Chain { chain: hex(&random(16)), seq: 0, prev: ZERO.into() },
525    };
526    let mut out = String::new();
527    let now = iso_now();
528    if chain.seq == 0 {
529        out.push_str(&chain.record("genesis", fields([("createdAt", now.clone().into())]), &now)?);
530    }
531    if let Some(b) = broken {
532        out.push_str(&chain.record("lock-broken", fields([("holderPid", b.pid.map_or(Value::Null, Value::Int)), ("ageMs", Value::Int(b.age_ms))]), &now)?);
533    }
534    out.push_str(&chain.record(
535        "run",
536        fields([("run", run.into()), ("runChain", journal.chain.clone().into()), ("runLength", Value::Int(journal.seq)), ("runTip", journal.prev.clone().into())]),
537        &now,
538    )?);
539    let mut f = OpenOptions::new().append(true).create(true).open(&path)?;
540    f.write_all(out.as_bytes())?;
541    f.sync_all()
542}
543
544#[cfg(test)]
545mod tests {
546    use super::*;
547
548    fn temp() -> PathBuf {
549        let p = std::env::temp_dir().join(format!("iw-evidence-{}", hex(&random(6))));
550        fs::create_dir_all(&p).unwrap();
551        p
552    }
553
554    #[test]
555    fn canonical_form_matches_javascript() {
556        let v = Value::Obj(fields([("b", Value::Int(2)), ("a", "q\"\\\n\u{1}é".into()), ("Z", Value::Arr(vec![Value::Null, Value::Bool(true)]))]));
557        assert_eq!(canonical(&v), "{\"Z\":[null,true],\"a\":\"q\\\"\\\\\\n\\u0001é\",\"b\":2}");
558    }
559
560    #[test]
561    fn the_hash_is_over_the_domain_tag_and_the_record_without_its_hash() {
562        let r = fields([("kind", "abend".into()), ("code", "S0C7".into()), ("hash", "ignored".into())]);
563        assert_eq!(record_hash(&r), hex(&sha256(b"cobolwork-evidence/v1\n{\"code\":\"S0C7\",\"kind\":\"abend\"}")));
564    }
565
566    #[test]
567    fn a_closed_journal_chains_and_reaches_the_ledger() {
568        let dir = temp();
569        let mut j = Journal::create(&dir.join("ev"), &[], "run", &["run".into()], "0.0.0").unwrap();
570        j.append("dd", fields([("dd", "IN".into()), ("event", "open".into()), ("mode", "INPUT".into()), ("sha256", hex(&sha256(b"x")).into()), ("bytes", Value::Int(1))])).unwrap();
571        let path = j.path.clone();
572        let id = j.id.clone();
573        assert_eq!(j.close(Some(0)).unwrap(), Ledger::Recorded);
574        let lines: Vec<String> = fs::read_to_string(&path).unwrap().lines().map(String::from).collect();
575        assert_eq!(lines.len(), 3);
576        let mut prev = ZERO.to_string();
577        for (i, line) in lines.iter().enumerate() {
578            assert_eq!(field_of(line, "seq").unwrap(), i.to_string());
579            assert_eq!(field_of(line, "prev").unwrap(), prev);
580            prev = field_of(line, "hash").unwrap();
581        }
582        let ledger = fs::read_to_string(dir.join("ev").join(LEDGER)).unwrap();
583        let run = ledger.lines().last().unwrap();
584        assert_eq!(field_of(run, "run").unwrap(), id);
585        assert_eq!(field_of(run, "runTip").unwrap(), prev);
586        assert_eq!(field_of(run, "runLength").unwrap(), "3");
587        fs::remove_dir_all(dir).unwrap();
588    }
589
590    #[test]
591    fn an_unknown_field_is_refused() {
592        let dir = temp();
593        let mut j = Journal::create(&dir.join("ev"), &[], "run", &[], "0.0.0").unwrap();
594        assert!(j.append("dd", fields([("dd", "IN".into()), ("event", "open".into()), ("record", "SECRET".into())])).is_err());
595        fs::remove_dir_all(dir).unwrap();
596    }
597
598    /// The rows of one of cobolwork's evidence tables (fixtures/cobolwork/evidence).
599    fn cobolwork_table(name: &str) -> Vec<String> {
600        let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/cobolwork/evidence").join(name);
601        let table = fs::read_to_string(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display()));
602        table.lines().filter(|l| !l.is_empty() && !l.starts_with('#')).map(String::from).collect()
603    }
604
605    /// cobolwork's verifier refuses a kind it does not know, a field it does not list, and a record
606    /// without a field it requires.
607    #[test]
608    fn every_kind_ironwork_writes_is_one_cobolworks_verifier_accepts() {
609        let table = cobolwork_table("kinds.tsv");
610        let words = |cell: &str| cell.split(' ').filter(|w| !w.is_empty()).map(String::from).collect::<Vec<_>>();
611        let theirs: BTreeMap<&str, (&str, Vec<String>, Vec<String>)> = table
612            .iter()
613            .map(|l| match l.split('\t').collect::<Vec<_>>()[..] {
614                [kind, file, fields, required] => (kind, (file, words(fields), words(required))),
615                ref row => panic!("a row has four cells: {row:?}"),
616            })
617            .collect();
618        for (kind, file, allowed, required) in KINDS {
619            let (their_file, their_fields, their_required) = theirs.get(kind).unwrap_or_else(|| panic!("cobolwork's verifier knows no {kind} record"));
620            assert_eq!(file, *their_file, "{kind}: cobolwork reads it from the {their_file}");
621            for field in allowed {
622                assert!(their_fields.iter().any(|f| f == field), "{kind}: cobolwork's verifier refuses {field}");
623            }
624            for field in their_required {
625                assert!(required.contains(&field.as_str()), "{kind}: cobolwork's verifier requires {field}, which ironwork may leave out");
626            }
627        }
628    }
629
630    /// A sink record joins a cobolwork finding by its kind.
631    #[test]
632    fn every_sink_kind_ironwork_raises_is_one_cobolwork_names() {
633        use crate::cics::Sink;
634        let theirs = cobolwork_table("sinks.tsv");
635        for kind in crate::unit::SINK_KINDS {
636            assert!(theirs.iter().any(|k| k == kind), "cobolwork names no {kind} sink");
637        }
638        let cics = [Sink::DynamicTransfer, Sink::RecordKey, Sink::RecordUpdate, Sink::Log, Sink::Screen, Sink::WebResponse, Sink::HttpHeader, Sink::OutboundHost, Sink::OutboundHttp, Sink::QueueName, Sink::Sysid];
639        for sink in cics {
640            // No wildcard: a new variant does not compile here until it is listed in `cics`.
641            let (Sink::DynamicTransfer | Sink::RecordKey | Sink::RecordUpdate | Sink::Log | Sink::Screen | Sink::WebResponse | Sink::HttpHeader | Sink::OutboundHost | Sink::OutboundHttp | Sink::QueueName | Sink::Sysid) = sink;
642            assert!(crate::unit::SINK_KINDS.contains(&sink.kind()), "{} is not in SINK_KINDS", sink.kind());
643        }
644    }
645
646    #[test]
647    fn an_evidence_directory_inside_a_tree_read_is_refused() {
648        let dir = temp();
649        assert!(prepare(&dir.join("src").join("ev"), std::slice::from_ref(&dir)).is_err());
650        assert!(!dir.join("src").exists());
651        fs::remove_dir_all(dir).unwrap();
652    }
653
654    fn closed(ev: &Path) -> Ledger {
655        Journal::create(ev, &[], "run", &[], "0.0.0").unwrap().close(Some(0)).unwrap()
656    }
657
658    fn ledger_lines(ev: &Path) -> Vec<String> {
659        fs::read_to_string(ev.join(LEDGER)).unwrap().lines().map(String::from).collect()
660    }
661
662    #[test]
663    fn an_empty_lock_is_aged_from_its_modification_time_and_names_no_holder() {
664        let dir = temp();
665        let ev = dir.join("ev");
666        prepare(&ev, &[]).unwrap();
667        let lock = File::create(ev.join(LOCK)).unwrap();
668        lock.set_modified(SystemTime::now() - Duration::from_secs(120)).unwrap();
669        drop(lock);
670        assert_eq!(closed(&ev), Ledger::Recorded);
671        assert!(!ev.join(LOCK).exists());
672        let lines = ledger_lines(&ev);
673        assert_eq!(lines.iter().map(|l| field_of(l, "kind").unwrap()).collect::<Vec<_>>(), ["genesis", "lock-broken", "run"]);
674        assert!(lines[1].contains("\"holderPid\":null"), "{}", lines[1]);
675        fs::remove_dir_all(dir).unwrap();
676    }
677
678    #[test]
679    fn a_stale_lock_is_aged_from_the_time_it_holds_and_names_its_holder() {
680        let dir = temp();
681        let ev = dir.join("ev");
682        prepare(&ev, &[]).unwrap();
683        let mut gone = std::process::Command::new(std::env::current_exe().unwrap()).arg("--list").stdout(std::process::Stdio::null()).spawn().unwrap();
684        gone.wait().unwrap();
685        fs::write(ev.join(LOCK), format!("{} {}\n", gone.id(), now_ms() - 120_000)).unwrap();
686        assert_eq!(closed(&ev), Ledger::Recorded);
687        let lines = ledger_lines(&ev);
688        assert_eq!(field_of(&lines[1], "kind").unwrap(), "lock-broken");
689        assert_eq!(field_of(&lines[1], "holderPid").unwrap(), gone.id().to_string());
690        fs::remove_dir_all(dir).unwrap();
691    }
692
693    #[test]
694    fn a_stale_lock_whose_holder_is_running_is_waited_for() {
695        let dir = temp();
696        let lock = dir.join(LOCK);
697        let held = format!("{} {}\n", std::process::id(), now_ms() - 120_000);
698        fs::write(&lock, &held).unwrap();
699        assert!(take_lock(&lock, Duration::from_millis(100)).is_err());
700        assert_eq!(fs::read_to_string(&lock).unwrap(), held);
701        fs::remove_dir_all(dir).unwrap();
702    }
703
704    fn locks(dir: &Path) -> Vec<String> {
705        fs::read_dir(dir).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).filter(|n| n.starts_with(LOCK)).collect()
706    }
707
708    /// A file's inode and change time. A rename or a link changes the change time, so an unchanged
709    /// pair shows the file never left its path.
710    #[cfg(unix)]
711    fn identity(path: &Path) -> (u64, i64, i64) {
712        use std::os::unix::fs::MetadataExt;
713        let meta = fs::metadata(path).unwrap();
714        (meta.ino(), meta.ctime(), meta.ctime_nsec())
715    }
716
717    #[cfg(unix)]
718    #[test]
719    fn a_lock_taken_after_a_stale_one_was_read_is_left_alone() {
720        let dir = temp();
721        let lock = dir.join(LOCK);
722        fs::write(&lock, format!("999999 {}\n", now_ms() - 120_000)).unwrap();
723        let stale = read_lock(&lock).unwrap();
724        fs::remove_file(&lock).unwrap();
725        let peer = format!("{} {}\n", std::process::id(), now_ms());
726        fs::write(&lock, &peer).unwrap();
727        let before = identity(&lock);
728        assert!(!break_stale(&lock, &stale));
729        assert_eq!(identity(&lock), before);
730        assert_eq!(fs::read_to_string(&lock).unwrap(), peer);
731        assert_eq!(locks(&dir), [LOCK]);
732        assert!(break_stale(&lock, &read_lock(&lock).unwrap()));
733        assert_ne!(identity(&lock).0, before.0);
734        assert_eq!(locks(&dir), [LOCK]);
735        fs::remove_dir_all(dir).unwrap();
736    }
737
738    #[test]
739    fn a_breakers_claim_is_waited_for_while_held_and_removed_once_stale() {
740        let dir = temp();
741        let ev = dir.join("ev");
742        prepare(&ev, &[]).unwrap();
743        let mut gone = std::process::Command::new(std::env::current_exe().unwrap()).arg("--list").stdout(std::process::Stdio::null()).spawn().unwrap();
744        gone.wait().unwrap();
745        let stale = format!("{} {}\n", gone.id(), now_ms() - 120_000);
746        fs::write(ev.join(LOCK), &stale).unwrap();
747        let claim = ev.join(format!("{LOCK}.break"));
748        fs::write(&claim, format!("{} {}\n", std::process::id(), now_ms())).unwrap();
749        assert!(take_lock(&ev.join(LOCK), Duration::from_millis(100)).is_err());
750        assert_eq!(fs::read_to_string(ev.join(LOCK)).unwrap(), stale);
751        fs::write(&claim, &stale).unwrap();
752        assert_eq!(closed(&ev), Ledger::Recorded);
753        assert_eq!(field_of(&ledger_lines(&ev)[1], "kind").unwrap(), "lock-broken");
754        assert!(locks(&ev).is_empty());
755        fs::remove_dir_all(dir).unwrap();
756    }
757
758    #[test]
759    fn a_ledger_whose_last_line_is_no_ledger_record_is_not_extended() {
760        let dir = temp();
761        let ev = dir.join("ev");
762        prepare(&ev, &[]).unwrap();
763        for tail in ["{\"seq\":0}\n".to_string(), format!("{{\"chain\":\"{}\",\"hash\":\"{}\",\"seq\":0}}\n", "a".repeat(31), "b".repeat(64)), format!("{}\n", "x".repeat(70_000))] {
764            fs::write(ev.join(LEDGER), &tail).unwrap();
765            assert!(matches!(closed(&ev), Ledger::Unrecorded(_)), "{}", &tail[..20]);
766            assert_eq!(fs::read_to_string(ev.join(LEDGER)).unwrap(), tail);
767        }
768        fs::remove_dir_all(dir).unwrap();
769    }
770}