Skip to main content

adk_auth/signed_audit/
note.rs

1//! C2SP signed notes and tlog checkpoints, compatible with Go's
2//! `golang.org/x/mod/sumdb/note` package.
3//!
4//! A note is text, a blank line, and one signature line per signer:
5//!
6//! ```text
7//! <origin>
8//! <tree size>
9//! <base64 root hash>
10//!
11//! — <key name> <base64(4-byte key hash ‖ signature)>
12//! ```
13//!
14//! Verifier keys use the note format `<name>+<hex key hash>+<base64(0x01 ‖ public key)>`;
15//! signer keys add a `PRIVATE+KEY+` prefix and carry the Ed25519 seed instead.
16
17use std::fmt;
18use std::sync::Arc;
19
20use adk_core::audit_log::AuditHash;
21use async_trait::async_trait;
22use aws_lc_rs::signature::{self, Ed25519KeyPair, KeyPair, UnparsedPublicKey};
23use base64::Engine;
24use base64::engine::general_purpose::STANDARD as BASE64;
25use sha2::{Digest, Sha256};
26use zeroize::Zeroizing;
27
28/// Algorithm byte for Ed25519 in note keys.
29const ALG_ED25519: u8 = 0x01;
30const SIGNATURE_PREFIX: &str = "\u{2014} ";
31
32/// A signature algorithm usable for checkpoints.
33#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
34#[non_exhaustive]
35pub enum SignatureAlgorithm {
36    /// Ed25519 (RFC 8032).
37    Ed25519,
38}
39
40impl SignatureAlgorithm {
41    fn id(self) -> u8 {
42        match self {
43            Self::Ed25519 => ALG_ED25519,
44        }
45    }
46}
47
48/// Errors from signing, parsing, or opening notes and keys.
49#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
50#[non_exhaustive]
51pub enum NoteError {
52    /// A key string is malformed.
53    #[error("invalid note key: {0}")]
54    InvalidKey(String),
55    /// A note or checkpoint is malformed.
56    #[error("malformed note: {0}")]
57    Malformed(String),
58    /// A signer failed to sign.
59    #[error("signing failed: {0}")]
60    Signing(String),
61}
62
63/// Signs checkpoints. Implement it over a KMS or HSM to keep the private key out of
64/// the process; [`Ed25519Signer`] holds the key in memory.
65#[async_trait]
66pub trait AuditSigner: Send + Sync {
67    /// The key name that appears in signature lines and verifier keys.
68    fn key_name(&self) -> &str;
69
70    /// The signature algorithm.
71    fn algorithm(&self) -> SignatureAlgorithm;
72
73    /// The raw public key.
74    fn public_key(&self) -> &[u8];
75
76    /// Signs `message`.
77    ///
78    /// # Errors
79    ///
80    /// [`NoteError::Signing`] when the key cannot sign.
81    async fn sign(&self, message: &[u8]) -> Result<Vec<u8>, NoteError>;
82
83    /// The note verifier key string for this signer.
84    fn verifier_key(&self) -> String {
85        NoteVerifier::from_public_key(self.key_name(), self.algorithm(), self.public_key())
86            .map(|verifier| verifier.to_string())
87            .unwrap_or_default()
88    }
89}
90
91fn valid_name(name: &str) -> bool {
92    !name.is_empty() && !name.contains('+') && !name.chars().any(char::is_whitespace)
93}
94
95fn key_hash(name: &str, key: &[u8]) -> u32 {
96    let mut hasher = Sha256::new();
97    hasher.update(name.as_bytes());
98    hasher.update(b"\n");
99    hasher.update(key);
100    let digest = hasher.finalize();
101    u32::from_be_bytes([digest[0], digest[1], digest[2], digest[3]])
102}
103
104/// An Ed25519 [`AuditSigner`] holding its seed in memory (zeroized on drop).
105///
106/// # Example
107///
108/// ```rust
109/// use adk_auth::signed_audit::{AuditSigner, Ed25519Signer, NoteVerifier};
110///
111/// let signer = Ed25519Signer::generate("audit.example.com").unwrap();
112/// let verifier: NoteVerifier = signer.verifier_key().parse().unwrap();
113/// assert_eq!(verifier.name(), "audit.example.com");
114/// ```
115pub struct Ed25519Signer {
116    name: String,
117    seed: Zeroizing<[u8; 32]>,
118    key_pair: Ed25519KeyPair,
119    public_key: [u8; 32],
120}
121
122impl fmt::Debug for Ed25519Signer {
123    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
124        f.debug_struct("Ed25519Signer").field("name", &self.name).finish_non_exhaustive()
125    }
126}
127
128impl Ed25519Signer {
129    /// Creates a signer from a 32-byte seed.
130    ///
131    /// # Errors
132    ///
133    /// [`NoteError::InvalidKey`] when `name` is empty or contains `+` or whitespace.
134    pub fn from_seed(name: impl Into<String>, seed: [u8; 32]) -> Result<Self, NoteError> {
135        let name = name.into();
136        if !valid_name(&name) {
137            return Err(NoteError::InvalidKey(format!(
138                "key name '{name}' must be non-empty without '+' or whitespace"
139            )));
140        }
141        let key_pair = Ed25519KeyPair::from_seed_unchecked(&seed)
142            .map_err(|e| NoteError::InvalidKey(format!("ed25519 seed rejected: {e}")))?;
143        let public_key: [u8; 32] = key_pair
144            .public_key()
145            .as_ref()
146            .try_into()
147            .map_err(|_| NoteError::InvalidKey("ed25519 public key is not 32 bytes".into()))?;
148        Ok(Self { name, seed: Zeroizing::new(seed), key_pair, public_key })
149    }
150
151    /// Generates a new random key.
152    ///
153    /// # Errors
154    ///
155    /// As [`from_seed`](Self::from_seed), or when the system RNG fails.
156    pub fn generate(name: impl Into<String>) -> Result<Self, NoteError> {
157        let mut seed = Zeroizing::new([0u8; 32]);
158        aws_lc_rs::rand::fill(seed.as_mut())
159            .map_err(|_| NoteError::InvalidKey("system random number generator failed".into()))?;
160        Self::from_seed(name, *seed)
161    }
162
163    /// Parses a note signer key, `PRIVATE+KEY+<name>+<hash>+<base64(0x01 ‖ seed)>`, as
164    /// produced by Go's `note.GenerateKey`.
165    ///
166    /// # Errors
167    ///
168    /// [`NoteError::InvalidKey`] when the key is malformed or its hash does not match.
169    pub fn from_note_key(key: &str) -> Result<Self, NoteError> {
170        let rest = key.strip_prefix("PRIVATE+KEY+").ok_or_else(|| {
171            NoteError::InvalidKey("signer key must start with PRIVATE+KEY+".into())
172        })?;
173        let (name, hash, encoded) = split_key(rest)?;
174        let decoded = Zeroizing::new(
175            BASE64
176                .decode(encoded)
177                .map_err(|e| NoteError::InvalidKey(format!("bad base64: {e}")))?,
178        );
179        let (&alg, seed) = decoded
180            .split_first()
181            .ok_or_else(|| NoteError::InvalidKey("signer key is empty".into()))?;
182        if alg != ALG_ED25519 {
183            return Err(NoteError::InvalidKey(format!("unsupported algorithm {alg}")));
184        }
185        let seed: [u8; 32] = seed
186            .try_into()
187            .map_err(|_| NoteError::InvalidKey("ed25519 seed is not 32 bytes".into()))?;
188        let signer = Self::from_seed(name, seed)?;
189        let verifier =
190            NoteVerifier::from_public_key(name, SignatureAlgorithm::Ed25519, &signer.public_key)?;
191        if verifier.key_hash != hash {
192            return Err(NoteError::InvalidKey("key hash does not match the key".into()));
193        }
194        Ok(signer)
195    }
196
197    /// Returns the note signer key string. Treat it as a secret.
198    pub fn to_note_key(&self) -> Zeroizing<String> {
199        let mut encoded = Zeroizing::new(Vec::with_capacity(33));
200        encoded.push(ALG_ED25519);
201        encoded.extend_from_slice(self.seed.as_ref());
202        let mut public = vec![ALG_ED25519];
203        public.extend_from_slice(&self.public_key);
204        Zeroizing::new(format!(
205            "PRIVATE+KEY+{}+{:08x}+{}",
206            self.name,
207            key_hash(&self.name, &public),
208            BASE64.encode(encoded.as_slice())
209        ))
210    }
211}
212
213#[async_trait]
214impl AuditSigner for Ed25519Signer {
215    fn key_name(&self) -> &str {
216        &self.name
217    }
218
219    fn algorithm(&self) -> SignatureAlgorithm {
220        SignatureAlgorithm::Ed25519
221    }
222
223    fn public_key(&self) -> &[u8] {
224        &self.public_key
225    }
226
227    async fn sign(&self, message: &[u8]) -> Result<Vec<u8>, NoteError> {
228        Ok(self.key_pair.sign(message).as_ref().to_vec())
229    }
230}
231
232fn split_key(text: &str) -> Result<(&str, u32, &str), NoteError> {
233    let mut parts = text.splitn(3, '+');
234    let (Some(name), Some(hash), Some(encoded)) = (parts.next(), parts.next(), parts.next()) else {
235        return Err(NoteError::InvalidKey("expected <name>+<hash>+<key>".into()));
236    };
237    if !valid_name(name) {
238        return Err(NoteError::InvalidKey(format!("invalid key name '{name}'")));
239    }
240    if hash.len() != 8 {
241        return Err(NoteError::InvalidKey("key hash must be 8 hex digits".into()));
242    }
243    let hash = u32::from_str_radix(hash, 16)
244        .map_err(|_| NoteError::InvalidKey("key hash must be 8 hex digits".into()))?;
245    Ok((name, hash, encoded))
246}
247
248/// A public key that verifies note signatures, parsed from a verifier key string.
249///
250/// # Example
251///
252/// ```rust
253/// use adk_auth::signed_audit::NoteVerifier;
254///
255/// let verifier: NoteVerifier =
256///     "PeterNeumann+c74f20a3+ARpc2QcUPDhMQegwxbzhKqiBfsVkmqq/LDE4izWy10TW".parse().unwrap();
257/// assert_eq!(verifier.key_hash(), 0xc74f20a3);
258/// ```
259#[derive(Debug, Clone, PartialEq, Eq, Hash)]
260pub struct NoteVerifier {
261    name: String,
262    key_hash: u32,
263    algorithm: SignatureAlgorithm,
264    public_key: Vec<u8>,
265}
266
267impl NoteVerifier {
268    /// Builds a verifier from a raw public key.
269    ///
270    /// # Errors
271    ///
272    /// [`NoteError::InvalidKey`] when the name is invalid or the key has the wrong length.
273    pub fn from_public_key(
274        name: &str,
275        algorithm: SignatureAlgorithm,
276        public_key: &[u8],
277    ) -> Result<Self, NoteError> {
278        if !valid_name(name) {
279            return Err(NoteError::InvalidKey(format!("invalid key name '{name}'")));
280        }
281        if public_key.len() != 32 {
282            return Err(NoteError::InvalidKey("ed25519 public key must be 32 bytes".into()));
283        }
284        let mut encoded = vec![algorithm.id()];
285        encoded.extend_from_slice(public_key);
286        Ok(Self {
287            name: name.to_string(),
288            key_hash: key_hash(name, &encoded),
289            algorithm,
290            public_key: public_key.to_vec(),
291        })
292    }
293
294    /// The key name.
295    pub fn name(&self) -> &str {
296        &self.name
297    }
298
299    /// The 32-bit key hash that identifies the key in signature lines.
300    pub fn key_hash(&self) -> u32 {
301        self.key_hash
302    }
303
304    /// Checks `signature` over `message`.
305    pub fn verify(&self, message: &[u8], signature_bytes: &[u8]) -> bool {
306        match self.algorithm {
307            SignatureAlgorithm::Ed25519 => {
308                UnparsedPublicKey::new(&signature::ED25519, &self.public_key)
309                    .verify(message, signature_bytes)
310                    .is_ok()
311            }
312        }
313    }
314}
315
316impl std::str::FromStr for NoteVerifier {
317    type Err = NoteError;
318
319    fn from_str(text: &str) -> Result<Self, Self::Err> {
320        let (name, hash, encoded) = split_key(text.trim())?;
321        let decoded = BASE64
322            .decode(encoded)
323            .map_err(|e| NoteError::InvalidKey(format!("bad base64: {e}")))?;
324        let (&alg, key) = decoded
325            .split_first()
326            .ok_or_else(|| NoteError::InvalidKey("verifier key is empty".into()))?;
327        if alg != ALG_ED25519 {
328            return Err(NoteError::InvalidKey(format!("unsupported algorithm {alg}")));
329        }
330        let verifier = Self::from_public_key(name, SignatureAlgorithm::Ed25519, key)?;
331        if verifier.key_hash != hash {
332            return Err(NoteError::InvalidKey("key hash does not match the key".into()));
333        }
334        Ok(verifier)
335    }
336}
337
338impl fmt::Display for NoteVerifier {
339    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
340        let mut encoded = vec![self.algorithm.id()];
341        encoded.extend_from_slice(&self.public_key);
342        write!(f, "{}+{:08x}+{}", self.name, self.key_hash, BASE64.encode(encoded))
343    }
344}
345
346/// One signature line of a note.
347#[derive(Debug, Clone, PartialEq, Eq)]
348pub struct NoteSignature {
349    /// The key name.
350    pub name: String,
351    /// The key hash.
352    pub key_hash: u32,
353    /// The signature bytes, without the key hash.
354    pub signature: Vec<u8>,
355}
356
357/// A parsed note: its signed text and its signature lines.
358#[derive(Debug, Clone, PartialEq, Eq)]
359pub struct Note {
360    /// The signed text, ending in a newline.
361    pub text: String,
362    /// Every signature line, verified or not.
363    pub signatures: Vec<NoteSignature>,
364}
365
366impl Note {
367    /// Parses a signed note without verifying it.
368    ///
369    /// # Errors
370    ///
371    /// [`NoteError::Malformed`] when the note does not follow the signed-note format.
372    pub fn parse(note: &str) -> Result<Self, NoteError> {
373        let split = note
374            .rfind("\n\n")
375            .ok_or_else(|| NoteError::Malformed("no blank line before the signatures".into()))?;
376        let text = &note[..=split];
377        let signatures_text = &note[split + 2..];
378        if !signatures_text.ends_with('\n') {
379            return Err(NoteError::Malformed("signature block must end in a newline".into()));
380        }
381        let mut signatures = Vec::new();
382        for line in signatures_text.lines() {
383            let rest = line.strip_prefix(SIGNATURE_PREFIX).ok_or_else(|| {
384                NoteError::Malformed("signature line must start with '— '".into())
385            })?;
386            let (name, encoded) = rest.split_once(' ').ok_or_else(|| {
387                NoteError::Malformed("signature line needs a name and a value".into())
388            })?;
389            if !valid_name(name) {
390                return Err(NoteError::Malformed(format!("invalid signer name '{name}'")));
391            }
392            let decoded = BASE64
393                .decode(encoded)
394                .map_err(|e| NoteError::Malformed(format!("bad signature base64: {e}")))?;
395            if decoded.len() < 5 {
396                return Err(NoteError::Malformed("signature is too short".into()));
397            }
398            signatures.push(NoteSignature {
399                name: name.to_string(),
400                key_hash: u32::from_be_bytes([decoded[0], decoded[1], decoded[2], decoded[3]]),
401                signature: decoded[4..].to_vec(),
402            });
403        }
404        if signatures.is_empty() {
405            return Err(NoteError::Malformed("note has no signatures".into()));
406        }
407        Ok(Self { text: text.to_string(), signatures })
408    }
409
410    /// Returns the verifiers among `verifiers` whose signature on this note is valid.
411    pub fn verified_by<'a>(&self, verifiers: &'a [NoteVerifier]) -> Vec<&'a NoteVerifier> {
412        verifiers
413            .iter()
414            .filter(|verifier| {
415                self.signatures.iter().any(|signature| {
416                    signature.name == verifier.name
417                        && signature.key_hash == verifier.key_hash
418                        && verifier.verify(self.text.as_bytes(), &signature.signature)
419                })
420            })
421            .collect()
422    }
423}
424
425/// Signs `text` with every signer and returns the signed note.
426///
427/// # Errors
428///
429/// [`NoteError::Malformed`] when `text` is empty, does not end in a newline, or holds a
430/// blank line; [`NoteError::Signing`] when a signer fails.
431pub async fn sign_note(text: &str, signers: &[Arc<dyn AuditSigner>]) -> Result<String, NoteError> {
432    if text.is_empty() || !text.ends_with('\n') || text.contains("\n\n") {
433        return Err(NoteError::Malformed(
434            "note text must be non-empty, end in a newline, and contain no blank line".into(),
435        ));
436    }
437    let mut note = format!("{text}\n");
438    for signer in signers {
439        let verifier = NoteVerifier::from_public_key(
440            signer.key_name(),
441            signer.algorithm(),
442            signer.public_key(),
443        )?;
444        let signature_bytes = signer.sign(text.as_bytes()).await?;
445        let mut value = verifier.key_hash.to_be_bytes().to_vec();
446        value.extend_from_slice(&signature_bytes);
447        note.push_str(&format!(
448            "{SIGNATURE_PREFIX}{} {}\n",
449            signer.key_name(),
450            BASE64.encode(value)
451        ));
452    }
453    Ok(note)
454}
455
456/// The body of a C2SP tlog checkpoint.
457#[derive(Debug, Clone, PartialEq, Eq)]
458pub struct CheckpointBody {
459    /// The log's origin line.
460    pub origin: String,
461    /// The tree size.
462    pub size: u64,
463    /// The root hash.
464    pub root_hash: AuditHash,
465}
466
467impl CheckpointBody {
468    /// Formats the checkpoint text that gets signed.
469    pub fn to_text(&self) -> String {
470        format!("{}\n{}\n{}\n", self.origin, self.size, BASE64.encode(self.root_hash.0))
471    }
472
473    /// Parses checkpoint text, ignoring extension lines after the root hash.
474    ///
475    /// # Errors
476    ///
477    /// [`NoteError::Malformed`] when a required line is missing or invalid.
478    pub fn parse(text: &str) -> Result<Self, NoteError> {
479        let mut lines = text.lines();
480        let origin = lines.next().filter(|line| !line.is_empty());
481        // Decimal digits only, no sign and no leading zero, as C2SP requires.
482        let size = lines
483            .next()
484            .filter(|line| line.bytes().all(|b| b.is_ascii_digit()))
485            .filter(|line| *line == "0" || !line.starts_with('0'))
486            .and_then(|line| line.parse::<u64>().ok());
487        let root = lines.next().and_then(|line| BASE64.decode(line).ok());
488        match (origin, size, root) {
489            (Some(origin), Some(size), Some(root)) => {
490                let root: [u8; 32] = root
491                    .try_into()
492                    .map_err(|_| NoteError::Malformed("root hash is not 32 bytes".into()))?;
493                Ok(Self { origin: origin.to_string(), size, root_hash: AuditHash(root) })
494            }
495            _ => Err(NoteError::Malformed(
496                "checkpoint needs an origin, a decimal size, and a base64 root hash".into(),
497            )),
498        }
499    }
500}
501
502#[cfg(test)]
503mod tests {
504    use super::*;
505
506    const PETER_SIGNER: &str =
507        "PRIVATE+KEY+PeterNeumann+c74f20a3+AYEKFALVFGyNhPJEMzD1QIDr+Y7hfZx09iUvxdXHKDFz";
508    const PETER_VERIFIER: &str =
509        "PeterNeumann+c74f20a3+ARpc2QcUPDhMQegwxbzhKqiBfsVkmqq/LDE4izWy10TW";
510    const PETER_TEXT: &str = "If you think cryptography is the answer to your problem,\n\
511                              then you don't know what your problem is.\n";
512
513    /// `TestSign` from golang.org/x/mod/sumdb/note.
514    #[tokio::test]
515    async fn go_note_sign_vector() {
516        let signer = Ed25519Signer::from_note_key(PETER_SIGNER).unwrap();
517        assert_eq!(signer.verifier_key(), PETER_VERIFIER);
518        assert_eq!(signer.to_note_key().as_str(), PETER_SIGNER);
519        let signers: Vec<Arc<dyn AuditSigner>> = vec![Arc::new(signer)];
520        let note = sign_note(PETER_TEXT, &signers).await.unwrap();
521        assert_eq!(
522            note,
523            format!(
524                "{PETER_TEXT}\n— PeterNeumann x08go/ZJkuBS9UG/SffcvIAQxVBtiFupLLr8pAcElZInNIuGUgYN1FFYC2pZSNXgKvqfqdngotpRZb6KE6RyyBwJnAM=\n"
525            )
526        );
527        let verifier: NoteVerifier = PETER_VERIFIER.parse().unwrap();
528        let parsed = Note::parse(&note).unwrap();
529        assert_eq!(parsed.text, PETER_TEXT);
530        assert_eq!(parsed.verified_by(std::slice::from_ref(&verifier)).len(), 1);
531    }
532
533    #[test]
534    fn tampered_notes_do_not_verify() {
535        let verifier: NoteVerifier = PETER_VERIFIER.parse().unwrap();
536        let good = format!(
537            "{PETER_TEXT}\n— PeterNeumann x08go/ZJkuBS9UG/SffcvIAQxVBtiFupLLr8pAcElZInNIuGUgYN1FFYC2pZSNXgKvqfqdngotpRZb6KE6RyyBwJnAM=\n"
538        );
539        let edited = good.replacen("answer", "Answer", 1);
540        let parsed = Note::parse(&edited).unwrap();
541        assert!(parsed.verified_by(std::slice::from_ref(&verifier)).is_empty());
542        assert!(Note::parse("no signatures\n").is_err());
543    }
544
545    #[test]
546    fn bad_keys_are_refused() {
547        // From golang.org/x/mod/sumdb/note TestNewVerifier.
548        assert!(
549            "PeterNeumann+cc469956+ARpc2QcUPDhMQegwxbzhKqiBfsVkmqq/LDE4izWy10TWBADKEY=="
550                .parse::<NoteVerifier>()
551                .is_err()
552        );
553        assert!(
554            "PeterNeumann+173116ae+ZRpc2QcUPDhMQegwxbzhKqiBfsVkmqq/LDE4izWy10TW"
555                .parse::<NoteVerifier>()
556                .is_err()
557        );
558        assert!(
559            "PeterNeumann+c74f20a4+ARpc2QcUPDhMQegwxbzhKqiBfsVkmqq/LDE4izWy10TW"
560                .parse::<NoteVerifier>()
561                .is_err()
562        );
563        assert!(Ed25519Signer::generate("has space").is_err());
564    }
565
566    #[test]
567    fn checkpoint_body_round_trips() {
568        let body = CheckpointBody {
569            origin: "example.com/log".into(),
570            size: 42,
571            root_hash: AuditHash([7; 32]),
572        };
573        let text = format!("{}extension line\n", body.to_text());
574        assert_eq!(CheckpointBody::parse(&text).unwrap(), body);
575        assert!(CheckpointBody::parse("origin\n042\nAAAA\n").is_err());
576    }
577}