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