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. A verifier that does not recognise this
5/// string must treat the note as absent: an unknown version may mean anything,
6/// and "run the tests" is the only safe reading of anything.
7pub const FORMAT: &str = "amont-attest-v2";
8
9/// The notes ref, as `git notes --ref` wants it.
10pub const NOTES_REF: &str = "amont-attest";
11
12/// The second notes ref, keyed by input fingerprint rather than by object.
13/// Every key there is a synthetic oid that is not an object, which is why it
14/// is a separate ref: `git notes prune` on it would drop everything, and the
15/// main ref keeps its 1.x invariant that every key is real.
16pub const INPUTS_REF: &str = "amont-attest-inputs";
17
18/// Where `sign.sh --no-push` keeps blocks that never reached origin, under
19/// `refs/notes/`, prefixed to either ref name above. Origin cannot revoke
20/// them, so a verifier reads them only when asked (`--include-local`).
21pub const LOCAL_PREFIX: &str = "attest-local/";
22
23/// The `ssh-keygen -Y` namespace. Namespaces exist so a signature minted for
24/// one purpose cannot be replayed for another; an `allowed_signers` entry
25/// pinned to this namespace accepts nothing else.
26pub const NAMESPACE: &str = "amont-attest";
27
28/// How many blocks of one note are read. Every block costs two `ssh-keygen`
29/// runs, and the notes ref is writable by anyone with push access.
30pub const MAX_BLOCKS: usize = 32;
31
32pub(crate) const BEGIN: &str = "-----BEGIN SSH SIGNATURE-----";
33pub(crate) const END: &str = "-----END SSH SIGNATURE-----";
34
35/// Where a suite ran, as `<arch>-<os>`. Coarser than a target triple on
36/// purpose: the libc flavour is not something `std` can answer, and the
37/// question a CI matrix actually asks is "did this run on MY leg".
38pub fn platform() -> String {
39 format!("{}-{}", std::env::consts::ARCH, std::env::consts::OS)
40}
41
42/// One signed statement out of a note: the exact bytes that were signed
43/// (trailing newline included) and the armored signature over them.
44#[derive(Debug, PartialEq)]
45pub struct Block {
46 pub payload: String,
47 pub signature: String,
48}
49
50/// A note into its blocks. Since 1.2.0 a note may hold several — a laptop's
51/// and a CI job's, each on its own platform — separated by blank lines, which
52/// is exactly what `git notes append` produces.
53///
54/// The grammar (SPEC.md): skip blank lines; a payload runs to the first blank
55/// line; skip blank lines; the next line must be the BEGIN marker, or parsing
56/// STOPS and what was collected so far stands; the signature runs to the END
57/// marker, and end of input closes an open one. Lines are split on LF only;
58/// `evaluate` rejects any note containing a carriage return before this runs.
59///
60/// Returns the blocks and whether more than `MAX_BLOCKS` were present.
61pub fn split_blocks(body: &str) -> (Vec<Block>, bool) {
62 enum State {
63 Between,
64 Payload,
65 WaitingForSignature,
66 Signature,
67 }
68 let mut blocks = Vec::new();
69 let mut state = State::Between;
70 let mut payload = String::new();
71 let mut signature = String::new();
72 let close = |blocks: &mut Vec<Block>, payload: &str, signature: &str| -> bool {
73 if blocks.len() == MAX_BLOCKS {
74 return true;
75 }
76 blocks.push(Block {
77 payload: payload.to_string(),
78 signature: signature.to_string(),
79 });
80 false
81 };
82 for line in body.split('\n') {
83 match state {
84 State::Between => {
85 if line.is_empty() {
86 continue;
87 }
88 payload.clear();
89 payload.push_str(line);
90 payload.push('\n');
91 state = State::Payload;
92 }
93 State::Payload => {
94 if line.is_empty() {
95 state = State::WaitingForSignature;
96 } else {
97 payload.push_str(line);
98 payload.push('\n');
99 }
100 }
101 State::WaitingForSignature => {
102 if line.is_empty() {
103 continue;
104 }
105 if line != BEGIN {
106 return (blocks, false);
107 }
108 signature.clear();
109 signature.push_str(line);
110 signature.push('\n');
111 state = State::Signature;
112 }
113 State::Signature => {
114 signature.push_str(line);
115 signature.push('\n');
116 if line == END {
117 if close(&mut blocks, &payload, &signature) {
118 return (blocks, true);
119 }
120 state = State::Between;
121 }
122 }
123 }
124 }
125 if let State::Signature = state {
126 if close(&mut blocks, &payload, &signature) {
127 return (blocks, true);
128 }
129 }
130 (blocks, false)
131}
132
133/// The first block of a note, as payload and signature.
134pub fn split_note(body: &str) -> Option<(String, String)> {
135 split_blocks(body)
136 .0
137 .into_iter()
138 .next()
139 .map(|b| (b.payload, b.signature))
140}
141
142/// Does an attestation minted on `ran_on` satisfy what the caller asked for?
143///
144/// `None` is "anywhere". A value with a dash is an exact `<arch>-<os>`. A value
145/// without one is an OS alone, compared to the part after the LAST dash of
146/// `ran_on` — never as a substring, so `inux` matches nothing and `x86_64`
147/// does not match `x86_64-linux`.
148pub fn platform_matches(want: Option<&str>, ran_on: &str) -> bool {
149 match want {
150 None => true,
151 Some(want) if want.contains('-') => want == ran_on,
152 Some(want) => ran_on.rsplit_once('-').is_some_and(|(_, os)| os == want),
153 }
154}
155
156/// Read a payload field BY PREFIX, never by line position: the payload has
157/// grown a line once already (v1 -> v2 added `platform`), and a positional
158/// reader silently mis-assigns every field after an insertion rather than
159/// failing. First match wins, so a second `gates` line cannot smuggle a value
160/// past the caller.
161///
162/// Byte-strict, like `verify.sh`: lines are split on LF only and nothing is
163/// trimmed but the separating spaces, so a `\r` or a trailing space is part
164/// of the value and a `tree` line that carries one matches nothing.
165pub fn field<'a>(payload: &'a str, name: &str) -> Option<&'a str> {
166 payload
167 .split('\n')
168 .find_map(|l| l.strip_prefix(name).and_then(|r| r.strip_prefix(' ')))
169 .map(|v| v.trim_start_matches(' '))
170}
171
172/// A 40- or 64-hex object id, as `hash-object` prints one.
173pub fn is_oid(s: &str) -> bool {
174 (s.len() == 40 || s.len() == 64)
175 && s.bytes()
176 .all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase())
177}
178
179/// The fingerprint a block claims for `gate`: an `input <gate> <fp>` line of
180/// exactly three blank-separated fields, first occurrence wins. Byte-strict
181/// like [`field`]; a fourth field or a malformed oid is not a claim.
182pub fn input_fp<'a>(payload: &'a str, gate: &str) -> Option<&'a str> {
183 payload.split('\n').find_map(|line| {
184 let f: Vec<&str> = line.split([' ', '\t']).filter(|t| !t.is_empty()).collect();
185 (f.len() == 3 && f[0] == "input" && f[1] == gate && is_oid(f[2])).then(|| f[2])
186 })
187}
188
189/// The canonical fingerprint a block claims: a `canon <oid>` line of exactly
190/// two blank-separated fields, first occurrence wins. A malformed oid is not
191/// a claim.
192pub fn canon_claim(payload: &str) -> Option<&str> {
193 payload.split('\n').find_map(|line| {
194 let f: Vec<&str> = line.split([' ', '\t']).filter(|t| !t.is_empty()).collect();
195 (f.len() == 2 && f[0] == "canon" && is_oid(f[1])).then(|| f[1])
196 })
197}
198
199/// The payload of an attestation, in the exact shape SPEC.md gives: `tree`,
200/// `gates`, `platform`, the `input` lines in spec order, `canon`, then the
201/// producer line, each followed by LF. The same inputs give the same bytes,
202/// so a re-run recognises its own block.
203pub fn payload(
204 tree: &str,
205 gates: &str,
206 platform: &str,
207 inputs: &[(String, String)],
208 canon: Option<&str>,
209 producer: &str,
210) -> String {
211 let mut out = format!("{FORMAT}\ntree {tree}\ngates {gates}\nplatform {platform}\n");
212 for (gate, fp) in inputs {
213 out.push_str(&format!("input {gate} {fp}\n"));
214 }
215 if let Some(c) = canon {
216 out.push_str(&format!("canon {c}\n"));
217 }
218 out.push_str(&format!("amont {producer}\n"));
219 out
220}
221
222/// A signed block as a note holds it: the payload without its trailing
223/// newline, a blank line, the armored signature without its own.
224pub fn block(payload: &str, signature: &str) -> String {
225 format!(
226 "{}\n\n{}",
227 payload.trim_end_matches('\n'),
228 signature.trim_end_matches('\n')
229 )
230}