Skip to main content

nibkeep_node/
recovery_file.rs

1//! The recovery file: the personal space's first key, sealed to each recovery code that
2//! stands, which cannot come from the log, whose governing changes it wraps. Each replica
3//! of the person keeps one in its folder, and each backup holds the same file, so that a
4//! code and a backup together open the library ([technical design: recovery codes]).
5//!
6//! [technical design: recovery codes]: ../../../docs/Technical-design.md#111-recovery-codes
7
8use std::fs;
9use std::io;
10use std::path::Path;
11
12use nibkeep_base::cbor::{self, FromCbor, ToCbor, Value};
13use nibkeep_base::{EntityId, Hash, SpaceId};
14use nibkeep_crypto::{Key, RecoveryCode, Signature, key_hash};
15use nibkeep_governance::{RecoveryEntry, SpaceEntry, recovery_record};
16use nibkeep_log::ChangeId;
17
18use crate::NodeError;
19
20/// The recovery file's name, in a replica's folder and in a backup's.
21pub const RECOVERY_FILE: &str = "recovery.cbor";
22
23/// The suite of the recovery file in version 1 of the specification.
24const SUITE: u8 = 1;
25
26/// The recovery file. In CBOR, the array `[1, codes, check]`: for each code, sorted by its
27/// record, `[record, entry, signature]`, the code's record in the personal space, the
28/// personal space's entry for it, as the personal space gives a space to a replica, and the
29/// code's signature of what the entry names, which the personal space states on the code's
30/// record ([`RecoveryEntry`]); and the BLAKE3 hash of the canonical encoding of `codes`, so
31/// that a file damaged on its drive reads as damaged, and is written again.
32#[derive(Clone, Debug, PartialEq, Eq)]
33pub struct RecoveryFile {
34	entries: Vec<(EntityId, SpaceEntry, Signature)>,
35}
36
37/// What a recovery file gives a code that opens it.
38pub struct OpenedRecovery {
39	/// The personal space.
40	pub space: SpaceId,
41	/// The member that the code is named for there: the user's own entity.
42	pub member: EntityId,
43	/// The personal space's first change: the only change that a replica takes as its first.
44	pub root: ChangeId,
45	/// The personal space's first key, whose hash the entry names.
46	pub key: Key,
47}
48
49impl RecoveryFile {
50	/// A file of these entries, each on its code's record, with the code's signature of what
51	/// it names.
52	pub(crate) fn new(mut entries: Vec<(EntityId, SpaceEntry, Signature)>) -> Self {
53		entries.sort_by_key(|(record, _, _)| *record);
54		Self { entries }
55	}
56
57	/// Reads the recovery file at `path`: `None` if there is none.
58	///
59	/// # Errors
60	///
61	/// Returns [`NodeError::Damaged`] if it does not read as one, and an error if it cannot
62	/// be read.
63	pub fn read(path: &Path) -> Result<Option<Self>, NodeError> {
64		match fs::read(path) {
65			Ok(bytes) => cbor::from_slice(&bytes)
66				.map(Some)
67				.map_err(|error| NodeError::Damaged(format!("{}: {error}", path.display()))),
68			Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None),
69			Err(error) => Err(NodeError::file(path)(error)),
70		}
71	}
72
73	/// The recovery file that `bytes` are, if they read as one.
74	pub(crate) fn from_bytes(bytes: &[u8]) -> Option<Self> {
75		cbor::from_slice(bytes).ok()
76	}
77
78	/// Its bytes.
79	pub(crate) fn to_bytes(&self) -> Vec<u8> {
80		cbor::to_vec(self)
81	}
82
83	/// The records of the codes that it holds the first key for, in the personal space.
84	pub fn records(&self) -> impl Iterator<Item = EntityId> + '_ {
85		self.entries.iter().map(|(record, _, _)| *record)
86	}
87
88	/// Its entries, each on its code's record, with the code's signature.
89	pub(crate) fn entries(&self) -> &[(EntityId, SpaceEntry, Signature)] {
90		&self.entries
91	}
92
93	/// Opens the personal space's first key with `code`: from the entry on the code's
94	/// record, which is derived from the space, the member and the code's recovery key, if
95	/// the code signed what it names, and it opens to a key whose hash it names.
96	///
97	/// # Errors
98	///
99	/// Returns [`NodeError::RecoveryFileChanged`] if the file holds an entry on the code's
100	/// record that the code did not sign, or that it signed and that does not open to the key
101	/// it names, as a device that turned against the person could write; and
102	/// [`NodeError::CodeOpensNothing`] if it holds no entry on the code's record.
103	pub fn open(&self, code: &RecoveryCode) -> Result<OpenedRecovery, NodeError> {
104		let key = code.signing_key().verifying_key();
105		let decryption = code.decryption_key();
106		let mut changed = false;
107		for (record, entry, signature) in &self.entries {
108			if recovery_record(entry.space, entry.member, &key) != *record {
109				continue;
110			}
111			let signed = RecoveryEntry {
112				space: entry.space,
113				member: entry.member,
114				root: entry.root,
115				hash: entry.hash,
116				key,
117				signature: *signature,
118			};
119			// An entry that the code signed and that does not open was sealed to it anew by
120			// someone else, as the file's check rules out a damaged drive.
121			if signed.verifies()
122				&& let Some(opened) = entry.open(&decryption, *record)
123				&& key_hash(&opened) == entry.hash
124			{
125				return Ok(OpenedRecovery {
126					space: entry.space,
127					member: entry.member,
128					root: ChangeId::from_hash(entry.root),
129					key: opened,
130				});
131			}
132			changed = true;
133		}
134		Err(if changed {
135			NodeError::RecoveryFileChanged
136		} else {
137			NodeError::CodeOpensNothing
138		})
139	}
140}
141
142impl ToCbor for RecoveryFile {
143	fn to_cbor(&self) -> Value {
144		let codes = Value::Array(
145			self.entries
146				.iter()
147				.map(|(record, entry, signature)| {
148					Value::Array(vec![record.to_cbor(), entry.to_cbor(), signature.to_cbor()])
149				})
150				.collect(),
151		);
152		let check = Hash::of(&cbor::encode(&codes));
153		Value::Array(vec![SUITE.to_cbor(), codes, check.to_cbor()])
154	}
155}
156
157impl FromCbor for RecoveryFile {
158	fn from_cbor(value: &Value) -> Result<Self, cbor::Error> {
159		const EXPECTED: &str = "a recovery file: [1, [[record, entry, signature], ...], check]";
160		let Value::Array(items) = value else {
161			return Err(cbor::Error::Expected(EXPECTED));
162		};
163		let [suite, listed, check] = items.as_slice() else {
164			return Err(cbor::Error::Expected(EXPECTED));
165		};
166		let Value::Array(codes) = listed else {
167			return Err(cbor::Error::Expected(EXPECTED));
168		};
169		if u8::from_cbor(suite) != Ok(SUITE)
170			|| Hash::from_cbor(check)? != Hash::of(&cbor::encode(listed))
171		{
172			return Err(cbor::Error::Expected(EXPECTED));
173		}
174		let entries = codes
175			.iter()
176			.map(|code| {
177				let Value::Array(pair) = code else {
178					return Err(cbor::Error::Expected(EXPECTED));
179				};
180				let [record, entry, signature] = pair.as_slice() else {
181					return Err(cbor::Error::Expected(EXPECTED));
182				};
183				Ok((
184					EntityId::from_cbor(record)?,
185					SpaceEntry::from_cbor(entry)?,
186					Signature::from_cbor(signature)?,
187				))
188			})
189			.collect::<Result<Vec<_>, _>>()?;
190		Ok(Self::new(entries))
191	}
192}
193
194#[cfg(test)]
195mod tests {
196	use nibkeep_crypto::key_hash;
197	use nibkeep_testkit::TestRng;
198
199	use super::*;
200
201	#[test]
202	fn a_recovery_file_reads_back_and_opens_with_its_code_alone() {
203		let mut rng = TestRng::new("a recovery file");
204		let space = SpaceId::random(&mut rng);
205		let member = EntityId::random(&mut rng);
206		let first = Key::generate(&mut rng);
207		let code = RecoveryCode::generate(&mut rng);
208		let other = RecoveryCode::generate(&mut rng);
209		let root = nibkeep_base::Hash::of(b"the first change");
210		let (record, entry, signature) =
211			signed_entry(&code, (space, member, root), &first, &mut rng);
212		let file = RecoveryFile::new(vec![(record, entry.clone(), signature)]);
213		let read: RecoveryFile = cbor::from_slice(&file.to_bytes()).expect("reads");
214		assert_eq!(read, file);
215		let opened = read.open(&code).expect("opens");
216		assert_eq!((opened.space, opened.member), (space, member));
217		assert_eq!(opened.root, ChangeId::from_hash(root));
218		assert!(opened.key.same_as(&first));
219		assert!(matches!(
220			read.open(&other),
221			Err(NodeError::CodeOpensNothing)
222		));
223		// An entry on another record than the code's opens nothing, even sealed to it.
224		let moved = RecoveryFile::new(vec![(EntityId::random(&mut rng), entry, signature)]);
225		assert!(matches!(
226			moved.open(&code),
227			Err(NodeError::CodeOpensNothing)
228		));
229		// A byte changed anywhere, as on a damaged drive, makes it read as damaged.
230		let bytes = file.to_bytes();
231		for at in [bytes.len() / 2, bytes.len() - 5] {
232			let mut damaged = bytes.clone();
233			damaged[at] ^= 1;
234			assert!(cbor::from_slice::<RecoveryFile>(&damaged).is_err(), "{at}");
235		}
236	}
237
238	/// An entry for `code` named for `member` in `space`, whose first change is `root` and
239	/// first key `first`, on the code's record, with the code's signature.
240	fn signed_entry(
241		code: &RecoveryCode,
242		(space, member, root): (SpaceId, EntityId, nibkeep_base::Hash),
243		first: &Key,
244		rng: &mut TestRng,
245	) -> (EntityId, SpaceEntry, Signature) {
246		let record = recovery_record(space, member, &code.signing_key().verifying_key());
247		let entry = SpaceEntry::seal(
248			&code.decryption_key().encryption_key(),
249			(space, member, root),
250			record,
251			(first, key_hash(first)),
252			rng,
253		);
254		let signed = RecoveryEntry::sign(code, (space, member, root), key_hash(first));
255		(record, entry, signed.signature)
256	}
257
258	#[test]
259	fn an_entry_that_the_code_did_not_sign_opens_nothing() {
260		// A device that holds the first key, and writes the file as it updates a backup,
261		// seals it to the code anew for what it chooses: the entry opens, but the code never
262		// signed what it names.
263		let mut rng = TestRng::new("a forged recovery file");
264		let space = SpaceId::random(&mut rng);
265		let member = EntityId::random(&mut rng);
266		let first = Key::generate(&mut rng);
267		let code = RecoveryCode::generate(&mut rng);
268		let root = nibkeep_base::Hash::of(b"the first change");
269		let (_, _, signature) = signed_entry(&code, (space, member, root), &first, &mut rng);
270		let made_up = EntityId::random(&mut rng);
271		let another_root = nibkeep_base::Hash::of(b"a space of the forger's making");
272		let another_key = Key::generate(&mut rng);
273		let forged = [
274			// A member made up, whom the library would take for its person.
275			signed_entry(&code, (space, made_up, root), &first, &mut rng),
276			// A personal space of the forger's making, under the same ID.
277			signed_entry(&code, (space, member, another_root), &another_key, &mut rng),
278			signed_entry(&code, (space, member, another_root), &first, &mut rng),
279		];
280		for (record, entry, _) in forged {
281			// With the genuine entry's signature, the best that it can do.
282			let file = RecoveryFile::new(vec![(record, entry.clone(), signature)]);
283			let read: RecoveryFile = cbor::from_slice(&file.to_bytes()).expect("reads");
284			assert!(matches!(
285				read.open(&code),
286				Err(NodeError::RecoveryFileChanged)
287			));
288			// Nor does another code's signature of the same entry pass.
289			let other = RecoveryCode::generate(&mut rng);
290			let signed =
291				RecoveryEntry::sign(&other, (entry.space, entry.member, entry.root), entry.hash);
292			let file = RecoveryFile::new(vec![(record, entry, signed.signature)]);
293			assert!(matches!(
294				file.open(&code),
295				Err(NodeError::RecoveryFileChanged)
296			));
297		}
298		// Nor does one that keeps what the code signed, with another key sealed to it.
299		let (record, _, signature) = signed_entry(&code, (space, member, root), &first, &mut rng);
300		let (_, mut resealed, _) =
301			signed_entry(&code, (space, member, root), &another_key, &mut rng);
302		resealed.hash = key_hash(&first);
303		let file = RecoveryFile::new(vec![(record, resealed, signature)]);
304		assert!(matches!(
305			file.open(&code),
306			Err(NodeError::RecoveryFileChanged)
307		));
308		// The genuine entry beside a forged one still opens.
309		let genuine = signed_entry(&code, (space, member, root), &first, &mut rng);
310		let (record, entry, _) = signed_entry(&code, (space, made_up, root), &first, &mut rng);
311		let file = RecoveryFile::new(vec![genuine, (record, entry, signature)]);
312		assert_eq!(file.open(&code).expect("opens").member, member);
313	}
314}