Skip to main content

openmoat_core/attribution/
note.rs

1//! The record `openmoat provenance --write-notes` keeps per commit in git
2//! notes (`refs/notes/openmoat`), and the checks `--verify` makes of it.
3//!
4//! A note says what the local audit log held when it was written: the
5//! log's head, and the chain hash of every event it cites. The digest over
6//! those rows and the claims ([`Note::digest_input`]) is hashed by the CLI
7//! (the core has no hash function); a note edited without the log cannot be
8//! made to verify, since `--verify` checks every cited event against the
9//! chain and attributes the commit again ([`compare`]).
10
11use serde::{Deserialize, Serialize};
12
13use super::FileRecord;
14
15/// The `format` of every note this build writes.
16pub const NOTE_FORMAT: &str = "openmoat-provenance-v1";
17
18/// The note format; an unknown one does not parse.
19#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
20pub enum NoteFormat {
21    /// The first format.
22    #[serde(rename = "openmoat-provenance-v1")]
23    V1,
24}
25
26/// The audit log's newest event when the note was written.
27#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
28#[serde(deny_unknown_fields)]
29pub struct AuditHead {
30    /// Its id.
31    pub event: i64,
32    /// Its chain hash.
33    pub hash: String,
34}
35
36/// An event a note cites, with its chain hash.
37#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
38#[serde(deny_unknown_fields)]
39pub struct EventHash {
40    /// The event's id.
41    pub event: i64,
42    /// Its chain hash.
43    pub hash: String,
44}
45
46/// One commit's provenance record.
47#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
48#[serde(deny_unknown_fields)]
49pub struct Note {
50    /// [`NOTE_FORMAT`].
51    pub format: NoteFormat,
52    /// The commit, as a full hash.
53    pub commit: String,
54    /// The log's head when the note was written.
55    pub head: AuditHead,
56    /// Every event [`Note::files`] cites, by id.
57    pub events: Vec<EventHash>,
58    /// The CLI's SHA-256 of [`Note::digest_input`], lowercase hex.
59    pub digest: String,
60    /// The files agent sessions wrote; empty when the log has none.
61    pub files: Vec<FileRecord>,
62}
63
64impl Note {
65    /// The bytes the digest covers: the format, the commit, the head, the
66    /// cited rows and every claim, each field length-prefixed so no two
67    /// notes give the same bytes.
68    #[must_use]
69    pub fn digest_input(&self) -> Vec<u8> {
70        let mut out = Vec::new();
71        let mut field = |text: &str| {
72            out.extend_from_slice(text.len().to_string().as_bytes());
73            out.push(b':');
74            out.extend_from_slice(text.as_bytes());
75            out.push(b'\n');
76        };
77        field(NOTE_FORMAT);
78        field(&self.commit);
79        field(&self.head.event.to_string());
80        field(&self.head.hash);
81        for row in &self.events {
82            field(&row.event.to_string());
83            field(&row.hash);
84        }
85        for file in &self.files {
86            field(&file.path);
87            field(&file.host);
88            field(&file.session);
89            field(&file.event.to_string());
90            field(&file.ts_ms.to_string());
91            field(file.evidence.as_str());
92            let lines: Vec<String> = file
93                .lines
94                .iter()
95                .map(|r| format!("{}-{}", r.start, r.end))
96                .collect();
97            field(&lines.join(","));
98            match &file.untrusted {
99                Some(u) => {
100                    field(u.kind.as_str());
101                    field(&u.source);
102                }
103                None => field("-"),
104            }
105        }
106        out
107    }
108}
109
110/// How a note differs from what the log says now.
111#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
112#[serde(tag = "kind", rename_all = "kebab-case")]
113pub enum Discrepancy {
114    /// The log has a write of the file by a session the note leaves out.
115    Omitted {
116        /// The file.
117        path: String,
118        /// The host.
119        host: String,
120        /// The session.
121        session: String,
122    },
123    /// The note says something else about a write the log still has.
124    Changed {
125        /// The file.
126        path: String,
127        /// The host.
128        host: String,
129        /// The session.
130        session: String,
131        /// What differs.
132        what: &'static str,
133    },
134}
135
136/// How `claimed` (a note's files) differs from `found` (the commit
137/// attributed again from today's log). A claim the log can no longer
138/// recompute (the lookup row was replaced by a later write, or aged out) is
139/// not a discrepancy: the cited event's chain hash is checked instead.
140#[must_use]
141pub fn compare(claimed: &[FileRecord], found: &[FileRecord]) -> Vec<Discrepancy> {
142    let mut out = Vec::new();
143    let same = |a: &FileRecord, b: &FileRecord| {
144        a.path == b.path && a.host == b.host && a.session == b.session
145    };
146    for now in found {
147        let Some(note) = claimed.iter().find(|c| same(c, now)) else {
148            out.push(Discrepancy::Omitted {
149                path: now.path.clone(),
150                host: now.host.clone(),
151                session: now.session.clone(),
152            });
153            continue;
154        };
155        let what = if note.event != now.event || note.ts_ms != now.ts_ms {
156            Some("the write it cites")
157        } else if note.evidence != now.evidence || note.lines != now.lines {
158            Some("how the write is tied to the file")
159        } else if note.untrusted.as_ref().map(|u| u.kind) != now.untrusted.as_ref().map(|u| u.kind)
160        {
161            Some("whether the session had read untrusted content")
162        } else {
163            None
164        };
165        if let Some(what) = what {
166            out.push(Discrepancy::Changed {
167                path: now.path.clone(),
168                host: now.host.clone(),
169                session: now.session.clone(),
170                what,
171            });
172        }
173    }
174    out
175}