weirdnet_update/
envelope.rs1use 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
14pub const MAX_ENVELOPE_BYTES: usize = 1024 * 1024;
16pub const MAX_SIGNATURES: usize = 64;
18
19#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
21#[serde(rename_all = "kebab-case")]
22pub enum Domain {
23 Root,
25 Manifest,
27 Freshness,
29}
30
31impl Domain {
32 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#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
54pub struct SignatureEntry {
55 pub key: PublicKey,
57 pub sig: Signature,
59}
60
61#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
63pub struct Signed {
64 pub domain: Domain,
66 #[serde(with = "serde_bytes")]
68 pub payload: Vec<u8>,
69 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 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 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 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 pub fn decode<T: DeserializeOwned>(&self) -> Result<T> {
129 cbor::from_slice(&self.payload)
130 }
131
132 pub fn payload_hash(&self) -> Hash32 {
134 Hash32::of(&self.payload)
135 }
136
137 pub fn to_bytes(&self) -> Result<Vec<u8>> {
139 cbor::to_vec(self)
140 }
141
142 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}