Skip to main content

gunnar_server/
attest.rs

1//! The attestation log, on the server's own store.
2//!
3//! At receive-pack time gunnar already knows who pushed, with which key, into
4//! which repo, which references moved, which objects are new and what the pack
5//! hashed to. The attestation rule says gunnar does exactly two things with that:
6//!
7//! 1. emits a `PushAttestation` on the event stream, and
8//! 2. appends **one JSON line** to a log in its own store (this module).
9//!
10//! # The dependency edge that is deliberately absent
11//!
12//! **Nothing here links the Build Thing, nornir, skade, arrow or parquet.** The
13//! log is a file of newline-delimited JSON and the event is a proto message;
14//! anything that wants a warehouse row subscribes to `Events.Watch` and writes
15//! the row itself. `tests/feature_split.rs` asserts the server half's resolved
16//! dependency graph, and this module is why that assertion has to keep holding:
17//! the moment a writer is linked in here, the appliance case (the no-OS server rule), where none
18//! of those crates could be linked at all, stops building.
19//!
20//! # Why a failed append does not fail the push
21//!
22//! The push has already happened when this is called: the references moved and
23//! the client has been told so. Returning an error here could only turn a
24//! successful push into a reported failure, which is the worst outcome of all:
25//! gunnar and the client would disagree about what is in the repository. A
26//! failure is therefore logged at `error!` and nothing else, and the operator
27//! sees a gap in the log rather than a phantom rejection.
28
29use std::io::Write;
30use std::path::{Path, PathBuf};
31
32use gunnar_proto::PushAttestation;
33
34/// The attestation log's file name, directly under the data root.
35///
36/// One file for the whole server rather than one per repository: an attestation
37/// is a provenance record of a *push*, and the consumer of the attestation wants the whole
38/// stream in arrival order. The repository is a field in every line.
39pub const ATTESTATION_LOG: &str = "attestations.jsonl";
40
41/// An append-only JSONL file.
42#[derive(Debug, Clone)]
43pub struct AttestationLog {
44    path: PathBuf,
45}
46
47impl AttestationLog {
48    /// The log under a data root.
49    pub fn under(root: impl AsRef<Path>) -> Self {
50        AttestationLog::at(root.as_ref().join(ATTESTATION_LOG))
51    }
52
53    /// The log at an explicit path.
54    pub fn at(path: impl Into<PathBuf>) -> Self {
55        AttestationLog { path: path.into() }
56    }
57
58    pub fn path(&self) -> &Path {
59        &self.path
60    }
61
62    /// Append one attestation as one line.
63    ///
64    /// The whole record, JSON plus its newline, is handed to a single
65    /// `write_all` on a file opened `O_APPEND`, so two concurrent pushes cannot
66    /// interleave halves of two lines. A reader may therefore split on `\n`
67    /// without a parser, which is the only property JSONL actually promises.
68    pub fn append(&self, attestation: &PushAttestation) -> anyhow::Result<()> {
69        let line = gunnar_grpc::attestation_json_line(attestation)?;
70        self.append_line(&line).map(|_| ())
71    }
72
73    /// **Append one record that is not a push**, and return its sequence
74    /// number — the zero-based line index it now sits at, which is also its
75    /// leaf index in the [`TransparencyLog`] over this file.
76    ///
77    /// The metered appliance's entitlement facts go through here
78    /// (`crate::entitlement`): every plan change is then a line under the
79    /// same signed tree heads as every push, so a service provider who edits
80    /// their own plan history is caught by the same audit that catches a
81    /// rewritten push. The line must be one JSON object with a top-level key
82    /// that is not a push's — [`AttestationLog::read`] tells them apart by
83    /// [`ENTITLEMENT_KEY`] and [`RECLAIM_KEY`] — and must not contain a
84    /// newline.
85    ///
86    /// Counting the existing lines is a read of the whole file, and that is
87    /// accepted: this is the rare path (a plan changes a few times a year per
88    /// tenant), and a sequence number that could be wrong would be worse than
89    /// one that costs a read. Two writers racing here can still interleave
90    /// their counts; the caller serialises (`EntitlementSlot` holds a mutex
91    /// across count-and-append).
92    pub fn append_line(&self, line: &str) -> anyhow::Result<u64> {
93        anyhow::ensure!(
94            !line.contains('\n'),
95            "an attestation record must be one line; this one holds a newline"
96        );
97        let seq = self.lines()?.len() as u64;
98        let _framed = gunnar_core::txlog::sink::append_line(&self.path, line)?;
99        let mut record = line.to_owned();
100        record.push('\n');
101        let mut file = std::fs::OpenOptions::new()
102            .create(true)
103            .append(true)
104            .open(&self.path)?;
105        file.write_all(record.as_bytes())?;
106        // **Synced, like every other framed write under the data root.** The twin's side of the
107        // same frame (`twin::append_line_once`) syncs; this did not, and
108        // `tests/appliance_powercut_recovery.rs` is what an unsynced write under this root costs
109        // on xfs — "rename journaled, data blocks not", the file back as zeroes. The frame above
110        // is already durable and the twin already has the line, so without this the PRIMARY is
111        // the only box that loses it, which is the wrong way round for the box that serves.
112        file.sync_data()?;
113        Ok(seq)
114    }
115
116    /// The raw lines, in order, blank ones dropped. The line index is the
117    /// record's sequence number and its leaf index.
118    fn lines(&self) -> anyhow::Result<Vec<String>> {
119        let text = match std::fs::read_to_string(&self.path) {
120            Ok(text) => text,
121            Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
122            Err(err) => return Err(err.into()),
123        };
124        Ok(text
125            .lines()
126            .filter(|line| !line.trim().is_empty())
127            .map(str::to_owned)
128            .collect())
129    }
130
131    /// Every push attestation in the log, in the order it was written.
132    ///
133    /// Exposed because a log nothing can read back is a log nobody can check.
134    /// A record that is not a push (an entitlement line or a cache-reclaim
135    /// line, see [`AttestationLog::append_line`]) is skipped, which is why the
136    /// **position in this vector is not a sequence number** — use
137    /// [`AttestationLog::read_indexed`] for anything that proves inclusion.
138    pub fn read(&self) -> anyhow::Result<Vec<PushAttestation>> {
139        Ok(self
140            .read_indexed()?
141            .into_iter()
142            .map(|(_, record)| record)
143            .collect())
144    }
145
146    /// [`AttestationLog::read`], with each push's line index — the number a
147    /// [`TransparencyLog`] proof is made against. The two are one function so
148    /// the index a verifier proves is the line the record was read from.
149    pub fn read_indexed(&self) -> anyhow::Result<Vec<(usize, PushAttestation)>> {
150        let mut out = Vec::new();
151        for (index, line) in self.lines()?.into_iter().enumerate() {
152            if is_non_push_line(&line) {
153                continue;
154            }
155            if is_crash_tail(&line) {
156                // The power cut's artifact, named rather than parsed. Kept as a LINE — the
157                // indices of everything before it are what proofs were made against — and not
158                // as a record. The line itself is not lost: `append_line` framed it before it
159                // wrote it, so the txlog holds it and the twin applied it.
160                tracing::warn!(
161                    target: gunnar_core::observe::TARGET_TWIN,
162                    path = %self.path.display(),
163                    index,
164                    bytes = line.len(),
165                    "a line of NUL bytes at the end of this log is a power cut's tear, not a record; \
166                     the records before it read as they did, and this box's copy of that one is torn \
167                     (the txlog and the twin hold it)"
168                );
169                continue;
170            }
171            let record: PushAttestation = serde_json::from_str(&line)
172                .map_err(|err| anyhow::anyhow!("attestation line {index} does not parse: {err}"))?;
173            // **A JSON object is not a push.** `PushAttestation`'s serde impl tolerates unknown
174            // keys and defaults everything else, so ANY object that is not a kind
175            // [`is_entitlement_line`] names came back from the line above as a push with no id,
176            // no repository, no principal and no pack hash — and `prove_pack`, `Repos.Chain` and
177            // every event listing then carried an invented record that `gunnar verify` would
178            // prove like a real one. An attestation always has an id; a record without one is a
179            // record this build does not know, and that is an error a reader sees.
180            anyhow::ensure!(
181                !record.attestation_id.is_empty(),
182                "attestation line {index} parses as a push with no attestation id — it is not a push. \
183                 A record kind this build does not know must be named in `is_entitlement_line`'s \
184                 predicate, never defaulted into a push that never happened"
185            );
186            out.push((index, record));
187        }
188        Ok(out)
189    }
190}
191
192/// **The artifact of a power cut on an appended log**: a line that is nothing but NUL bytes.
193///
194/// `tests/appliance_powercut_recovery.rs` paid for this shape once already, on
195/// `replication.json`: "rename journaled, data blocks not", and the file came back 0 bytes. An
196/// `O_APPEND` log tears the same way — xfs journals the new size before the blocks reach the
197/// platter, so the tail comes back as zeroes. It is not blank, so `lines()` keeps it; it is not
198/// JSON, so every reader used to die on it, for ever, on a box with no shell to edit it with.
199fn is_crash_tail(line: &str) -> bool {
200    !line.is_empty() && line.bytes().all(|b| b == 0)
201}
202
203/// The top-level key that marks an entitlement record in the push log. A
204/// push attestation has no such key; a line that has it is skipped by
205/// [`AttestationLog::read`] and written by `crate::entitlement`.
206pub const ENTITLEMENT_KEY: &str = "entitlement";
207
208/// The top-level key that marks a **cache-reclaim** record: the bytes of
209/// derived cache a namespace gave back when its plan fell to Suspended or
210/// Retention. Written by `crate::entitlement`, skipped by
211/// [`AttestationLog::read`] for the same reason [`ENTITLEMENT_KEY`] is.
212///
213/// It is on this log and not a log of its own because the reclaim is a
214/// *consequence of a plan change*: the fact that caused it is the line before
215/// it, under the same signed tree heads, so an operator asking "what did
216/// suspending this tenant actually give back" reads two adjacent lines and an
217/// appliance that rewrote either is caught by the same audit.
218pub const RECLAIM_KEY: &str = "cache_reclaim";
219
220/// Is this line one of the records that is **not** a push?
221///
222/// Decided by the shape of the JSON, not by a parse failure: a push line that
223/// does not parse must stay an error a reader sees, never be mistaken for a
224/// different kind of record and skipped.
225///
226/// **Every new record kind has to be named here, and the failure mode of
227/// forgetting is not the loud one it looks like.** The expectation was that an
228/// unlisted key would make [`AttestationLog::read_indexed`] error — it does
229/// hard-error on a line it cannot parse as a `PushAttestation`. That is not
230/// what happens. MEASURED 2026-09-16 by removing `RECLAIM_KEY` from this
231/// predicate and running
232/// `a_record_that_is_not_a_push_is_skipped_and_its_index_still_belongs_to_it`:
233/// `PushAttestation` tolerates unknown fields and defaults the rest, so the
234/// reclaim line came back as a **phantom push** — `(2, "")`, an attestation
235/// with no id, no repository, no principal and no pack hash — sitting between
236/// the real ones. A verifier would have proved it and an event listing would
237/// have shown it. The cost of a missing key here is an invented record, not an
238/// error, which is why the guard asserts the exact line indices rather than
239/// "it parses".
240fn is_non_push_line(line: &str) -> bool {
241    serde_json::from_str::<serde_json::Value>(line)
242        .ok()
243        .and_then(|value| {
244            value
245                .as_object()
246                .map(|map| map.contains_key(ENTITLEMENT_KEY) || map.contains_key(RECLAIM_KEY))
247        })
248        .unwrap_or(false)
249}
250
251#[cfg(test)]
252mod tests {
253    use super::*;
254    use gunnar_proto::{RefUpdate, RepoPath};
255
256    fn sample(id: &str) -> PushAttestation {
257        PushAttestation {
258            attestation_id: id.to_owned(),
259            repo: Some(RepoPath::new("team", "project")),
260            principal_id: "tester".into(),
261            principal_name: "tester".into(),
262            key_fingerprint: "SHA256:zzz".into(),
263            credential: "key:SHA256:zzz".into(),
264            hash_kind: gunnar_proto::HashKind::Sha256 as i32,
265            ref_updates: vec![RefUpdate {
266                ref_name: "refs/heads/main".into(),
267                old_oid: "0".repeat(64),
268                new_oid: "a".repeat(64),
269            }],
270            new_object_oids: vec!["b".repeat(64)],
271            new_object_oids_unknown: String::new(),
272            new_object_count: 1,
273            // Empty: this sample's object set is known, and the count above is
274            // a count rather than an absence.
275            new_object_bytes: 512,
276            pack_hash: "c".repeat(64),
277            received_at_unix_ms: 1,
278            server_agent: gunnar_proto::AGENT.into(),
279            transport: "ssh".into(),
280        }
281    }
282
283
284    /// ★ **A line written by an older gunnar must still read.** The log is
285    /// append-only and outlives every release; the 1.4.0 server on gunnar.rs
286    /// refused `Repos.Chain` on alice/linux with *"attestation line 0 does
287    /// not parse: missing field `new_object_oids_unknown`"* — a field 1.3.x
288    /// never wrote, because it did not exist. Every field the schema grows
289    /// after a log has lines is absent from those lines, so the reader must
290    /// take an absent field as its default. Here: a 1.3.0-shaped line, with
291    /// no `new_object_oids_unknown`, read back through the real reader.
292    #[test]
293    fn a_line_from_before_a_field_existed_still_reads() {
294        let dir = tempfile::tempdir().expect("temp dir");
295        let log = AttestationLog::under(dir.path());
296        let mut value = serde_json::to_value(sample("old")).expect("a sample serialises");
297        value
298            .as_object_mut()
299            .expect("an object")
300            .remove("new_object_oids_unknown")
301            .expect("the sample carried the field the old server lacked");
302        std::fs::write(log.path(), format!("{value}\n")).expect("write a 1.3.0 line");
303
304        let back = log
305            .read()
306            .expect("a line from before the field existed must still parse");
307        assert_eq!(back.len(), 1);
308        assert_eq!(back[0].attestation_id, "old");
309        assert_eq!(back[0].new_object_oids_unknown, "", "absent reads as the default");
310    }
311
312    #[test]
313    fn two_appends_are_two_lines_and_read_back_in_order() {
314        let dir = tempfile::tempdir().expect("temp dir");
315        let log = AttestationLog::under(dir.path());
316        assert!(
317            log.read().expect("an absent log reads as empty").is_empty(),
318            "a log that has never been written must read as empty, not as an error"
319        );
320
321        log.append(&sample("first")).expect("append the first");
322        log.append(&sample("second")).expect("append the second");
323
324        // Applied output: the bytes on disk, not a round-trip through the same
325        // struct. A writer that overwrote instead of appending would still make
326        // `read()` return something.
327        let raw = std::fs::read_to_string(log.path()).expect("read the raw file");
328        assert_eq!(
329            raw.lines().count(),
330            2,
331            "an append-only log must have grown by one line: {raw}"
332        );
333        assert!(raw.ends_with('\n'), "every record is newline-terminated");
334
335        let back = log.read().expect("read the log");
336        assert_eq!(
337            back.iter()
338                .map(|a| a.attestation_id.as_str())
339                .collect::<Vec<_>>(),
340            ["first", "second"],
341            "the log must preserve arrival order"
342        );
343        assert_eq!(back[0].ref_updates[0].ref_name, "refs/heads/main");
344        assert_eq!(back[0].new_object_count, 1);
345    }
346
347    /// **Every non-push record kind has to be in [`is_non_push_line`], and
348    /// what it costs to forget is an INVENTED PUSH.**
349    ///
350    /// Seen RED 2026-09-16, with `RECLAIM_KEY` taken back out of the
351    /// predicate: the reclaim line did not error, it came back as
352    /// `(2, "")` — a `PushAttestation` with every field defaulted, because
353    /// prost's serde impl tolerates an unknown key and fills the rest in.
354    /// A record with no id, no repository, no principal and no pack hash then
355    /// sits in the middle of the real ones, and `gunnar verify` proves it like
356    /// any other leaf.
357    ///
358    /// That is why this asserts the exact `(line index, id)` pairs. "It still
359    /// parses" would have been green for the broken predicate.
360    #[test]
361    fn a_record_that_is_not_a_push_is_skipped_and_its_index_still_belongs_to_it() {
362        let dir = tempfile::tempdir().expect("temp dir");
363        let log = AttestationLog::under(dir.path());
364
365        log.append(&sample("before")).expect("a push");
366        let entitlement = serde_json::json!({ ENTITLEMENT_KEY: { "tenant": "acme" } });
367        assert_eq!(log.append_line(&entitlement.to_string()).expect("a fact"), 1);
368        let reclaim =
369            serde_json::json!({ RECLAIM_KEY: { "namespace": "acme", "bytes_freed": 4096 } });
370        assert_eq!(log.append_line(&reclaim.to_string()).expect("a reclaim"), 2);
371        log.append(&sample("after")).expect("another push");
372
373        let indexed = log.read_indexed().expect("the log still reads as pushes");
374        assert_eq!(
375            indexed
376                .iter()
377                .map(|(i, a)| (*i, a.attestation_id.as_str()))
378                .collect::<Vec<_>>(),
379            [(0, "before"), (3, "after")],
380            "the two non-push lines are skipped, and the pushes keep the LINE index a \
381             proof is made against — never their position in this vector"
382        );
383    }
384
385    /// **A power cut leaves a NUL tail, and a NUL tail must not kill every read
386    /// of the log for ever.**
387    ///
388    /// The same failure this repository has already paid for once:
389    /// `tests/appliance_powercut_recovery.rs` — "`ReplicationConfig::save` wrote
390    /// `replication.json` and renamed it with no fsync, so the power cut left it
391    /// **0 bytes** on xfs (rename journaled, data blocks not)". [`AttestationLog::append_line`]
392    /// is the same shape: `O_APPEND`, one `write_all`, and no `sync_data` — while
393    /// its own twin-side sibling (`twin::append_line_once`) does sync. xfs journals
394    /// the size before the data blocks reach the platter, so the artifact of a cut
395    /// is a line of NUL bytes at the end of the file.
396    ///
397    /// That line is not blank, so `lines()` keeps it; it is not JSON, so
398    /// [`AttestationLog::read`] and [`AttestationLog::read_indexed`] hard-error on
399    /// it — and every caller of theirs dies with them: `prove_pack` (a verifier
400    /// holding an artifact), `Repos.Chain`, the whole evidence door. For ever,
401    /// on an appliance with no shell to edit the file with.
402    ///
403    /// The record itself is NOT lost: `append_line` frames the line before it
404    /// writes it, so the txlog holds it and the twin applied it. Only this box's
405    /// copy is torn. So the good records before the tear must keep reading, and
406    /// the tear must be named rather than parsed.
407    #[test]
408    fn a_nul_tail_from_a_power_cut_does_not_kill_every_read_of_the_log() {
409        use std::io::Write as _;
410        let dir = tempfile::tempdir().expect("temp dir");
411        let log = AttestationLog::under(dir.path());
412        log.append(&sample("before")).expect("a push");
413        log.append(&sample("after")).expect("another push");
414
415        // What the cut leaves: the size is there, the bytes are not.
416        let mut f = std::fs::OpenOptions::new().append(true).open(log.path()).expect("open");
417        f.write_all(&[0u8; 96]).expect("the torn tail");
418        f.write_all(b"\n").expect("and the newline xfs had already journalled");
419        drop(f);
420
421        let back = log.read().expect("the records written before the cut still read");
422        assert_eq!(back.iter().map(|a| a.attestation_id.as_str()).collect::<Vec<_>>(), ["before", "after"]);
423
424        let indexed = log.read_indexed().expect("and so do their line indices");
425        assert_eq!(indexed.iter().map(|(i, a)| (*i, a.attestation_id.as_str())).collect::<Vec<_>>(), [(0, "before"), (1, "after")]);
426    }
427
428    /// **A record kind this build does not know must not be DEFAULTED into a push
429    /// that never happened.**
430    ///
431    /// Found while pinning the power cut, and worse than it: `PushAttestation`'s
432    /// serde impl tolerates unknown keys and defaults everything else, so ANY JSON
433    /// object that [`is_non_push_line`] does not name came back out of
434    /// [`AttestationLog::read_indexed`] as a push. MEASURED on master 2026-09-16:
435    /// one line of `{"this": "..."}` produced
436    /// `(1, PushAttestation { attestation_id: "", repo: None, principal_id: "",
437    /// pack_hash: "", .. })` sitting between the real records — an invented push
438    /// that `prove_pack` would prove, `Repos.Chain` would list and `gunnar verify`
439    /// would accept like any other leaf.
440    ///
441    /// The cost of forgetting to name a new record kind is therefore not an error
442    /// a reader sees; it is a phantom. An attestation always has an id, so a record
443    /// without one is refused by name.
444    #[test]
445    fn a_json_object_that_is_not_a_push_is_refused_and_never_defaulted_into_one() {
446        let dir = tempfile::tempdir().expect("temp dir");
447        let log = AttestationLog::under(dir.path());
448        log.append(&sample("before")).expect("a push");
449        log.append_line("{\"some_later_record_kind\": {\"nobody\": \"named it here\"}}").expect("a line");
450
451        let err = log.read_indexed().expect_err("a record kind this build does not know");
452        let say = format!("{err:#}");
453        assert!(say.contains("no attestation id") && say.contains("never happened"), "{say}");
454    }
455}
456
457// ───────────────────────────────────────────────────────────────────────────
458// Push attestation, second half: the log becomes evidence
459// ───────────────────────────────────────────────────────────────────────────
460
461/// Where the signed tree heads are kept, beside the log they cover.
462///
463/// A second append-only file rather than a column in the first, because the two
464/// have different shapes: the log gains a line per push, and a head is issued
465/// when somebody asks. Putting heads in the same file would make every head a
466/// record that the next head has to cover, which is a log that can never be
467/// caught up with.
468pub const TRANSPARENCY_HEADS: &str = "transparency-heads.jsonl";
469
470/// Where signed build records are kept.
471///
472/// Its own file rather than lines in the attestation log, because the two are
473/// different records with different readers: `attestations.jsonl` parses as
474/// `PushAttestation` end to end, and a build record among them would break
475/// every reader of it. They get the same Merkle machinery — [`TransparencyLog`]
476/// is over *lines* — and their own heads.
477pub const BUILD_LOG: &str = "builds.jsonl";
478
479/// The signed tree heads over [`BUILD_LOG`].
480pub const BUILD_HEADS: &str = "build-heads.jsonl";
481
482/// Where signed forge events are kept — issues, reviews, merges.
483///
484/// **One file for the whole server**, like the attestation log and for the same
485/// reason: the consumer wants the stream in arrival order, and the repository
486/// is a field in every line. A file per repository would make "what happened on
487/// this server today" a directory walk.
488pub const FORGE_LOG: &str = "forge.jsonl";
489
490/// The signed tree heads over [`FORGE_LOG`].
491pub const FORGE_HEADS: &str = "forge-heads.jsonl";
492
493/// The signed group-membership log: one line per add/remove, each an `sshsig`
494/// the acting admin made under `gunnar-membership`. One file, in arrival order,
495/// with the group in every line, for the same reason [`FORGE_LOG`] is one file.
496pub const MEMBERSHIP_LOG: &str = "membership.jsonl";
497
498/// The signed tree heads over [`MEMBERSHIP_LOG`].
499pub const MEMBERSHIP_HEADS: &str = "membership-heads.jsonl";
500
501/// **The transparency log**: the push-attestation log, plus the evidence that it
502/// has not been rewritten.
503///
504/// # What it adds, and what it deliberately does not
505///
506/// It adds nothing to the attestation format. The Merkle tree is a **pure
507/// function of the lines already on disk** — leaf *i* is
508/// `SHA-256(0x00 ‖ line_i)` over the exact bytes of line *i*, no
509/// canonicalisation, no re-serialisation — so there is no second encoding to
510/// keep in step and no chance of hashing something other than what is stored.
511///
512/// A signed tree head at size N pins every line up to N. Rewriting line 3
513/// changes the root, so **every head issued since** stops verifying against the
514/// file: the tampering is detected by any holder of any later head, including
515/// one who never saw the original line. That is the property, and
516/// [`TransparencyLog::audit`] is the check.
517///
518/// What it does not add is a *consistency* proof between two heads (RFC 6962's
519/// second proof type). A verifier with two heads can today detect that the file
520/// changed under them; it cannot yet be shown that head M is a prefix-extension
521/// of head N without recomputing from the records. That is a real gap and it is
522/// named rather than papered over.
523#[derive(Debug, Clone)]
524pub struct TransparencyLog {
525    records: PathBuf,
526    heads: PathBuf,
527}
528
529/// One record's place in the log, and the proof that it is there.
530#[derive(Debug, Clone, PartialEq, Eq)]
531pub struct Inclusion {
532    /// Where in the log the record sits, counting from zero.
533    pub index: usize,
534    /// How many records the tree this proof is against holds.
535    pub size: usize,
536    /// The record's leaf hash, hex.
537    pub leaf: String,
538    /// The root the proof reconstructs, hex.
539    pub root: String,
540    /// The sibling hashes, hex, leaf-upwards.
541    pub proof: Vec<String>,
542}
543
544/// What an [`TransparencyLog::audit`] found.
545#[derive(Debug, Clone, PartialEq, Eq)]
546pub enum AuditVerdict {
547    /// Every stored head verifies, and every head's root matches the records
548    /// the log holds at that size.
549    Consistent { records: usize, heads: usize },
550    /// A head does not verify against the key it names.
551    HeadNotSigned { size: u64, why: String },
552    /// A head verifies, and the records do not hash to the root it swore to.
553    /// **This is tampering**: the head is authentic and the file no longer is.
554    RecordsRewritten {
555        size: u64,
556        signed_root: String,
557        actual_root: String,
558    },
559    /// A head covers more records than the log holds. Lines were removed.
560    RecordsTruncated { size: u64, records: usize },
561}
562
563impl AuditVerdict {
564    /// `true` only for [`AuditVerdict::Consistent`]. A caller that treats every
565    /// other verdict as "some problem" is right to.
566    pub fn is_consistent(&self) -> bool {
567        matches!(self, AuditVerdict::Consistent { .. })
568    }
569}
570
571impl std::fmt::Display for AuditVerdict {
572    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
573        match self {
574            AuditVerdict::Consistent { records, heads } => write!(
575                f,
576                "consistent: {records} record(s) under {heads} signed head(s)"
577            ),
578            AuditVerdict::HeadNotSigned { size, why } => {
579                write!(f, "the head at size {size} does not verify: {why}")
580            }
581            AuditVerdict::RecordsRewritten {
582                size,
583                signed_root,
584                actual_root,
585            } => write!(
586                f,
587                "THE LOG HAS BEEN REWRITTEN: the head at size {size} was signed over root \
588                 {signed_root} and the records now hash to {actual_root}"
589            ),
590            AuditVerdict::RecordsTruncated { size, records } => write!(
591                f,
592                "THE LOG HAS BEEN TRUNCATED: a head covers {size} record(s) and the log holds \
593                 {records}"
594            ),
595        }
596    }
597}
598
599impl TransparencyLog {
600    /// The push-attestation log under a data root.
601    pub fn under(root: impl AsRef<Path>) -> Self {
602        let root = root.as_ref();
603        TransparencyLog::over(root.join(ATTESTATION_LOG), root.join(TRANSPARENCY_HEADS))
604    }
605
606    /// **Any append-only JSONL file**, with its own heads beside it.
607    ///
608    /// The Merkle machinery cares about *lines*, not about what is in them, so
609    /// the same log covers push attestations and build provenance without a
610    /// second implementation (one implementation). What is record-specific is exactly two
611    /// methods — [`Self::records`] and [`Self::prove_pack`] — and they say so.
612    pub fn over(records: impl Into<PathBuf>, heads: impl Into<PathBuf>) -> Self {
613        TransparencyLog {
614            records: records.into(),
615            heads: heads.into(),
616        }
617    }
618
619    /// This log's records, **read as push attestations**.
620    ///
621    /// Only meaningful for the push log; a build log's lines are a different
622    /// shape and this would refuse them. Everything else on this type is
623    /// record-agnostic.
624    pub fn records(&self) -> AttestationLog {
625        AttestationLog::at(self.records.clone())
626    }
627
628    /// Where the records are.
629    pub fn records_path(&self) -> &Path {
630        &self.records
631    }
632
633    /// Where the signed heads are.
634    pub fn heads_path(&self) -> &Path {
635        &self.heads
636    }
637
638    /// The raw record lines, exactly as they are on disk.
639    ///
640    /// **The bytes, not the parsed attestations.** A leaf is the hash of what
641    /// was written; re-serialising a parsed record could produce different
642    /// bytes for the same push — a different field order, a different escape —
643    /// and the root would then depend on the serialiser rather than on the log.
644    fn lines(&self) -> anyhow::Result<Vec<String>> {
645        let text = match std::fs::read_to_string(&self.records) {
646            Ok(text) => text,
647            Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
648            Err(err) => return Err(err.into()),
649        };
650        Ok(text
651            .lines()
652            .filter(|line| !line.trim().is_empty())
653            .map(str::to_owned)
654            .collect())
655    }
656
657    /// The record lines, for a caller that decodes them itself.
658    ///
659    /// `pub` because the build log's records are not `PushAttestation`s and
660    /// have to be parsed by whoever knows their shape.
661    pub fn lines_of(&self) -> anyhow::Result<Vec<String>> {
662        self.lines()
663    }
664
665    fn leaves(&self) -> anyhow::Result<Vec<gunnar_core::transparency::Hash>> {
666        Ok(self
667            .lines()?
668            .iter()
669            .map(|line| gunnar_core::transparency::leaf_hash(line.as_bytes()))
670            .collect())
671    }
672
673    /// How many records the log holds.
674    pub fn len(&self) -> anyhow::Result<usize> {
675        Ok(self.lines()?.len())
676    }
677
678    pub fn is_empty(&self) -> anyhow::Result<bool> {
679        Ok(self.len()? == 0)
680    }
681
682    /// The current Merkle root, hex.
683    pub fn root(&self) -> anyhow::Result<String> {
684        Ok(gunnar_core::transparency::hex(
685            &gunnar_core::transparency::root(&self.leaves()?),
686        ))
687    }
688
689    /// Issue a signed tree head over everything the log currently holds, and
690    /// append it.
691    ///
692    /// Returns the head. Issuing one over an **empty** log is allowed and
693    /// meaningful: it is how a verifier learns the log exists and held nothing
694    /// at that moment, which is the only way "this server has never accepted a
695    /// push" can be evidence rather than an absence.
696    pub fn issue_head(
697        &self,
698        key: &gunnar_core::ssh_key::PrivateKey,
699        at_unix_ms: i64,
700    ) -> anyhow::Result<gunnar_core::SignedTreeHead> {
701        let leaves = self.leaves()?;
702        let head = gunnar_core::TreeHead {
703            size: leaves.len() as u64,
704            root: gunnar_core::transparency::hex(&gunnar_core::transparency::root(&leaves)),
705            at_unix_ms,
706        };
707        let signed = gunnar_core::transparency::sign_tree_head(key, head)?;
708        let mut line = serde_json::to_string(&signed)?;
709        line.push('\n');
710        let _framed = gunnar_core::txlog::sink::append_line(&self.heads, line.trim_end_matches('\n'))?;
711        let mut file = std::fs::OpenOptions::new()
712            .create(true)
713            .append(true)
714            .open(&self.heads)?;
715        file.write_all(line.as_bytes())?;
716        Ok(signed)
717    }
718
719    /// Every signed head that has been issued, oldest first.
720    pub fn heads(&self) -> anyhow::Result<Vec<gunnar_core::SignedTreeHead>> {
721        let text = match std::fs::read_to_string(&self.heads) {
722            Ok(text) => text,
723            Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
724            Err(err) => return Err(err.into()),
725        };
726        text.lines()
727            .filter(|line| !line.trim().is_empty())
728            .map(|line| serde_json::from_str(line).map_err(anyhow::Error::from))
729            .collect()
730    }
731
732    /// The inclusion proof for the record at `index`.
733    ///
734    /// `None` when the log does not hold that many records — a proof for a
735    /// record that is not there is not an empty proof.
736    pub fn prove(&self, index: usize) -> anyhow::Result<Option<Inclusion>> {
737        let leaves = self.leaves()?;
738        let Some(proof) = gunnar_core::transparency::inclusion_proof(&leaves, index) else {
739            return Ok(None);
740        };
741        Ok(Some(Inclusion {
742            index,
743            size: leaves.len(),
744            leaf: gunnar_core::transparency::hex(&leaves[index]),
745            root: gunnar_core::transparency::hex(&gunnar_core::transparency::root(&leaves)),
746            proof: proof.iter().map(gunnar_core::transparency::hex).collect(),
747        }))
748    }
749
750    /// Find the record for a pack hash, and prove it.
751    ///
752    /// The lookup a verifier actually makes: it holds an artifact, the artifact
753    /// names a pack, and it wants to know the push that landed it. Scans, which
754    /// is honest about the cost — an index over the log is a later problem and
755    /// pretending one exists would be worse than the scan.
756    pub fn prove_pack(&self, pack_hash: &str) -> anyhow::Result<Option<Inclusion>> {
757        // `read_indexed`, not `read` + `position`: an entitlement line between
758        // two pushes is a leaf too, so a push's vector position is not its
759        // line index, and a proof made against it would not verify.
760        let records = self.records().read_indexed()?;
761        let Some((index, _)) = records.iter().find(|(_, r)| r.pack_hash == pack_hash) else {
762            return Ok(None);
763        };
764        self.prove(*index)
765    }
766
767    /// **Check every signed head against the records on disk.**
768    ///
769    /// This is what the log is for. It answers three different questions, and
770    /// keeping them apart is the point:
771    ///
772    /// * a head that does not verify means somebody wrote a head they could not
773    ///   sign — or the key rotated and the verifier was not told;
774    /// * a head that *does* verify over a root the records no longer produce
775    ///   means the **records** were changed after they were signed for, which is
776    ///   tampering and nothing else;
777    /// * a head covering more records than exist means lines were removed.
778    ///
779    /// The first verdict wins and is returned; an operator fixes one thing at a
780    /// time.
781    pub fn audit(&self, key: &gunnar_core::ssh_key::PublicKey) -> anyhow::Result<AuditVerdict> {
782        let leaves = self.leaves()?;
783        let heads = self.heads()?;
784        for head in &heads {
785            if let Err(problem) = gunnar_core::transparency::verify_tree_head(head, key) {
786                return Ok(AuditVerdict::HeadNotSigned {
787                    size: head.head.size,
788                    why: problem.to_string(),
789                });
790            }
791            let size = head.head.size as usize;
792            if size > leaves.len() {
793                return Ok(AuditVerdict::RecordsTruncated {
794                    size: head.head.size,
795                    records: leaves.len(),
796                });
797            }
798            // The root over the FIRST `size` records: a head is a claim about a
799            // prefix, and checking it against the whole file would fail on
800            // every head but the newest.
801            let actual =
802                gunnar_core::transparency::hex(&gunnar_core::transparency::root(&leaves[..size]));
803            if actual != head.head.root {
804                return Ok(AuditVerdict::RecordsRewritten {
805                    size: head.head.size,
806                    signed_root: head.head.root.clone(),
807                    actual_root: actual,
808                });
809            }
810        }
811        Ok(AuditVerdict::Consistent {
812            records: leaves.len(),
813            heads: heads.len(),
814        })
815    }
816}