Skip to main content

hide_transparency/
checkpoint.rs

1//! Signed checkpoints in the C2SP `tlog-checkpoint` / `signed-note` text form.
2//!
3//! The 40-byte checkpoint of §12 says nothing about who published it. This
4//! wraps the same size and root in the note format Go's sumdb, Sigstore and
5//! the public witness network already parse, signed with HIDE-Sign under the
6//! signed-note "0xff" (unassigned type) convention. Witnesses cosign by adding
7//! their own signature line over the same text; a verifier that demands a
8//! threshold of witnesses turns a split view into a detectable event, because
9//! an honest witness never signs two roots for one size.
10//!
11//! Spec §16.2 is normative for every byte here.
12
13use base64::{Engine as _, engine::general_purpose::STANDARD};
14use hide_sign::{SIGNATURE_LENGTH, SigningIdentity, VerifyingIdentity};
15use sha2::{Digest, Sha256};
16
17use crate::{Hash, LogError};
18
19/// Signature context for a checkpoint note, log or witness alike.
20pub const CHECKPOINT_CONTEXT: &[u8] = b"HIDE/1.0 checkpoint";
21
22/// Distinguishes a HIDE-Sign key in the signed-note key id: `0xff` is the
23/// signed-note escape for types without an assigned byte, followed by a
24/// longer identifier as that specification recommends.
25const SIGNATURE_TYPE: &[u8] = b"\xffHIDE/1.0 hide-sign";
26
27/// Origins are ASCII without spaces or '+', so a key name can equal the origin
28/// and no Unicode lookalike can name the same log twice.
29pub const MAX_ORIGIN_BYTES: usize = 256;
30/// Signed-note verifiers must accept at least 16 signatures.
31const MAX_SIGNATURES: usize = 32;
32/// 32 HIDE-Sign lines are about 150 KB; anything larger is refused unread.
33pub const MAX_NOTE_BYTES: usize = 196_608;
34
35const DASH: &str = "\u{2014} ";
36
37/// One signature line: who, which key, and the raw signature bytes.
38#[derive(Debug, Clone, PartialEq, Eq)]
39pub struct NoteSignature {
40    pub name: String,
41    pub key_id: [u8; 4],
42    pub signature: Vec<u8>,
43}
44
45/// A parsed note: the signed text and every signature line, known or not.
46#[derive(Debug, Clone, PartialEq, Eq)]
47pub struct SignedNote {
48    pub text: String,
49    pub signatures: Vec<NoteSignature>,
50}
51
52/// `SHA-256(name || 0x0A || 0xFF || "HIDE/1.0 hide-sign" || verifying_key)[:4]`.
53pub fn key_id(name: &str, key: &VerifyingIdentity) -> [u8; 4] {
54    let mut hasher = Sha256::new();
55    hasher.update(name.as_bytes());
56    hasher.update([0x0a]);
57    hasher.update(SIGNATURE_TYPE);
58    hasher.update(key.to_bytes());
59    let digest = hasher.finalize();
60    [digest[0], digest[1], digest[2], digest[3]]
61}
62
63pub(crate) fn valid_name(name: &str) -> bool {
64    !name.is_empty()
65        && name.len() <= MAX_ORIGIN_BYTES
66        && name
67            .bytes()
68            .all(|b| (0x21..=0x7e).contains(&b) && b != b'+')
69}
70
71impl SignedNote {
72    pub fn encode(&self) -> String {
73        let mut out = String::with_capacity(self.text.len() + 4600 * self.signatures.len());
74        out.push_str(&self.text);
75        out.push('\n');
76        for signature in &self.signatures {
77            let mut raw = Vec::with_capacity(4 + signature.signature.len());
78            raw.extend_from_slice(&signature.key_id);
79            raw.extend_from_slice(&signature.signature);
80            out.push_str(DASH);
81            out.push_str(&signature.name);
82            out.push(' ');
83            out.push_str(&STANDARD.encode(raw));
84            out.push('\n');
85        }
86        out
87    }
88
89    /// Parses the note structure. Signatures are not verified here.
90    pub fn decode(bytes: &[u8]) -> Result<Self, LogError> {
91        if bytes.len() > MAX_NOTE_BYTES {
92            return Err(LogError::Malformed);
93        }
94        let note = std::str::from_utf8(bytes).map_err(|_| LogError::Malformed)?;
95        if note.chars().any(|c| c.is_control() && c != '\n') || !note.ends_with('\n') {
96            return Err(LogError::Malformed);
97        }
98        // The text ends at the LAST blank line; it keeps its final newline.
99        let split = note.rfind("\n\n").ok_or(LogError::Malformed)?;
100        let text = &note[..=split];
101        let block = &note[split + 2..];
102        let mut signatures = Vec::new();
103        for line in block.split_terminator('\n') {
104            if signatures.len() == MAX_SIGNATURES {
105                return Err(LogError::Malformed);
106            }
107            let rest = line.strip_prefix(DASH).ok_or(LogError::Malformed)?;
108            let (name, encoded) = rest.split_once(' ').ok_or(LogError::Malformed)?;
109            if !valid_name(name) {
110                return Err(LogError::Malformed);
111            }
112            let raw = STANDARD.decode(encoded).map_err(|_| LogError::Malformed)?;
113            if raw.len() < 5 {
114                return Err(LogError::Malformed);
115            }
116            signatures.push(NoteSignature {
117                name: name.to_owned(),
118                key_id: [raw[0], raw[1], raw[2], raw[3]],
119                signature: raw[4..].to_vec(),
120            });
121        }
122        if signatures.is_empty() {
123            return Err(LogError::Malformed);
124        }
125        let parsed = Self {
126            text: text.to_owned(),
127            signatures,
128        };
129        // One note, one encoding: base64 padding, stray spaces and the like
130        // all fail here rather than being silently normalised.
131        if parsed.encode().as_bytes() != bytes {
132            return Err(LogError::Malformed);
133        }
134        Ok(parsed)
135    }
136
137    /// Whether `key`, named `name`, signed this note. Unknown keys (name or id
138    /// differing) are skipped, as signed-note requires; a matching line whose
139    /// signature fails is an error, never a skip.
140    fn signed_by(&self, name: &str, key: &VerifyingIdentity) -> Result<bool, LogError> {
141        let id = key_id(name, key);
142        let mut found = false;
143        for line in self
144            .signatures
145            .iter()
146            .filter(|s| s.name == name && s.key_id == id)
147        {
148            if line.signature.len() != SIGNATURE_LENGTH
149                || key
150                    .verify(CHECKPOINT_CONTEXT, self.text.as_bytes(), &line.signature)
151                    .is_err()
152            {
153                return Err(LogError::BadSignature);
154            }
155            found = true;
156        }
157        Ok(found)
158    }
159}
160
161/// The tree head a log publishes: origin, size and root.
162#[derive(Debug, Clone, PartialEq, Eq)]
163pub struct Checkpoint {
164    pub origin: String,
165    pub size: u64,
166    pub root: Hash,
167}
168
169impl Checkpoint {
170    /// The note text: exactly three lines, no extension lines.
171    pub fn text(&self) -> Result<String, LogError> {
172        if !valid_name(&self.origin) {
173            return Err(LogError::Malformed);
174        }
175        Ok(format!(
176            "{}\n{}\n{}\n",
177            self.origin,
178            self.size,
179            STANDARD.encode(self.root)
180        ))
181    }
182
183    fn parse_text(text: &str) -> Result<Self, LogError> {
184        let lines: Vec<&str> = text.split_terminator('\n').collect();
185        let [origin, size, root] = lines.as_slice() else {
186            return Err(LogError::Malformed);
187        };
188        if !valid_name(origin) {
189            return Err(LogError::Malformed);
190        }
191        let size: u64 = size.parse().map_err(|_| LogError::Malformed)?;
192        let root: Hash = STANDARD
193            .decode(root)
194            .map_err(|_| LogError::Malformed)?
195            .try_into()
196            .map_err(|_| LogError::Malformed)?;
197        let checkpoint = Self {
198            origin: (*origin).to_owned(),
199            size,
200            root,
201        };
202        // Rejects "+5", "05", and anything else `parse` tolerates.
203        if checkpoint.text()? != text {
204            return Err(LogError::Malformed);
205        }
206        Ok(checkpoint)
207    }
208
209    /// Signs as the log. The key name is the origin.
210    pub fn sign(&self, log: &SigningIdentity) -> Result<SignedNote, LogError> {
211        let text = self.text()?;
212        Ok(SignedNote {
213            signatures: vec![NoteSignature {
214                name: self.origin.clone(),
215                key_id: key_id(&self.origin, &log.verifying_key()),
216                signature: log.sign(CHECKPOINT_CONTEXT, text.as_bytes()).to_vec(),
217            }],
218            text,
219        })
220    }
221
222    /// Adds a witness cosignature to a note that already carries the log's.
223    pub fn cosign(
224        note: &mut SignedNote,
225        name: &str,
226        witness: &SigningIdentity,
227    ) -> Result<(), LogError> {
228        if !valid_name(name) || note.signatures.len() >= MAX_SIGNATURES {
229            return Err(LogError::Malformed);
230        }
231        note.signatures.push(NoteSignature {
232            name: name.to_owned(),
233            key_id: key_id(name, &witness.verifying_key()),
234            signature: witness
235                .sign(CHECKPOINT_CONTEXT, note.text.as_bytes())
236                .to_vec(),
237        });
238        Ok(())
239    }
240
241    /// Parses and verifies a note from the log at `origin` signed by `log`.
242    pub fn verify(note: &[u8], origin: &str, log: &VerifyingIdentity) -> Result<Self, LogError> {
243        Self::verify_witnessed(note, origin, log, &[], 0)
244    }
245
246    /// As [`Self::verify`], and additionally requires at least `threshold`
247    /// distinct witnesses from `witnesses` to have cosigned.
248    pub fn verify_witnessed(
249        note: &[u8],
250        origin: &str,
251        log: &VerifyingIdentity,
252        witnesses: &[(&str, &VerifyingIdentity)],
253        threshold: usize,
254    ) -> Result<Self, LogError> {
255        let parsed = SignedNote::decode(note)?;
256        let checkpoint = Self::parse_text(&parsed.text)?;
257        if checkpoint.origin != origin {
258            return Err(LogError::WrongOrigin {
259                found: checkpoint.origin,
260            });
261        }
262        if !parsed.signed_by(origin, log)? {
263            return Err(LogError::Unsigned);
264        }
265        // A witness listed twice (or the log listed as its own witness) must
266        // not count twice toward the threshold.
267        let mut counted: Vec<(&str, [u8; 4])> = vec![(origin, key_id(origin, log))];
268        let mut cosigned = 0;
269        for (name, key) in witnesses {
270            let id = key_id(name, key);
271            if counted.iter().any(|(n, k)| n == name || *k == id) {
272                continue;
273            }
274            if parsed.signed_by(name, key)? {
275                cosigned += 1;
276                counted.push((name, id));
277            }
278        }
279        if cosigned < threshold {
280            return Err(LogError::Unsigned);
281        }
282        Ok(checkpoint)
283    }
284}