Skip to main content

weirdnet_update/
envelope.rs

1//! Signed envelopes.
2//!
3//! An envelope carries the exact CBOR bytes of a record and the signatures over them, so a
4//! verifier checks signatures on the bytes it received and only then decodes. Each signature
5//! covers `weirdnet-update/v1/<domain>` + `0x00` + payload, so a signature made for one record
6//! kind never verifies as another.
7
8use crate::keys::{PublicKey, Signature, SigningKey};
9use crate::{Error, Hash32, Result, cbor};
10use serde::{Deserialize, Serialize, de::DeserializeOwned};
11use std::collections::BTreeSet;
12use std::fmt;
13
14/// Largest encoded envelope accepted from the network.
15pub const MAX_ENVELOPE_BYTES: usize = 1024 * 1024;
16/// Most signatures one envelope may carry.
17pub const MAX_SIGNATURES: usize = 64;
18
19/// What a signature is for.
20#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
21#[serde(rename_all = "kebab-case")]
22pub enum Domain {
23    /// An org [`Root`](crate::Root).
24    Root,
25    /// An [`UpdateManifest`](crate::UpdateManifest).
26    Manifest,
27    /// A [`Freshness`](crate::Freshness) record.
28    Freshness,
29    /// An [`Announcement`](crate::announce::Announcement).
30    Announcement,
31}
32
33impl Domain {
34    /// The signing context string.
35    pub fn context(self) -> &'static str {
36        match self {
37            Self::Root => "weirdnet-update/v1/root",
38            Self::Manifest => "weirdnet-update/v1/manifest",
39            Self::Freshness => "weirdnet-update/v1/freshness",
40            Self::Announcement => "weirdnet-update/v1/announcement",
41        }
42    }
43}
44
45impl fmt::Display for Domain {
46    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
47        f.write_str(match self {
48            Self::Root => "root",
49            Self::Manifest => "manifest",
50            Self::Freshness => "freshness",
51            Self::Announcement => "announcement",
52        })
53    }
54}
55
56/// One signature and the key that made it.
57#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
58pub struct SignatureEntry {
59    /// Signer.
60    pub key: PublicKey,
61    /// Signature over the domain-separated payload.
62    pub sig: Signature,
63}
64
65/// A record's CBOR bytes plus signatures.
66#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
67pub struct Signed {
68    /// What the record is.
69    pub domain: Domain,
70    /// The record's exact CBOR encoding.
71    #[serde(with = "serde_bytes")]
72    pub payload: Vec<u8>,
73    /// Signatures, in any order.
74    pub signatures: Vec<SignatureEntry>,
75}
76
77fn message(domain: Domain, payload: &[u8]) -> Vec<u8> {
78    let ctx = domain.context().as_bytes();
79    let mut msg = Vec::with_capacity(ctx.len() + 1 + payload.len());
80    msg.extend_from_slice(ctx);
81    msg.push(0);
82    msg.extend_from_slice(payload);
83    msg
84}
85
86impl Signed {
87    /// Encodes `value` and signs it with each key (k-of-n signers may also add theirs later
88    /// with [`Signed::add_signature`]).
89    pub fn sign<T: Serialize>(domain: Domain, value: &T, keys: &[&SigningKey]) -> Result<Self> {
90        let mut env = Self { domain, payload: cbor::to_vec(value)?, signatures: Vec::new() };
91        for key in keys {
92            env.add_signature(key);
93        }
94        Ok(env)
95    }
96
97    /// Adds (or replaces) `key`'s signature.
98    pub fn add_signature(&mut self, key: &SigningKey) {
99        let public = key.public();
100        let sig = key.sign_raw(&message(self.domain, &self.payload));
101        self.signatures.retain(|e| e.key != public);
102        self.signatures.push(SignatureEntry { key: public, sig });
103    }
104
105    /// Checks that at least `threshold` distinct keys from `trusted` made valid signatures.
106    /// Signatures from other keys, and repeated signatures from one key, don't count.
107    pub fn verify_threshold(&self, domain: Domain, trusted: &[PublicKey], threshold: usize) -> Result<()> {
108        if self.domain != domain {
109            return Err(Error::WrongDomain { expected: domain, found: self.domain });
110        }
111        if threshold == 0 {
112            return Err(Error::invalid("threshold", "must be at least 1"));
113        }
114        if self.signatures.len() > MAX_SIGNATURES {
115            return Err(Error::invalid("envelope", format!("more than {MAX_SIGNATURES} signatures")));
116        }
117        let msg = message(domain, &self.payload);
118        let mut good = BTreeSet::new();
119        for entry in &self.signatures {
120            if trusted.contains(&entry.key) && !good.contains(&entry.key) && entry.key.verify(&msg, &entry.sig) {
121                good.insert(entry.key);
122            }
123        }
124        if good.len() < threshold {
125            return Err(Error::Threshold { domain, found: good.len(), needed: threshold });
126        }
127        Ok(())
128    }
129
130    /// Decodes the payload. Call only after [`Signed::verify_threshold`], or on data whose
131    /// trust is checked another way (an initial root is checked against its pin).
132    pub fn decode<T: DeserializeOwned>(&self) -> Result<T> {
133        cbor::from_slice(&self.payload)
134    }
135
136    /// BLAKE3 of the payload; freshness records name a manifest by it.
137    pub fn payload_hash(&self) -> Hash32 {
138        Hash32::of(&self.payload)
139    }
140
141    /// CBOR encoding of the whole envelope.
142    pub fn to_bytes(&self) -> Result<Vec<u8>> {
143        cbor::to_vec(self)
144    }
145
146    /// Parses an envelope, refusing anything over [`MAX_ENVELOPE_BYTES`].
147    pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
148        if bytes.len() > MAX_ENVELOPE_BYTES {
149            return Err(Error::Decode(format!("envelope larger than {MAX_ENVELOPE_BYTES} bytes")));
150        }
151        let env: Self = cbor::from_slice(bytes)?;
152        if env.signatures.len() > MAX_SIGNATURES {
153            return Err(Error::Decode(format!("more than {MAX_SIGNATURES} signatures")));
154        }
155        Ok(env)
156    }
157}