Skip to main content

nibkeep_keys/
file.rs

1//! The key file: two compartments, each opened by a passphrase or the platform's keystore.
2
3use std::fmt;
4use std::fs;
5use std::io::Write;
6use std::path::Path;
7use std::sync::atomic::{AtomicU64, Ordering};
8
9use nibkeep_base::cbor::{self, FromCbor, ToCbor, Value};
10use nibkeep_crypto::rand_core::CryptoRng;
11use nibkeep_crypto::{Envelope, Key, PassphraseParams};
12use zeroize::Zeroizing;
13
14use crate::{KeysError, ReplicaKeys, SecretsKeys};
15
16/// The suite of the key file format in version 1 of the specification.
17const SUITE: u8 = 1;
18
19/// The name of the replica compartment, in its associated data.
20const REPLICA: &str = "nibkeep key file: replica";
21
22/// The name of the secrets compartment, in its associated data.
23const SECRETS: &str = "nibkeep key file: secrets";
24
25/// Counts writes, so that concurrent writes use temporary files of their own.
26static WRITES: AtomicU64 = AtomicU64::new(0);
27
28/// How a compartment's key is found.
29#[derive(Clone, PartialEq, Eq)]
30pub enum Protection {
31	/// Derived from a passphrase with Argon2id.
32	Passphrase {
33		/// The cost of the derivation.
34		params: PassphraseParams,
35		/// Random bytes, new for every compartment key.
36		salt: [u8; 16],
37	},
38	/// Kept in the platform's keystore, under a service and an account name. Every
39	/// compartment key has an account name of its own.
40	Keystore {
41		/// The service name.
42		service: String,
43		/// The account name.
44		account: String,
45	},
46}
47
48impl fmt::Debug for Protection {
49	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
50		match self {
51			Self::Passphrase { params, .. } => f
52				.debug_struct("Passphrase")
53				.field("params", params)
54				.finish_non_exhaustive(),
55			Self::Keystore { service, account } => f
56				.debug_struct("Keystore")
57				.field("service", service)
58				.field("account", account)
59				.finish(),
60		}
61	}
62}
63
64/// How to protect a compartment that is being written.
65#[derive(Clone, Copy)]
66pub enum NewProtection<'a> {
67	/// With a passphrase, at this cost.
68	Passphrase(&'a str, PassphraseParams),
69	/// With a new random key, kept in the platform's keystore under this service name and
70	/// an account name of its own.
71	Keystore {
72		/// The service name.
73		service: &'a str,
74	},
75}
76
77impl fmt::Debug for NewProtection<'_> {
78	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
79		match self {
80			Self::Passphrase(_, params) => f.debug_tuple("Passphrase").field(params).finish(),
81			Self::Keystore { service } => f
82				.debug_struct("Keystore")
83				.field("service", service)
84				.finish(),
85		}
86	}
87}
88
89/// What unlocks a compartment.
90#[derive(Clone, Copy)]
91pub enum Unlocker<'a> {
92	/// The passphrase.
93	Passphrase(&'a str),
94	/// The key in the platform's keystore, which the platform may release only after its
95	/// own confirmation.
96	Keystore,
97}
98
99impl fmt::Debug for Unlocker<'_> {
100	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
101		f.write_str(match self {
102			Self::Passphrase(_) => "Passphrase(..)",
103			Self::Keystore => "Keystore",
104		})
105	}
106}
107
108/// The key of an unlocked compartment: kept while the compartment stays unlocked, so that
109/// changing its keys needs no new passphrase or confirmation. It is wiped when dropped and
110/// never printed.
111#[derive(Clone)]
112pub struct CompartmentKey(Key);
113
114impl fmt::Debug for CompartmentKey {
115	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
116		f.write_str("CompartmentKey(..)")
117	}
118}
119
120#[derive(Clone, Debug, PartialEq, Eq)]
121struct Compartment {
122	protection: Protection,
123	envelope: Envelope,
124}
125
126/// A secrets compartment sealed apart from any key file, as deriving a key from a passphrase,
127/// or a keystore's prompt, takes a while, and put in the key file as it is on the disk
128/// afterwards, with [`KeyFile::put_secrets`]. One dropped without being put deletes its
129/// keystore key, which no file will need.
130#[derive(Debug)]
131pub struct SealedSecrets(Option<Compartment>);
132
133impl SealedSecrets {
134	/// Seals `keys` in a new secrets compartment, protected as `protection` says. Returns
135	/// it, and its key.
136	///
137	/// # Errors
138	///
139	/// Returns an error if the passphrase cannot be used or the keystore fails, as when the
140	/// person turns its prompt down.
141	pub fn seal(
142		keys: &SecretsKeys,
143		protection: &NewProtection<'_>,
144		rng: &mut impl CryptoRng,
145	) -> Result<(Self, CompartmentKey), KeysError> {
146		let (compartment, key) = Compartment::seal(&keys.encode(), SECRETS, protection, rng)?;
147		Ok((Self(Some(compartment)), key))
148	}
149
150	/// Replaces the keys it holds, with its key, which asks nothing again.
151	///
152	/// # Errors
153	///
154	/// Returns an error if `key` is not its key.
155	pub fn update(
156		&mut self,
157		keys: &SecretsKeys,
158		key: &CompartmentKey,
159		rng: &mut impl CryptoRng,
160	) -> Result<(), KeysError> {
161		self.0
162			.as_mut()
163			.ok_or(KeysError::NoSecrets)?
164			.reseal(&keys.encode(), SECRETS, key, rng)
165	}
166
167	/// How it is protected.
168	#[must_use]
169	pub fn protection(&self) -> Option<&Protection> {
170		self.0.as_ref().map(|compartment| &compartment.protection)
171	}
172}
173
174impl Drop for SealedSecrets {
175	fn drop(&mut self) {
176		if let Some(Compartment {
177			protection: Protection::Keystore { service, account },
178			..
179		}) = self.0.take()
180		{
181			let _ = keyring_core::Entry::new(&service, &account)
182				.and_then(|entry| entry.delete_credential());
183		}
184	}
185}
186
187/// The key file of a replica: the replica compartment, with the replica's keys and the
188/// space keys, and, on replicas that hold secrets, the secrets compartment. The two open
189/// separately.
190///
191/// In CBOR, a key file is the array `[1, replica]` or `[1, replica, secrets]`.
192/// `docs/spec/keys.md` describes the format.
193#[derive(Clone, Debug)]
194pub struct KeyFile {
195	replica: Compartment,
196	secrets: Option<Compartment>,
197	/// Keystore entries of replaced compartments, deleted once the file that no longer
198	/// needs them is written.
199	obsolete: Vec<(String, String)>,
200}
201
202impl PartialEq for KeyFile {
203	fn eq(&self, other: &Self) -> bool {
204		self.replica == other.replica && self.secrets == other.secrets
205	}
206}
207
208impl Eq for KeyFile {}
209
210impl KeyFile {
211	/// Makes a key file with the replica's keys, protected as `protection` says. Returns the
212	/// file and the key of its replica compartment, which is unlocked.
213	///
214	/// # Errors
215	///
216	/// Returns an error if the passphrase cannot be used or the keystore fails.
217	pub fn create(
218		replica: &ReplicaKeys,
219		protection: &NewProtection<'_>,
220		rng: &mut impl CryptoRng,
221	) -> Result<(Self, CompartmentKey), KeysError> {
222		let (compartment, key) = Compartment::seal(&replica.encode(), REPLICA, protection, rng)?;
223		let file = Self {
224			replica: compartment,
225			secrets: None,
226			obsolete: Vec::new(),
227		};
228		Ok((file, key))
229	}
230
231	/// How the replica compartment is protected.
232	#[must_use]
233	pub fn replica_protection(&self) -> &Protection {
234		&self.replica.protection
235	}
236
237	/// How the secrets compartment is protected, if there is one.
238	#[must_use]
239	pub fn secrets_protection(&self) -> Option<&Protection> {
240		self.secrets.as_ref().map(|secrets| &secrets.protection)
241	}
242
243	/// Unlocks the replica compartment.
244	///
245	/// # Errors
246	///
247	/// Returns an error if `unlocker` does not open it.
248	pub fn unlock_replica(&self, unlocker: &Unlocker<'_>) -> Result<CompartmentKey, KeysError> {
249		self.replica.unlock(REPLICA, unlocker)
250	}
251
252	/// The replica's keys.
253	///
254	/// # Errors
255	///
256	/// Returns an error if `key` is not the replica compartment's key.
257	pub fn replica(&self, key: &CompartmentKey) -> Result<ReplicaKeys, KeysError> {
258		ReplicaKeys::decode(&self.replica.open(REPLICA, key)?)
259	}
260
261	/// Replaces the replica's keys, for example after the replica joins a space.
262	///
263	/// # Errors
264	///
265	/// Returns an error if `key` is not the replica compartment's key.
266	pub fn set_replica(
267		&mut self,
268		keys: &ReplicaKeys,
269		key: &CompartmentKey,
270		rng: &mut impl CryptoRng,
271	) -> Result<(), KeysError> {
272		self.replica.reseal(&keys.encode(), REPLICA, key, rng)
273	}
274
275	/// Protects the replica compartment another way, for example with a new passphrase.
276	/// Returns the compartment's new key. A keystore entry that the old protection used is
277	/// deleted once the file is written.
278	///
279	/// # Errors
280	///
281	/// Returns an error if `key` is not the replica compartment's key, or the new protection
282	/// cannot be set up.
283	pub fn protect_replica(
284		&mut self,
285		key: &CompartmentKey,
286		protection: &NewProtection<'_>,
287		rng: &mut impl CryptoRng,
288	) -> Result<CompartmentKey, KeysError> {
289		let contents = self.replica.open(REPLICA, key)?;
290		let (compartment, new_key) = Compartment::seal(&contents, REPLICA, protection, rng)?;
291		let old = std::mem::replace(&mut self.replica, compartment);
292		self.retire(old);
293		Ok(new_key)
294	}
295
296	/// Sets the secrets compartment, protected as `protection` says, replacing any there
297	/// was: when the replica is chosen to hold secrets, or the person changes how they are
298	/// protected. Returns the compartment's key.
299	///
300	/// # Errors
301	///
302	/// Returns an error if the passphrase cannot be used or the keystore fails.
303	pub fn set_secrets(
304		&mut self,
305		keys: &SecretsKeys,
306		protection: &NewProtection<'_>,
307		rng: &mut impl CryptoRng,
308	) -> Result<CompartmentKey, KeysError> {
309		let (compartment, key) = Compartment::seal(&keys.encode(), SECRETS, protection, rng)?;
310		if let Some(old) = self.secrets.replace(compartment) {
311			self.retire(old);
312		}
313		Ok(key)
314	}
315
316	/// Unlocks the secrets compartment. Unlock it each time the person confirms, and drop
317	/// the key and the secrets keys after a timeout.
318	///
319	/// # Errors
320	///
321	/// Returns an error if the file has no secrets compartment, or `unlocker` does not open
322	/// it.
323	pub fn unlock_secrets(&self, unlocker: &Unlocker<'_>) -> Result<CompartmentKey, KeysError> {
324		self.secrets
325			.as_ref()
326			.ok_or(KeysError::NoSecrets)?
327			.unlock(SECRETS, unlocker)
328	}
329
330	/// The secrets keys.
331	///
332	/// # Errors
333	///
334	/// Returns an error if the file has no secrets compartment, or `key` is not its key.
335	pub fn secrets(&self, key: &CompartmentKey) -> Result<SecretsKeys, KeysError> {
336		let secrets = self.secrets.as_ref().ok_or(KeysError::NoSecrets)?;
337		SecretsKeys::decode(&secrets.open(SECRETS, key)?)
338	}
339
340	/// Whether the keystore lost the key of the secrets compartment, which then opens never
341	/// again: Android destroys keys that need the person's confirmation once the screen lock
342	/// is removed. Asks the keystore for the entry's attributes: a store whose keys need a
343	/// confirmation should answer without one, as an app's on Android does.
344	///
345	/// # Errors
346	///
347	/// Returns an error if the keystore fails.
348	pub fn secrets_key_lost(&self) -> Result<bool, KeysError> {
349		let Some(Protection::Keystore { service, account }) = self.secrets_protection() else {
350			return Ok(false);
351		};
352		match keyring_core::Entry::new(service, account)?.get_attributes() {
353			Ok(_) => Ok(false),
354			Err(keyring_core::Error::NoEntry) => Ok(true),
355			Err(error) => Err(error.into()),
356		}
357	}
358
359	/// Replaces the secrets keys.
360	///
361	/// # Errors
362	///
363	/// Returns an error if the file has no secrets compartment, or `key` is not its key.
364	pub fn update_secrets(
365		&mut self,
366		keys: &SecretsKeys,
367		key: &CompartmentKey,
368		rng: &mut impl CryptoRng,
369	) -> Result<(), KeysError> {
370		self.secrets
371			.as_mut()
372			.ok_or(KeysError::NoSecrets)?
373			.reseal(&keys.encode(), SECRETS, key, rng)
374	}
375
376	/// Reads a key file.
377	///
378	/// # Errors
379	///
380	/// Returns an error if the file cannot be read or is not a key file.
381	pub fn read(path: &Path) -> Result<Self, KeysError> {
382		let bytes = fs::read(path)?;
383		cbor::from_slice(&bytes).map_err(|error| KeysError::Damaged(error.to_string()))
384	}
385
386	/// Writes the key file, replacing it as a whole: a new file is written next to it and
387	/// renamed over it, so that a crash leaves either the old file or the new one. On
388	/// Unix, only the owner may read it. Then deletes the keystore keys that only replaced
389	/// compartments needed; a key that cannot be deleted now is tried again at the next
390	/// write.
391	///
392	/// # Errors
393	///
394	/// Returns an error if the new file cannot be written; the old one is then unchanged.
395	pub fn write(&mut self, path: &Path) -> Result<(), KeysError> {
396		let name = path
397			.file_name()
398			.map_or_else(|| "keys".into(), |name| name.to_string_lossy());
399		let temporary = path.with_file_name(format!(
400			".{name}.{}.{}.tmp",
401			std::process::id(),
402			WRITES.fetch_add(1, Ordering::Relaxed)
403		));
404		let written =
405			write_new(&temporary, &cbor::to_vec(self)).and_then(|()| fs::rename(&temporary, path));
406		if let Err(error) = written {
407			let _ = fs::remove_file(&temporary);
408			return Err(error.into());
409		}
410		// The rename is in place; syncing the directory makes it survive a power cut where
411		// the file system allows it.
412		#[cfg(unix)]
413		{
414			let directory = path
415				.parent()
416				.filter(|directory| !directory.as_os_str().is_empty())
417				.unwrap_or_else(|| Path::new("."));
418			let _ = fs::File::open(directory).and_then(|directory| directory.sync_all());
419		}
420		self.obsolete.retain(|(service, account)| {
421			let deleted = keyring_core::Entry::new(service, account)
422				.and_then(|entry| entry.delete_credential());
423			matches!(deleted, Err(error) if !matches!(error, keyring_core::Error::NoEntry))
424		});
425		Ok(())
426	}
427
428	/// Deletes the keystore keys that the file's compartments use, for a file that is
429	/// thrown away, such as one whose library was never finished. A file protected by
430	/// passphrases uses none.
431	pub fn discard(self) {
432		let entries = [Some(self.replica), self.secrets]
433			.into_iter()
434			.flatten()
435			.filter_map(|compartment| match compartment.protection {
436				Protection::Keystore { service, account } => Some((service, account)),
437				Protection::Passphrase { .. } => None,
438			})
439			.chain(self.obsolete);
440		for (service, account) in entries {
441			let _ = keyring_core::Entry::new(&service, &account)
442				.and_then(|entry| entry.delete_credential());
443		}
444	}
445
446	/// Puts in the file a secrets compartment sealed apart from it, in place of any it had,
447	/// whose keystore key is deleted once the file is written.
448	pub fn put_secrets(&mut self, mut sealed: SealedSecrets) {
449		if let Some(new) = sealed.0.take()
450			&& let Some(old) = self.secrets.replace(new)
451		{
452			self.retire(old);
453		}
454	}
455
456	/// Removes the secrets compartment from a file that is written next, such as one that a
457	/// new replica made to receive the secrets, which it was not given; its keystore key, if
458	/// it has one, is deleted once the file is written without it.
459	pub fn remove_secrets(&mut self) {
460		if let Some(old) = self.secrets.take() {
461			self.retire(old);
462		}
463	}
464
465	/// Removes the secrets compartment, and deletes its keystore key if it has one: for a
466	/// compartment that no written file holds, such as one whose file could not be written.
467	pub fn discard_secrets(&mut self) {
468		if let Some(Compartment {
469			protection: Protection::Keystore { service, account },
470			..
471		}) = self.secrets.take()
472		{
473			let _ = keyring_core::Entry::new(&service, &account)
474				.and_then(|entry| entry.delete_credential());
475		}
476	}
477
478	/// Puts back `before`, the file as it was before a change that could not be written,
479	/// such as a new protection, and deletes the keystore keys that only the change made:
480	/// those of compartments protected otherwise in `before`. Keystore keys still to delete
481	/// that `before` does not use stay to delete, such as those taken over from an earlier
482	/// copy of the file.
483	pub fn restore(&mut self, before: Self) {
484		let uses = |(service, account): &(String, String)| {
485			[Some(&before.replica), before.secrets.as_ref()]
486				.into_iter()
487				.flatten()
488				.any(|compartment| {
489					matches!(&compartment.protection, Protection::Keystore { service: s, account: a }
490						if s == service && a == account)
491				})
492		};
493		let mut pending: Vec<(String, String)> = std::mem::take(&mut self.obsolete)
494			.into_iter()
495			.filter(|entry| !uses(entry))
496			.collect();
497		let changed = |now: Option<&Compartment>, then: Option<&Compartment>| match now {
498			Some(Compartment {
499				protection: Protection::Keystore { service, account },
500				..
501			}) if now.map(|now| &now.protection) != then.map(|then| &then.protection) => {
502				Some((service.clone(), account.clone()))
503			}
504			_ => None,
505		};
506		let made = [
507			changed(Some(&self.replica), Some(&before.replica)),
508			changed(self.secrets.as_ref(), before.secrets.as_ref()),
509		];
510		for (service, account) in made.into_iter().flatten() {
511			let _ = keyring_core::Entry::new(&service, &account)
512				.and_then(|entry| entry.delete_credential());
513		}
514		*self = before;
515		pending.retain(|entry| !self.obsolete.contains(entry));
516		self.obsolete.append(&mut pending);
517	}
518
519	/// Takes over the keystore keys that `older`, an earlier copy of this file, has still to
520	/// delete, so that writing this one deletes them.
521	pub fn take_obsolete(&mut self, older: &mut Self) {
522		self.obsolete.append(&mut older.obsolete);
523	}
524
525	/// Remembers the keystore entry of a replaced compartment, to delete it once the file is
526	/// written.
527	fn retire(&mut self, old: Compartment) {
528		if let Protection::Keystore { service, account } = old.protection {
529			self.obsolete.push((service, account));
530		}
531	}
532}
533
534/// Creates a new file, readable only by its owner on Unix, and writes and syncs `bytes`.
535fn write_new(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
536	let mut options = fs::OpenOptions::new();
537	options.write(true).create_new(true);
538	#[cfg(unix)]
539	std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
540	let mut file = options.open(path)?;
541	file.write_all(bytes)?;
542	file.sync_all()
543}
544
545impl Compartment {
546	/// Encrypts contents with a new compartment key, protected as `protection` says.
547	fn seal(
548		contents: &[u8],
549		name: &str,
550		protection: &NewProtection<'_>,
551		rng: &mut impl CryptoRng,
552	) -> Result<(Self, CompartmentKey), KeysError> {
553		let (protection, key) = match *protection {
554			NewProtection::Passphrase(passphrase, params) => {
555				let mut salt = [0; 16];
556				rng.fill_bytes(&mut salt);
557				let key = Key::from_passphrase(passphrase, &salt, &params)?;
558				(Protection::Passphrase { params, salt }, key)
559			}
560			NewProtection::Keystore { service } => {
561				// A new account name, so that no key that a written file needs is replaced.
562				let mut suffix = [0; 8];
563				rng.fill_bytes(&mut suffix);
564				let account = format!("nibkeep-{:016x}", u64::from_be_bytes(suffix));
565				let key = Key::generate(rng);
566				keyring_core::Entry::new(service, &account)?.set_secret(key.expose_bytes())?;
567				let protection = Protection::Keystore {
568					service: service.to_owned(),
569					account,
570				};
571				(protection, key)
572			}
573		};
574		let envelope = Envelope::seal(&key, contents, &associated_data(name, &protection), rng);
575		Ok((
576			Self {
577				protection,
578				envelope,
579			},
580			CompartmentKey(key),
581		))
582	}
583
584	/// Gets the compartment key from the passphrase or the keystore, and checks that it
585	/// opens the compartment.
586	fn unlock(&self, name: &str, unlocker: &Unlocker<'_>) -> Result<CompartmentKey, KeysError> {
587		let key = match (&self.protection, unlocker) {
588			(Protection::Passphrase { params, salt }, Unlocker::Passphrase(passphrase)) => {
589				Key::from_passphrase(passphrase, salt, params)?
590			}
591			(Protection::Keystore { service, account }, Unlocker::Keystore) => {
592				let secret =
593					Zeroizing::new(keyring_core::Entry::new(service, account)?.get_secret()?);
594				Key::from_slice(&secret).ok_or(KeysError::WrongKey)?
595			}
596			_ => return Err(KeysError::WrongUnlocker),
597		};
598		let key = CompartmentKey(key);
599		self.open(name, &key)?;
600		Ok(key)
601	}
602
603	/// Decrypts the compartment's contents.
604	fn open(&self, name: &str, key: &CompartmentKey) -> Result<Zeroizing<Vec<u8>>, KeysError> {
605		self.envelope
606			.open(&key.0, &associated_data(name, &self.protection))
607			.map_err(|_| match self.protection {
608				Protection::Passphrase { .. } => KeysError::WrongPassphrase,
609				Protection::Keystore { .. } => KeysError::WrongKey,
610			})
611	}
612
613	/// Encrypts new contents with the compartment's key, after checking the key.
614	fn reseal(
615		&mut self,
616		contents: &[u8],
617		name: &str,
618		key: &CompartmentKey,
619		rng: &mut impl CryptoRng,
620	) -> Result<(), KeysError> {
621		self.open(name, key)?;
622		self.envelope = Envelope::seal(
623			&key.0,
624			contents,
625			&associated_data(name, &self.protection),
626			rng,
627		);
628		Ok(())
629	}
630}
631
632/// The associated data of a compartment: its name and its protection, so that neither can
633/// be changed without the change being noticed.
634fn associated_data(name: &str, protection: &Protection) -> Vec<u8> {
635	cbor::encode(&Value::Array(vec![name.to_cbor(), protection.to_cbor()]))
636}
637
638impl ToCbor for KeyFile {
639	fn to_cbor(&self) -> Value {
640		let mut items = vec![SUITE.to_cbor(), self.replica.to_cbor()];
641		if let Some(secrets) = &self.secrets {
642			items.push(secrets.to_cbor());
643		}
644		Value::Array(items)
645	}
646}
647
648impl FromCbor for KeyFile {
649	fn from_cbor(value: &Value) -> Result<Self, cbor::Error> {
650		const EXPECTED: &str = "a key file: [1, replica] or [1, replica, secrets]";
651		let Value::Array(items) = value else {
652			return Err(cbor::Error::Expected(EXPECTED));
653		};
654		let (suite, replica, secrets) = match items.as_slice() {
655			[suite, replica] => (suite, replica, None),
656			[suite, replica, secrets] => (suite, replica, Some(secrets)),
657			_ => return Err(cbor::Error::Expected(EXPECTED)),
658		};
659		if u8::from_cbor(suite) != Ok(SUITE) {
660			return Err(cbor::Error::Expected(EXPECTED));
661		}
662		Ok(Self {
663			replica: Compartment::from_cbor(replica)?,
664			secrets: secrets.map(Compartment::from_cbor).transpose()?,
665			obsolete: Vec::new(),
666		})
667	}
668}
669
670impl ToCbor for Protection {
671	fn to_cbor(&self) -> Value {
672		match self {
673			Self::Passphrase { params, salt } => Value::Array(vec![
674				0_u8.to_cbor(),
675				params.to_cbor(),
676				Value::Bytes(salt.to_vec()),
677			]),
678			Self::Keystore { service, account } => {
679				Value::Array(vec![1_u8.to_cbor(), service.to_cbor(), account.to_cbor()])
680			}
681		}
682	}
683}
684
685impl FromCbor for Protection {
686	fn from_cbor(value: &Value) -> Result<Self, cbor::Error> {
687		const EXPECTED: &str = "a protection: [0, parameters, salt] or [1, service, account]";
688		let error = || cbor::Error::Expected(EXPECTED);
689		let Value::Array(items) = value else {
690			return Err(error());
691		};
692		match items.as_slice() {
693			[kind, params, Value::Bytes(salt)] if u8::from_cbor(kind) == Ok(0) => {
694				Ok(Self::Passphrase {
695					params: PassphraseParams::from_cbor(params)?,
696					salt: salt.as_slice().try_into().map_err(|_| error())?,
697				})
698			}
699			[kind, service, account] if u8::from_cbor(kind) == Ok(1) => Ok(Self::Keystore {
700				service: String::from_cbor(service)?,
701				account: String::from_cbor(account)?,
702			}),
703			_ => Err(error()),
704		}
705	}
706}
707
708impl ToCbor for Compartment {
709	fn to_cbor(&self) -> Value {
710		Value::Array(vec![self.protection.to_cbor(), self.envelope.to_cbor()])
711	}
712}
713
714impl FromCbor for Compartment {
715	fn from_cbor(value: &Value) -> Result<Self, cbor::Error> {
716		const EXPECTED: &str = "a compartment: [protection, envelope]";
717		let Value::Array(items) = value else {
718			return Err(cbor::Error::Expected(EXPECTED));
719		};
720		let [protection, envelope] = items.as_slice() else {
721			return Err(cbor::Error::Expected(EXPECTED));
722		};
723		Ok(Self {
724			protection: Protection::from_cbor(protection)?,
725			envelope: Envelope::from_cbor(envelope)?,
726		})
727	}
728}