capsule_library/library/key_pins.rs
1//! The pinned attestation-key history of each server this library has pushed to (SSoT:
2//! [Transfer — Durability: Custody Receipts](https://docs/design/transfer/durability/#custody-receipts)
3//! — the client checks a receipt's signature **under the pinned key**).
4//!
5//! A server publishes its attestation keys at `/.well-known/capsule/attestation-keys` with an
6//! append-only history, so a receipt signed before a rotation still verifies. A client that
7//! trusted whatever each fetch returned would accept a receipt from anyone able to swap that
8//! record — the server itself, or anything on the path to it. So the first fetch is pinned
9//! (trust on first use) and every later fetch is checked against the pin:
10//!
11//! - **First contact** — nothing is pinned for the origin: the published history is pinned.
12//! - **Unchanged** — every published key is already pinned: nothing is written.
13//! - **Extended** — every pinned key is still published, and new ones were added: the new keys
14//! are appended to the pin, in the order the server published them.
15//! - **Rewritten** — a pinned key is no longer published (dropped, or replaced by another):
16//! [`KeyPinError::HistoryRewritten`], and the pin is left exactly as it was. There is no
17//! silent re-pin; a server that rotates *out* a key breaks the append-only contract.
18//!
19//! The comparison is by key, not by position: a server that republishes the same history in
20//! another order has dropped nothing, and the pin keeps its own order.
21//!
22//! # The file
23//!
24//! `.library/attestation-keys.cbor` ([`attestation_key_pins_path`]) is canonical CBOR of a
25//! versioned map from a server's canonical origin (`scheme://host[:port]`, as the caller
26//! derives it) to the pinned keys' raw bytes. It is rewritten through a temporary sibling and a
27//! rename, so a crash mid-write leaves the previous pin whole.
28//!
29//! # Backup and restore
30//!
31//! The pin rides the backup artifact verbatim ([`read_attestation_key_pins`]), so a restored
32//! library keeps checking receipts under the keys it pinned rather than trusting whatever the
33//! server publishes first after the restore. [`restore_attestation_key_pins`] folds a carried
34//! pin into the library by the same append-only rule a fetch obeys, per origin: the union is
35//! kept only where one history extends the other, and two histories that each hold a key the
36//! other lacks are [`KeyPinError::HistoriesDiverge`], with neither overwritten.
37
38use std::collections::BTreeMap;
39use std::fs;
40use std::path::{Path, PathBuf};
41
42use capsule_core::cbor::{self, CanonicalError};
43use capsule_core::crypto::keys::HybridVerifyingKey;
44use serde::{Deserialize, Serialize};
45use serde_bytes::ByteBuf;
46
47use crate::utils::paths::tmp_path;
48
49/// The pin file's schema version. A file stamped with another one is refused, never rewritten.
50const PIN_FILE_VERSION: u8 = 1;
51
52/// `.library/attestation-keys.cbor` — the pinned attestation-key history of every server this
53/// library has contacted.
54pub fn attestation_key_pins_path(root: &Path) -> PathBuf {
55 root.join(".library").join("attestation-keys.cbor")
56}
57
58/// The on-disk shape of the pin file.
59#[derive(Debug, Default, Serialize, Deserialize)]
60struct PinFile {
61 version: u8,
62 /// Canonical origin → the pinned keys' raw bytes, in pinned order.
63 servers: BTreeMap<String, Vec<ByteBuf>>,
64}
65
66/// What pinning a fetched history did.
67#[derive(Debug, Clone, Copy, PartialEq, Eq)]
68pub enum KeyPinOutcome {
69 /// Nothing was pinned for the origin; the published history now is.
70 FirstContact {
71 /// How many keys were pinned.
72 keys: usize,
73 },
74 /// The published history holds exactly the pinned keys; nothing was written.
75 Unchanged,
76 /// The published history extends the pin; the new keys were appended to it.
77 Extended {
78 /// How many keys were appended.
79 added: usize,
80 },
81}
82
83/// The pinned history a run verifies under, and how it got there.
84#[derive(Debug, Clone)]
85pub struct PinnedKeys {
86 /// What this call did to the pin.
87 pub outcome: KeyPinOutcome,
88 /// Every pinned key for the origin, in pinned order, after this call.
89 pub keys: Vec<HybridVerifyingKey>,
90}
91
92/// Errors pinning or reading a server's attestation-key history.
93#[derive(Debug, thiserror::Error)]
94pub enum KeyPinError {
95 /// The server no longer publishes a key this library pinned for it: its history was
96 /// rewritten, not extended. The pin is unchanged and nothing the server signs is trusted.
97 #[error(
98 "the server at {origin} no longer publishes {missing} of the {pinned} attestation key(s) \
99 pinned for it; its key history was rewritten, not extended, so its receipts are not trusted"
100 )]
101 HistoryRewritten {
102 /// The canonical origin whose pin was contradicted.
103 origin: String,
104 /// How many pinned keys the server no longer publishes.
105 missing: usize,
106 /// How many keys were pinned.
107 pinned: usize,
108 },
109 /// A backup carries a pinned history for an origin that neither extends nor is extended by
110 /// the one this library pins: each holds a key the other lacks. Neither pin is trusted over
111 /// the other, so the restore is refused and the library's pin is left exactly as it was.
112 #[error(
113 "the backup pins an attestation-key history for {origin} that diverges from this \
114 library's: the backup holds {only_carried} key(s) this library does not pin, and this \
115 library pins {only_local} key(s) the backup lacks"
116 )]
117 HistoriesDiverge {
118 /// The canonical origin whose two pinned histories diverge.
119 origin: String,
120 /// How many keys only the backup's pin holds.
121 only_carried: usize,
122 /// How many keys only this library's pin holds.
123 only_local: usize,
124 },
125 /// The server published no attestation key at all, so there is nothing to pin and nothing
126 /// a receipt could verify under.
127 #[error("the server at {origin} publishes no attestation key")]
128 EmptyHistory {
129 /// The canonical origin that published nothing.
130 origin: String,
131 },
132 /// The pin file was written by a schema this build does not know.
133 #[error("the attestation-key pin file has schema v{found}; this build reads v{supported}")]
134 UnsupportedVersion {
135 /// The version the file carries.
136 found: u8,
137 /// The version this build reads and writes.
138 supported: u8,
139 },
140 /// A pinned key's bytes no longer decode as a key.
141 #[error("a pinned attestation key for {origin} does not decode: {reason}")]
142 CorruptPin {
143 /// The canonical origin whose pin is corrupt.
144 origin: String,
145 /// Why the key did not decode.
146 reason: String,
147 },
148 /// The pin file could not be decoded or encoded.
149 #[error("attestation-key pin codec: {0}")]
150 Codec(#[from] CanonicalError),
151 /// A filesystem error reading or writing the pin file.
152 #[error("attestation-key pin I/O: {0}")]
153 Io(String),
154}
155
156/// A pin failure during a backup restore, as the backup error the restore reports: a diverged
157/// history keeps its counts, everything else its message.
158impl From<KeyPinError> for capsule_core::backup::BackupError {
159 fn from(error: KeyPinError) -> Self {
160 match error {
161 KeyPinError::HistoriesDiverge {
162 origin,
163 only_carried,
164 only_local,
165 } => Self::AttestationKeyPinsDiverge {
166 origin,
167 only_carried,
168 only_local,
169 },
170 other => Self::AttestationKeyPins(other.to_string()),
171 }
172 }
173}
174
175/// The pin file's raw bytes, or `None` when it is absent or empty.
176fn read_pin_bytes(root: &Path) -> Result<Option<Vec<u8>>, KeyPinError> {
177 match fs::read(attestation_key_pins_path(root)) {
178 Ok(bytes) if bytes.is_empty() => Ok(None),
179 Ok(bytes) => Ok(Some(bytes)),
180 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
181 Err(e) => Err(KeyPinError::Io(e.to_string())),
182 }
183}
184
185fn load_pin_file(root: &Path) -> Result<PinFile, KeyPinError> {
186 match read_pin_bytes(root)? {
187 Some(bytes) => decode_pin_file(&bytes),
188 None => Ok(empty_pin_file()),
189 }
190}
191
192/// Decode pin-file bytes, refusing another schema version and any key that does not decode.
193fn decode_pin_file(bytes: &[u8]) -> Result<PinFile, KeyPinError> {
194 let file: PinFile = cbor::from_slice(bytes)?;
195 if file.version != PIN_FILE_VERSION {
196 return Err(KeyPinError::UnsupportedVersion {
197 found: file.version,
198 supported: PIN_FILE_VERSION,
199 });
200 }
201 Ok(file)
202}
203
204fn empty_pin_file() -> PinFile {
205 PinFile {
206 version: PIN_FILE_VERSION,
207 servers: BTreeMap::new(),
208 }
209}
210
211fn store_pin_file(root: &Path, file: &PinFile) -> Result<(), KeyPinError> {
212 store_pin_bytes(root, &cbor::to_canonical_vec(file)?)
213}
214
215/// Write `bytes` as the pin file through a temporary sibling and a rename.
216fn store_pin_bytes(root: &Path, bytes: &[u8]) -> Result<(), KeyPinError> {
217 let path = attestation_key_pins_path(root);
218 if let Some(parent) = path.parent() {
219 fs::create_dir_all(parent).map_err(|e| KeyPinError::Io(e.to_string()))?;
220 }
221 let tmp = tmp_path(&path);
222 fs::write(&tmp, bytes).map_err(|e| KeyPinError::Io(e.to_string()))?;
223 fs::rename(&tmp, &path).map_err(|e| KeyPinError::Io(e.to_string()))?;
224 Ok(())
225}
226
227fn decode_pin(origin: &str, pinned: &[ByteBuf]) -> Result<Vec<HybridVerifyingKey>, KeyPinError> {
228 pinned
229 .iter()
230 .map(|bytes| {
231 HybridVerifyingKey::from_bytes(bytes).map_err(|e| KeyPinError::CorruptPin {
232 origin: origin.to_owned(),
233 reason: e.to_string(),
234 })
235 })
236 .collect()
237}
238
239/// The history pinned for `origin`, or `None` when this library has never contacted it.
240pub fn load_pinned_attestation_keys(
241 root: &Path,
242 origin: &str,
243) -> Result<Option<Vec<HybridVerifyingKey>>, KeyPinError> {
244 let file = load_pin_file(root)?;
245 file.servers
246 .get(origin)
247 .map(|pinned| decode_pin(origin, pinned))
248 .transpose()
249}
250
251/// Check the history `origin` just `published` against the pin, pin or extend it, and return
252/// the pinned history every receipt from that server is verified under.
253///
254/// Nothing pinned for `origin` pins `published` ([`KeyPinOutcome::FirstContact`]); a history
255/// holding exactly the pinned keys writes nothing ([`KeyPinOutcome::Unchanged`]); one holding
256/// every pinned key and more appends the new keys in published order
257/// ([`KeyPinOutcome::Extended`]). Keys are compared by value, not position. A history missing a
258/// pinned key is [`KeyPinError::HistoryRewritten`], and an empty one
259/// [`KeyPinError::EmptyHistory`]; a refusal writes nothing.
260#[tracing::instrument(skip(root, published), fields(published = published.len()))]
261pub fn pin_attestation_keys(
262 root: &Path,
263 origin: &str,
264 published: &[HybridVerifyingKey],
265) -> Result<PinnedKeys, KeyPinError> {
266 if published.is_empty() {
267 tracing::warn!("attestation-key pin: the server publishes no key");
268 return Err(KeyPinError::EmptyHistory {
269 origin: origin.to_owned(),
270 });
271 }
272 let published_bytes: Vec<Vec<u8>> =
273 published.iter().map(HybridVerifyingKey::to_bytes).collect();
274
275 let mut file = load_pin_file(root)?;
276 let Some(pinned) = file.servers.get(origin) else {
277 let keys = published.len();
278 file.servers.insert(
279 origin.to_owned(),
280 published_bytes.into_iter().map(ByteBuf::from).collect(),
281 );
282 store_pin_file(root, &file)?;
283 tracing::info!(keys, "attestation-key pin: first contact, history pinned");
284 return Ok(PinnedKeys {
285 outcome: KeyPinOutcome::FirstContact { keys },
286 keys: published.to_vec(),
287 });
288 };
289
290 let missing = pinned
291 .iter()
292 .filter(|key| !published_bytes.iter().any(|p| p == key.as_slice()))
293 .count();
294 if missing > 0 {
295 tracing::warn!(
296 missing,
297 pinned = pinned.len(),
298 "attestation-key pin: a pinned key is no longer published; refusing"
299 );
300 return Err(KeyPinError::HistoryRewritten {
301 origin: origin.to_owned(),
302 missing,
303 pinned: pinned.len(),
304 });
305 }
306
307 let added: Vec<ByteBuf> = published_bytes
308 .into_iter()
309 .filter(|key| !pinned.iter().any(|p| p.as_slice() == key.as_slice()))
310 .map(ByteBuf::from)
311 .collect();
312 if added.is_empty() {
313 tracing::debug!(keys = pinned.len(), "attestation-key pin: unchanged");
314 let keys = decode_pin(origin, pinned)?;
315 return Ok(PinnedKeys {
316 outcome: KeyPinOutcome::Unchanged,
317 keys,
318 });
319 }
320
321 let added_count = added.len();
322 let mut extended = pinned.clone();
323 extended.extend(added);
324 let keys = decode_pin(origin, &extended)?;
325 file.servers.insert(origin.to_owned(), extended);
326 store_pin_file(root, &file)?;
327 tracing::info!(
328 added = added_count,
329 keys = keys.len(),
330 "attestation-key pin: history extended and re-pinned"
331 );
332 Ok(PinnedKeys {
333 outcome: KeyPinOutcome::Extended { added: added_count },
334 keys,
335 })
336}
337
338/// What folding a backup's pinned histories into this library did.
339#[derive(Debug, Clone, Copy, PartialEq, Eq)]
340pub enum KeyPinRestoreOutcome {
341 /// This library pinned nothing; the backup's pin file was written byte for byte.
342 Restored {
343 /// How many origins the restored pin covers.
344 origins: usize,
345 },
346 /// Every history the backup carries is already pinned here, or extended by the pin here:
347 /// nothing was written.
348 Unchanged,
349 /// This library's pin was extended with what the backup carries.
350 Merged {
351 /// Origins the backup pins that this library had never contacted.
352 origins_added: usize,
353 /// Keys appended to histories this library already pinned.
354 keys_added: usize,
355 },
356 /// The backup's pin file has a schema newer than this build reads, so it was left out and
357 /// nothing was written. A newer artifact still restores its assets on an older build; the
358 /// library re-pins each server on its next contact, as one that never pinned it would.
359 SkippedNewerSchema {
360 /// The schema version the carried pin file declares.
361 found: u8,
362 },
363}
364
365/// Just the schema version of a pin file, read before the rest so a newer schema whose shape
366/// this build cannot decode is recognised as newer rather than as corrupt.
367#[derive(Deserialize)]
368struct PinFileVersion {
369 version: u8,
370}
371
372/// Refuse a pin file holding a key that does not decode.
373fn check_pin_keys(file: &PinFile) -> Result<(), KeyPinError> {
374 for (origin, pinned) in &file.servers {
375 decode_pin(origin, pinned)?;
376 }
377 Ok(())
378}
379
380/// The pin file's bytes exactly as they are on disk, for the backup artifact to carry, or `None`
381/// when this library has pinned nothing.
382///
383/// The bytes are checked first — this build's schema, and every key decodes — so an artifact
384/// never carries a pin a restore would refuse.
385pub fn read_attestation_key_pins(root: &Path) -> Result<Option<Vec<u8>>, KeyPinError> {
386 let Some(bytes) = read_pin_bytes(root)? else {
387 return Ok(None);
388 };
389 check_pin_keys(&decode_pin_file(&bytes)?)?;
390 Ok(Some(bytes))
391}
392
393/// Fold the pin file a backup `carried` into this library's pin.
394///
395/// A library with no pin takes the carried file byte for byte
396/// ([`KeyPinRestoreOutcome::Restored`]). Otherwise each origin is merged by the rule a fetch
397/// obeys: an origin this library never contacted is pinned as carried; one whose pinned history
398/// holds every carried key is kept as it is; one whose pinned keys are all carried, plus more, is
399/// extended by the carried keys it lacks, in carried order. An origin where each side holds a key
400/// the other lacks is [`KeyPinError::HistoriesDiverge`]. Every origin is checked before anything
401/// is written, so a refusal — that one, or a carried file that does not decode — leaves the
402/// library's pin exactly as it was.
403///
404/// A carried file stamped with a schema **newer** than this build reads is not refused: it is
405/// skipped with a warning ([`KeyPinRestoreOutcome::SkippedNewerSchema`]), so a backup from a
406/// newer build still restores here. A pin is never worth more than the assets it travels with.
407/// Any other version, and anything that does not decode, is refused.
408#[tracing::instrument(skip_all, fields(carried = carried.len()))]
409pub fn restore_attestation_key_pins(
410 root: &Path,
411 carried: &[u8],
412) -> Result<KeyPinRestoreOutcome, KeyPinError> {
413 use std::collections::btree_map::Entry;
414
415 let PinFileVersion { version } = cbor::from_slice(carried)?;
416 if version > PIN_FILE_VERSION {
417 tracing::warn!(
418 found = version,
419 supported = PIN_FILE_VERSION,
420 "attestation-key pin restore: the backup's pin has a newer schema; skipping it"
421 );
422 return Ok(KeyPinRestoreOutcome::SkippedNewerSchema { found: version });
423 }
424 let carried_file = decode_pin_file(carried)?;
425 check_pin_keys(&carried_file)?;
426 if carried_file.servers.is_empty() {
427 tracing::debug!("attestation-key pin restore: the backup pins no origin");
428 return Ok(KeyPinRestoreOutcome::Unchanged);
429 }
430 let Some(local_bytes) = read_pin_bytes(root)? else {
431 store_pin_bytes(root, carried)?;
432 let origins = carried_file.servers.len();
433 tracing::info!(
434 origins,
435 "attestation-key pin restore: pin restored from the backup"
436 );
437 return Ok(KeyPinRestoreOutcome::Restored { origins });
438 };
439
440 let mut local = decode_pin_file(&local_bytes)?;
441 let (mut origins_added, mut keys_added) = (0usize, 0usize);
442 for (origin, keys) in carried_file.servers {
443 match local.servers.entry(origin) {
444 Entry::Vacant(slot) => {
445 slot.insert(keys);
446 origins_added += 1;
447 }
448 Entry::Occupied(mut slot) => {
449 let pinned = slot.get_mut();
450 let only_local = pinned.iter().filter(|key| !keys.contains(key)).count();
451 let only_carried: Vec<ByteBuf> = keys
452 .into_iter()
453 .filter(|key| !pinned.contains(key))
454 .collect();
455 if only_local > 0 && !only_carried.is_empty() {
456 tracing::warn!(
457 origin = %slot.key(),
458 only_local,
459 only_carried = only_carried.len(),
460 "attestation-key pin restore: the histories diverge; refusing"
461 );
462 return Err(KeyPinError::HistoriesDiverge {
463 origin: slot.key().clone(),
464 only_carried: only_carried.len(),
465 only_local,
466 });
467 }
468 keys_added += only_carried.len();
469 pinned.extend(only_carried);
470 }
471 }
472 }
473
474 if origins_added == 0 && keys_added == 0 {
475 tracing::debug!("attestation-key pin restore: the backup's pin is already held");
476 return Ok(KeyPinRestoreOutcome::Unchanged);
477 }
478 store_pin_file(root, &local)?;
479 tracing::info!(
480 origins_added,
481 keys_added,
482 "attestation-key pin restore: the backup's pin merged into this library's"
483 );
484 Ok(KeyPinRestoreOutcome::Merged {
485 origins_added,
486 keys_added,
487 })
488}
489
490#[cfg(test)]
491mod tests;