Skip to main content

git_attest/
format.rs

1//! The attestation format: the payload's fields, the note's blocks, and the
2//! names every producer and verifier shares (SPEC.md, "The note").
3
4/// First token of every payload written (the GREEN name since 1.10.0; see
5/// [`WRITE`]; the LEGACY one is still read). A verifier that does not recognise this
6/// string must treat the note as absent: an unknown version may mean anything,
7/// and "run the tests" is the only safe reading of anything.
8pub const FORMAT: &str = WRITE.format;
9
10/// The notes ref, as `git notes --ref` wants it.
11pub const NOTES_REF: &str = WRITE.notes_ref;
12
13/// The second notes ref, keyed by input fingerprint rather than by object.
14/// Every key there is a synthetic oid that is not an object, which is why it
15/// is a separate ref: `git notes prune` on it would drop everything, and the
16/// main ref keeps its 1.x invariant that every key is real.
17pub const INPUTS_REF: &str = WRITE.inputs_ref;
18
19/// Where `sign.sh --no-push` keeps blocks that never reached origin, under
20/// `refs/notes/`, prefixed to either ref name above. Origin cannot revoke
21/// them, so a verifier reads them only when asked (`--include-local`).
22pub const LOCAL_PREFIX: &str = "attest-local/";
23
24/// The `ssh-keygen -Y` namespace. Namespaces exist so a signature minted for
25/// one purpose cannot be replayed for another; an `allowed_signers` entry
26/// pinned to this namespace accepts nothing else.
27pub const NAMESPACE: &str = WRITE.namespace;
28
29/// One complete set of the names a signed attestation lives under: its header,
30/// the two notes refs, the SSH namespace, the two fingerprint domains and the
31/// payload's producer-line word. A note is read WHOLE under one set (SPEC.md,
32/// "Names"): its header says which, and the namespace, the domains and the
33/// inputs ref follow, so the two sets never mix inside one note.
34#[derive(Debug, Clone, Copy, PartialEq, Eq)]
35pub struct Names {
36    /// First line of every payload.
37    pub format: &'static str,
38    /// The notes ref, as `git notes --ref` wants it.
39    pub notes_ref: &'static str,
40    /// The fingerprint-keyed notes ref.
41    pub inputs_ref: &'static str,
42    /// The `ssh-keygen -Y` namespace.
43    pub namespace: &'static str,
44    /// Domain of the input-fingerprint lookup key.
45    pub input_domain: &'static str,
46    /// Domain of the canonical-tree lookup key.
47    pub canon_domain: &'static str,
48    /// The word that starts the producer line of a payload.
49    pub producer: &'static str,
50}
51
52/// The names notes were written under from 1.0 to 1.9. Still read during the
53/// 30-day window (ADR-0068); removed at the census (2.0.0).
54pub const LEGACY: Names = Names {
55    format: "amont-attest-v2",
56    notes_ref: "amont-attest",
57    inputs_ref: "amont-attest-inputs",
58    namespace: "amont-attest",
59    input_domain: "amont-attest-input",
60    canon_domain: "amont-attest-canon",
61    producer: "amont",
62};
63
64/// The names notes are signed under since 1.10.0. Verifiers read them first
65/// and fall back to [`LEGACY`] (SPEC.md, "Names").
66pub const GREEN: Names = Names {
67    format: "greengate-attest-v2",
68    notes_ref: "greengate-attest",
69    inputs_ref: "greengate-attest-inputs",
70    namespace: "greengate-attest",
71    input_domain: "greengate-attest-input",
72    canon_domain: "greengate-attest-canon",
73    producer: "greengate",
74};
75
76/// The ONE owner of what is written: [`FORMAT`], [`NOTES_REF`],
77/// [`INPUTS_REF`], [`NAMESPACE`], the producer word of [`payload`] and the
78/// set-less functions (`fingerprint::key`, `canon_key`, their preimages,
79/// `notes::sync_mirrors`) all derive from it. [`GREEN`] since 1.10.0 (LEGACY
80/// before), together with the name assignments at the top of `sign/sign.sh`,
81/// held equal to these by `tests/sign.sh`, which reads back what both
82/// signers write.
83pub const WRITE: Names = GREEN;
84
85/// How many blocks of one note are read. Every block costs two `ssh-keygen`
86/// runs, and the notes ref is writable by anyone with push access.
87pub const MAX_BLOCKS: usize = 32;
88
89pub(crate) const BEGIN: &str = "-----BEGIN SSH SIGNATURE-----";
90pub(crate) const END: &str = "-----END SSH SIGNATURE-----";
91
92/// Where a suite ran, as `<arch>-<os>`. Coarser than a target triple on
93/// purpose: the libc flavour is not something `std` can answer, and the
94/// question a CI matrix actually asks is "did this run on MY leg".
95pub fn platform() -> String {
96    format!("{}-{}", std::env::consts::ARCH, std::env::consts::OS)
97}
98
99/// The platform a signer principal is bound to: the text after its last `@`
100/// when that is `<arch>-<os>` over the closed sets below, else `None`. A
101/// principal that names no platform (`ci@relais`, an email address) is
102/// unbound, and so is one whose suffix has any other shape
103/// (`x@x86_64-linux-gnu`, `x@riscv64-linux`).
104pub fn bound_platform(principal: &str) -> Option<&str> {
105    const ARCHES: [&str; 2] = ["x86_64", "aarch64"];
106    const SYSTEMS: [&str; 3] = ["linux", "macos", "windows"];
107    let (_, suffix) = principal.rsplit_once('@')?;
108    let (arch, system) = suffix.split_once('-')?;
109    (ARCHES.contains(&arch) && SYSTEMS.contains(&system)).then_some(suffix)
110}
111
112/// One signed statement out of a note: the exact bytes that were signed
113/// (trailing newline included) and the armored signature over them.
114#[derive(Debug, PartialEq)]
115pub struct Block {
116    pub payload: String,
117    pub signature: String,
118}
119
120/// A note into its blocks. Since 1.2.0 a note may hold several — a laptop's
121/// and a CI job's, each on its own platform — separated by blank lines, which
122/// is exactly what `git notes append` produces.
123///
124/// The grammar (SPEC.md): skip blank lines; a payload runs to the first blank
125/// line; skip blank lines; the next line must be the BEGIN marker, or parsing
126/// STOPS and what was collected so far stands; the signature runs to the END
127/// marker, and end of input closes an open one. Lines are split on LF only;
128/// `evaluate` rejects any note containing a carriage return before this runs.
129///
130/// Returns the blocks and whether more than `MAX_BLOCKS` were present.
131pub fn split_blocks(body: &str) -> (Vec<Block>, bool) {
132    enum State {
133        Between,
134        Payload,
135        WaitingForSignature,
136        Signature,
137    }
138    let mut blocks = Vec::new();
139    let mut state = State::Between;
140    let mut payload = String::new();
141    let mut signature = String::new();
142    let close = |blocks: &mut Vec<Block>, payload: &str, signature: &str| -> bool {
143        if blocks.len() == MAX_BLOCKS {
144            return true;
145        }
146        blocks.push(Block {
147            payload: payload.to_string(),
148            signature: signature.to_string(),
149        });
150        false
151    };
152    for line in body.split('\n') {
153        match state {
154            State::Between => {
155                if line.is_empty() {
156                    continue;
157                }
158                payload.clear();
159                payload.push_str(line);
160                payload.push('\n');
161                state = State::Payload;
162            }
163            State::Payload => {
164                if line.is_empty() {
165                    state = State::WaitingForSignature;
166                } else {
167                    payload.push_str(line);
168                    payload.push('\n');
169                }
170            }
171            State::WaitingForSignature => {
172                if line.is_empty() {
173                    continue;
174                }
175                if line != BEGIN {
176                    return (blocks, false);
177                }
178                signature.clear();
179                signature.push_str(line);
180                signature.push('\n');
181                state = State::Signature;
182            }
183            State::Signature => {
184                signature.push_str(line);
185                signature.push('\n');
186                if line == END {
187                    if close(&mut blocks, &payload, &signature) {
188                        return (blocks, true);
189                    }
190                    state = State::Between;
191                }
192            }
193        }
194    }
195    if let State::Signature = state {
196        if close(&mut blocks, &payload, &signature) {
197            return (blocks, true);
198        }
199    }
200    (blocks, false)
201}
202
203/// The first block of a note, as payload and signature.
204pub fn split_note(body: &str) -> Option<(String, String)> {
205    split_blocks(body)
206        .0
207        .into_iter()
208        .next()
209        .map(|b| (b.payload, b.signature))
210}
211
212/// Does an attestation minted on `ran_on` satisfy what the caller asked for?
213///
214/// `None` is "anywhere". A value with a dash is an exact `<arch>-<os>`. A value
215/// without one is an OS alone, compared to the part after the LAST dash of
216/// `ran_on` — never as a substring, so `inux` matches nothing and `x86_64`
217/// does not match `x86_64-linux`.
218pub fn platform_matches(want: Option<&str>, ran_on: &str) -> bool {
219    match want {
220        None => true,
221        Some(want) if want.contains('-') => want == ran_on,
222        Some(want) => ran_on.rsplit_once('-').is_some_and(|(_, os)| os == want),
223    }
224}
225
226/// Read a payload field BY PREFIX, never by line position: the payload has
227/// grown a line once already (v1 -> v2 added `platform`), and a positional
228/// reader silently mis-assigns every field after an insertion rather than
229/// failing. First match wins, so a second `gates` line cannot smuggle a value
230/// past the caller.
231///
232/// Byte-strict, like `verify.sh`: lines are split on LF only and nothing is
233/// trimmed but the separating spaces, so a `\r` or a trailing space is part
234/// of the value and a `tree` line that carries one matches nothing.
235pub fn field<'a>(payload: &'a str, name: &str) -> Option<&'a str> {
236    payload
237        .split('\n')
238        .find_map(|l| l.strip_prefix(name).and_then(|r| r.strip_prefix(' ')))
239        .map(|v| v.trim_start_matches(' '))
240}
241
242/// A 40- or 64-hex object id, as `hash-object` prints one.
243pub fn is_oid(s: &str) -> bool {
244    (s.len() == 40 || s.len() == 64)
245        && s.bytes()
246            .all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase())
247}
248
249/// The fingerprint a block claims for `gate`: an `input <gate> <fp>` line of
250/// exactly three blank-separated fields, first occurrence wins. Byte-strict
251/// like [`field`]; a fourth field or a malformed oid is not a claim.
252pub fn input_fp<'a>(payload: &'a str, gate: &str) -> Option<&'a str> {
253    payload.split('\n').find_map(|line| {
254        let f: Vec<&str> = line.split([' ', '\t']).filter(|t| !t.is_empty()).collect();
255        (f.len() == 3 && f[0] == "input" && f[1] == gate && is_oid(f[2])).then(|| f[2])
256    })
257}
258
259/// The canonical fingerprint a block claims: a `canon <oid>` line of exactly
260/// two blank-separated fields, first occurrence wins. A malformed oid is not
261/// a claim.
262pub fn canon_claim(payload: &str) -> Option<&str> {
263    payload.split('\n').find_map(|line| {
264        let f: Vec<&str> = line.split([' ', '\t']).filter(|t| !t.is_empty()).collect();
265        (f.len() == 2 && f[0] == "canon" && is_oid(f[1])).then(|| f[1])
266    })
267}
268
269/// The payload of an attestation, in the exact shape SPEC.md gives: `tree`,
270/// `gates`, `platform`, the `input` lines in spec order, `canon`, then the
271/// producer line, each followed by LF. The same inputs give the same bytes,
272/// so a re-run recognises its own block.
273pub fn payload(
274    tree: &str,
275    gates: &str,
276    platform: &str,
277    inputs: &[(String, String)],
278    canon: Option<&str>,
279    producer: &str,
280) -> String {
281    let mut out = format!("{FORMAT}\ntree {tree}\ngates {gates}\nplatform {platform}\n");
282    for (gate, fp) in inputs {
283        out.push_str(&format!("input {gate} {fp}\n"));
284    }
285    if let Some(c) = canon {
286        out.push_str(&format!("canon {c}\n"));
287    }
288    out.push_str(&format!("{} {producer}\n", WRITE.producer));
289    out
290}
291
292/// A signed block as a note holds it: the payload without its trailing
293/// newline, a blank line, the armored signature without its own.
294pub fn block(payload: &str, signature: &str) -> String {
295    format!(
296        "{}\n\n{}",
297        payload.trim_end_matches('\n'),
298        signature.trim_end_matches('\n')
299    )
300}