Skip to main content

nibkeep_node/library/
secrets.rs

1//! Secrets: the secrets keys of the library's spaces, which seal the values of secret
2//! fields, in the key file's secrets compartment (`docs/Design.md`, section 6.9); and
3//! giving them to the replicas that the person chooses, which ask for them with a key of
4//! their secrets compartment ([technical design](../../../../docs/Technical-design.md#12-secrets)).
5
6use std::collections::{BTreeMap, BTreeSet};
7use std::fs::File;
8use std::path::Path;
9
10use nibkeep_base::{EntityId, Hash, SpaceId};
11use nibkeep_crypto::rand_core::CryptoRng;
12use nibkeep_crypto::{DecryptionKey, EncryptionKey, Key, RecoveryCode, VerifyingKey, key_hash};
13use nibkeep_governance::{Roster, SealedSecretsKey};
14use nibkeep_keys::{
15	CompartmentKey, KeyFile, NewProtection, Protection, SealedSecrets, SecretsKeys, SpaceKeyMap,
16	Unlocker,
17};
18
19use super::recovering::RecoveredSecrets;
20use super::secrets_keys::{fresh_number, keep_given, take_given};
21use super::{INFO, KEYS, Library};
22use crate::NodeError;
23use crate::info::Info;
24
25/// Where a library's secrets are, as this replica sees them.
26#[derive(Clone, Copy, Debug, PartialEq, Eq)]
27pub enum SecretsState {
28	/// No replica has set up the secrets yet: the first secret saved sets them up here.
29	NotSetUp,
30	/// This replica holds the secrets keys, or takes those given to it when its secrets are
31	/// next unlocked.
32	Here,
33	/// This replica asked for the secrets, and waits for one that holds them to give them.
34	Asked,
35	/// Another replica holds the secrets; this one can ask for them.
36	Elsewhere,
37}
38
39/// A compartment of the key file.
40#[derive(Clone, Copy)]
41pub(super) enum Compartment {
42	/// The replica's keys.
43	Replica,
44	/// The secrets keys.
45	Secrets,
46}
47
48/// The file that writers of the key file lock, so that two of them never replace each
49/// other's keys.
50const KEYS_LOCK: &str = "keys.lock";
51
52impl Library {
53	/// How the library's secrets keys are protected, or `None` if it has none yet, as the
54	/// key file on the disk says: another program may have given them since the library was
55	/// opened.
56	///
57	/// # Errors
58	///
59	/// Returns an error if the key file cannot be read.
60	pub fn secrets_protection(&self) -> Result<Option<Protection>, NodeError> {
61		Ok(self.key_file_on_disk()?.secrets_protection().cloned())
62	}
63
64	/// Whether another replica keeps the library's secrets, which this one cannot read or
65	/// write until one that holds them gives them: it has not asked for them, or waits.
66	///
67	/// # Errors
68	///
69	/// Returns an error if the key file or a space cannot be read.
70	pub fn secrets_elsewhere(&self) -> Result<bool, NodeError> {
71		Ok(matches!(
72			self.secrets_state()?,
73			SecretsState::Asked | SecretsState::Elsewhere
74		))
75	}
76
77	/// Where the library's secrets are: here, asked for, held by another replica, or not set
78	/// up anywhere yet, as the key file on the disk and the personal space's records say. A
79	/// replica with a secrets compartment holds them, unless it asked another replica that
80	/// gave it nothing yet; one whose secrets compartment is gone, whatever its records say,
81	/// can ask for them again.
82	///
83	/// # Errors
84	///
85	/// Returns an error if the key file or a space cannot be read.
86	pub fn secrets_state(&self) -> Result<SecretsState, NodeError> {
87		let own = self.info.replica;
88		let roster = self.roster(self.info.personal)?;
89		if self.secrets_protection()?.is_some() {
90			if roster.secrets_given_to(own).next().is_some() {
91				return Ok(SecretsState::Here);
92			}
93			return Ok(match roster.secrets_from(own) {
94				Some(from) if from != own => SecretsState::Asked,
95				_ => SecretsState::Here,
96			});
97		}
98		Ok(if self.secrets_held_elsewhere(&roster)? {
99			SecretsState::Elsewhere
100		} else {
101			SecretsState::NotSetUp
102		})
103	}
104
105	/// Whether another replica that is not revoked holds the secrets, as the records give
106	/// them. Where only revoked replicas held them, their secrets are lost, and new ones may
107	/// be set up.
108	fn secrets_held_elsewhere(&self, roster: &Roster) -> Result<bool, NodeError> {
109		let own = self.info.replica;
110		for holder in roster.secrets_holders() {
111			if holder != own && self.is_remaining(self.info.personal, roster, holder)? {
112				return Ok(true);
113			}
114		}
115		Ok(false)
116	}
117
118	/// The key of the secrets compartment, which must be open, or why it is not: locked, or
119	/// not set up on this replica.
120	pub(super) fn open_compartment(&self) -> Result<CompartmentKey, NodeError> {
121		match &self.secrets_compartment {
122			Some(compartment) => Ok(compartment.clone()),
123			None if self.secrets_protection()?.is_some() => Err(NodeError::SecretsLocked),
124			None => Err(NodeError::SetUpSecretsFirst),
125		}
126	}
127
128	/// Whether a replica of a space remains: its keys are listed, and none is revoked.
129	pub(super) fn is_remaining(
130		&self,
131		space: SpaceId,
132		roster: &Roster,
133		replica: EntityId,
134	) -> Result<bool, NodeError> {
135		Ok(self
136			.remaining(space, roster, &[])?
137			.iter()
138			.any(|(remaining, _)| *remaining == replica))
139	}
140
141	/// The roster of every space.
142	pub(super) fn rosters(&self) -> Result<BTreeMap<SpaceId, Roster>, NodeError> {
143		self.secret_spaces()?
144			.into_iter()
145			.map(|space| Ok((space, self.roster(space)?)))
146			.collect()
147	}
148
149	/// Whether a space's secrets are unlocked: whether its secret values can be read and
150	/// written.
151	#[must_use]
152	pub fn secrets_unlocked(&self, space: nibkeep_base::SpaceId) -> bool {
153		self.spaces
154			.get(&space)
155			.is_some_and(|open| open.keys.newest_secrets().is_some())
156	}
157
158	/// Gives the library its secrets keys, the first time a secret is stored: a new secrets
159	/// key for the personal space, in the key file's secrets compartment, protected as
160	/// `protection` says, apart from the library's other keys, and never by the library's
161	/// own passphrase. The records then say that this replica holds them, at the time
162	/// `wall_millis`. The secrets are unlocked afterwards.
163	///
164	/// # Errors
165	///
166	/// Returns an error if the passphrase is the library's; [`NodeError::SecretsElsewhere`]
167	/// if another replica holds the secrets, which this one asks for instead; if the library
168	/// has secrets keys already, also when another program gave them since the library was
169	/// opened; if the passphrase cannot be used or the keystore fails; or if the key file
170	/// cannot be read or written, in which case nothing changed. If only the records cannot
171	/// be written, the secrets are set up all the same, and locked: the next time they are
172	/// unlocked, the records say so.
173	pub fn set_up_secrets(
174		&mut self,
175		protection: &NewProtection<'_>,
176		wall_millis: u64,
177		rng: &mut impl CryptoRng,
178	) -> Result<(), NodeError> {
179		self.check_not_ai_agent("hold secrets")?;
180		// The library's passphrase would make the two layers one.
181		if self.opens_the_other(protection, Compartment::Replica)? {
182			return Err(NodeError::LibraryPassphrase);
183		}
184		match self.secrets_state()? {
185			SecretsState::NotSetUp => {}
186			SecretsState::Here | SecretsState::Asked => return Err(NodeError::SecretsSetUp),
187			// Keys made here would seal what no other replica reads.
188			SecretsState::Elsewhere => return Err(NodeError::SecretsElsewhere),
189		}
190		// Records that do not say it holds them would have another set up secrets of its own.
191		self.check_own_key()?;
192		let decryption = DecryptionKey::generate(rng);
193		let rosters = self.rosters()?;
194		// The personal space's, of a random number, as new keys have, so that two set up at the
195		// same time differ; another space's are set up there, by an admin.
196		let personal = self.info.personal;
197		let epoch = fresh_number(&rosters[&personal].secrets_numbers(), rng);
198		let keys = SecretsKeys {
199			spaces: BTreeMap::from([(personal, BTreeMap::from([(epoch, Key::generate(rng))]))]),
200			decryption: decryption.clone(),
201		};
202		// Sealed before the key file is locked, as deriving a key from a passphrase, or a
203		// keystore's prompt, takes a while.
204		let (sealed, key) = SealedSecrets::seal(&keys, protection, rng)?;
205		self.write_sealed_secrets(sealed, key)?;
206		self.open_secrets(&keys)?;
207		let own = self.info.replica;
208		let encryption = decryption.encryption_key();
209		let stated =
210			self.state_held_secrets(&rosters, (&keys, &encryption), Some(own), wall_millis, rng);
211		if stated.is_err() {
212			self.lock_secrets();
213			return stated;
214		}
215		// Sealed with the key that the records give now.
216		let _ = self.settle_secrets_keys(wall_millis, rng);
217		Ok(())
218	}
219
220	/// Takes the secrets from a copy of a replica made elsewhere, whose secrets `unlocker`
221	/// opens, by their passphrase or their keystore entry (technical design: copies of a replica): only the
222	/// keys that the records gave the copy's replica, by number and hash, so that no key of
223	/// another's making is taken, as a replica takes keys given to it. This replica then
224	/// holds them, in its secrets compartment, protected as `protection` says, and the
225	/// records say so, as when a replica sets up the secrets. The copy is only read. Returns
226	/// how many keys it took. The secrets are unlocked afterwards.
227	///
228	/// # Errors
229	///
230	/// Returns an error if the passphrase is the library's; [`NodeError::SecretsSetUp`] if
231	/// this replica holds the secrets or asked for them already; an error of the keys if
232	/// `unlocker` does not open the copy's secrets; [`NodeError::NoSecretsInCopy`] if they
233	/// hold none of the keys that the records gave the copy's replica;
234	/// [`NodeError::NewerFormats`] if a later version of NibKeep changed the copy; and the
235	/// errors of [`Library::set_up_secrets`].
236	pub fn take_secrets_from_copy(
237		&mut self,
238		copy: &Path,
239		unlocker: &Unlocker<'_>,
240		protection: &NewProtection<'_>,
241		wall_millis: u64,
242		rng: &mut impl CryptoRng,
243	) -> Result<usize, NodeError> {
244		self.check_not_ai_agent("hold secrets")?;
245		if self.opens_the_other(protection, Compartment::Replica)? {
246			return Err(NodeError::LibraryPassphrase);
247		}
248		if matches!(
249			self.secrets_state()?,
250			SecretsState::Here | SecretsState::Asked
251		) {
252			return Err(NodeError::SecretsSetUp);
253		}
254		self.check_own_key()?;
255		// A copy that a later version changed is read by none of its files.
256		crate::engines::check(copy)?;
257		let key_file = KeyFile::read(&copy.join(KEYS))?;
258		let copied = key_file.secrets(&key_file.unlock_secrets(unlocker)?)?;
259		let replica = Info::read(&copy.join(INFO))?.replica;
260		let rosters = self.rosters()?;
261		// The copy's keys that the records gave its replica, by number and hash: from the
262		// replica it asked, or with a link that a key kept checks.
263		let Some(copy_key) = rosters
264			.get(&self.info.personal)
265			.and_then(|roster| roster.own_key_of(replica))
266			.copied()
267		else {
268			return Err(NodeError::NoSecretsInCopy);
269		};
270		let given = self.secrets_given(&rosters, Some(&copy_key), None)?;
271		let spaces = keep_given(&given, &copied.spaces);
272		let taken = spaces.values().map(BTreeMap::len).sum();
273		if taken == 0 {
274			return Err(NodeError::NoSecretsInCopy);
275		}
276		self.hold_taken_secrets(&rosters, spaces, protection, wall_millis, rng)?;
277		// A copy of a device that was revoked holds no safe key: a new one, now that the
278		// records say this replica holds them.
279		let _ = self.settle_secrets_keys(wall_millis, rng);
280		Ok(taken)
281	}
282
283	/// Takes the secrets that the recovery code `code` holds, on a replica that recovers with
284	/// it, which holds no secrets yet: the keys that the replica which made the code gave it,
285	/// and those linked with them, as [`Library::code_secrets_given`] says, so that no key of
286	/// another's making is taken. This replica then holds them, in its secrets compartment,
287	/// protected as `protection` says, and the records say so, as when it takes a copy's
288	/// secrets; they are unlocked afterwards. Without `protection`, as the person chose, it
289	/// takes none ([technical design](../../../../docs/Technical-design.md#111-recovery-codes)).
290	/// [`Recovering::finish`] checks first that `protection` is not the library's passphrase.
291	///
292	/// # Errors
293	///
294	/// Returns an error if the key file or a change cannot be saved.
295	///
296	/// [`Recovering::finish`]: super::recovering::Recovering::finish
297	pub(super) fn take_code_secrets(
298		&mut self,
299		code: &RecoveryCode,
300		protection: Option<&NewProtection<'_>>,
301		wall_millis: u64,
302		rng: &mut impl CryptoRng,
303	) -> Result<RecoveredSecrets, NodeError> {
304		let rosters = self.rosters()?;
305		let spaces = self.secrets_code_opens(&rosters, code)?;
306		let taken = spaces.values().map(BTreeMap::len).sum();
307		if taken == 0 {
308			return Ok(if self.lost_devices_held_secrets(&rosters)? {
309				RecoveredSecrets::NotInCode
310			} else {
311				RecoveredSecrets::NoneHeld
312			});
313		}
314		let Some(protection) = protection else {
315			return Ok(RecoveredSecrets::Left);
316		};
317		self.hold_taken_secrets(&rosters, spaces, protection, wall_millis, rng)?;
318		Ok(RecoveredSecrets::Taken { keys: taken })
319	}
320
321	/// Whether, before a recovery revokes them, the person's other replicas held secrets: a
322	/// replica that the records say holds them, and that is listed and not revoked. Secrets
323	/// that only revoked replicas held were lost before.
324	fn lost_devices_held_secrets(
325		&self,
326		rosters: &BTreeMap<SpaceId, Roster>,
327	) -> Result<bool, NodeError> {
328		let personal = self.info.personal;
329		let Some(roster) = rosters.get(&personal) else {
330			return Ok(false);
331		};
332		let holders = roster.secrets_holders();
333		let open = self.space(personal)?;
334		let log = open.stored.log();
335		for holder in holders {
336			if holder == self.info.replica {
337				continue;
338			}
339			let keys = roster.keys_of(holder);
340			let mut stands = !keys.is_empty();
341			for key in keys {
342				stands &= log.is_listed(key, &open.keys)? && !log.is_revoked(key, &open.keys)?;
343			}
344			if stands {
345				return Ok(true);
346			}
347		}
348		Ok(false)
349	}
350
351	/// Makes this replica's secrets compartment, which it did not have, with `spaces`, the
352	/// secrets keys that it took from elsewhere, and a new key to receive with, protected as
353	/// `protection` says; then states on its records, as `rosters` have them, that it holds
354	/// them and takes them from itself, as when it sets up the secrets. They are unlocked
355	/// afterwards, but if the records cannot be written.
356	fn hold_taken_secrets(
357		&mut self,
358		rosters: &BTreeMap<SpaceId, Roster>,
359		spaces: SpaceKeyMap,
360		protection: &NewProtection<'_>,
361		wall_millis: u64,
362		rng: &mut impl CryptoRng,
363	) -> Result<(), NodeError> {
364		let decryption = DecryptionKey::generate(rng);
365		let keys = SecretsKeys {
366			spaces,
367			decryption: decryption.clone(),
368		};
369		// Sealed before the key file is locked, as deriving a key from a passphrase, or a
370		// keystore's prompt, takes a while.
371		let (sealed, key) = SealedSecrets::seal(&keys, protection, rng)?;
372		self.write_sealed_secrets(sealed, key)?;
373		self.open_secrets(&keys)?;
374		let own = self.info.replica;
375		let encryption = decryption.encryption_key();
376		let stated =
377			self.state_held_secrets(rosters, (&keys, &encryption), Some(own), wall_millis, rng);
378		if stated.is_err() {
379			self.lock_secrets();
380		}
381		stated
382	}
383
384	/// Whether this replica may ask for the secrets from `from`: it holds none, while `from`
385	/// does, is not this one, and is not revoked. A replica that asked already may name
386	/// another, with [`Library::ask_secrets_from`].
387	///
388	/// # Errors
389	///
390	/// Returns [`NodeError::SecretsNowhere`] if no replica holds the secrets yet,
391	/// [`NodeError::SecretsSetUp`] if this one does, [`NodeError::SecretsAsked`] if it asked
392	/// already, [`NodeError::WhichDevice`] if `from` holds none, as the records say, or is
393	/// revoked; [`NodeError::ForeignKey`] if this replica's record lists a key that it did
394	/// not make; and an error if this replica is an AI agent's, or the library cannot be
395	/// read.
396	pub fn check_may_ask(&self, from: EntityId) -> Result<(), NodeError> {
397		self.check_not_ai_agent("hold secrets")?;
398		match self.secrets_state()? {
399			SecretsState::NotSetUp => return Err(NodeError::SecretsNowhere),
400			SecretsState::Here => return Err(NodeError::SecretsSetUp),
401			SecretsState::Asked => return Err(NodeError::SecretsAsked),
402			SecretsState::Elsewhere => {}
403		}
404		self.check_holder(from)?;
405		self.check_own_key()
406	}
407
408	/// Whether this replica's key is its own in the personal space, as only then does what it
409	/// says of the secrets count: the only key on its record, listed on no other.
410	fn check_own_key(&self) -> Result<(), NodeError> {
411		let own = self.replica.signing.verifying_key();
412		if self.roster(self.info.personal)?.owner_of(&own) == Some(self.info.replica) {
413			Ok(())
414		} else {
415			Err(NodeError::ForeignKey)
416		}
417	}
418
419	/// Whether `from` holds the secrets, as the records give them, and is not revoked.
420	fn check_holder(&self, from: EntityId) -> Result<(), NodeError> {
421		let roster = self.roster(self.info.personal)?;
422		if from == self.info.replica
423			|| !roster.secrets_holders().contains(&from)
424			|| !self.is_remaining(self.info.personal, &roster, from)?
425		{
426			return Err(NodeError::WhichDevice(
427				"that device does not hold the secrets, or has not said so yet: unlock its \
428				 secrets once"
429					.to_owned(),
430			));
431		}
432		Ok(())
433	}
434
435	/// Asks for the secrets that another replica holds, from `from`, which the person
436	/// chose: states, at the time `wall_millis`, a new key that opens what is sealed to it,
437	/// and that it takes the secrets from `from` alone; then makes this replica's secrets
438	/// compartment, protected as `protection` says, and never by the library's passphrase,
439	/// with that key and no secrets keys yet. When the person chooses to, `from` gives them,
440	/// and this replica takes them while its secrets are unlocked. They are unlocked
441	/// afterwards.
442	///
443	/// # Errors
444	///
445	/// Returns the errors of [`Library::check_may_ask`]; an error if the passphrase is the
446	/// library's, cannot be used, or the keystore fails; or if the key file cannot be read or
447	/// written. If the compartment cannot be written after the records were, the replica can
448	/// ask again.
449	pub fn ask_for_secrets(
450		&mut self,
451		from: EntityId,
452		protection: &NewProtection<'_>,
453		wall_millis: u64,
454		rng: &mut impl CryptoRng,
455	) -> Result<(), NodeError> {
456		self.check_may_ask(from)?;
457		if self.opens_the_other(protection, Compartment::Replica)? {
458			return Err(NodeError::LibraryPassphrase);
459		}
460		let decryption = DecryptionKey::generate(rng);
461		let keys = SecretsKeys {
462			spaces: SpaceKeyMap::new(),
463			decryption: decryption.clone(),
464		};
465		// Sealed first, as the person may turn a keystore's prompt down, which then leaves no
466		// request for a key that nothing holds.
467		let (sealed, key) = SealedSecrets::seal(&keys, protection, rng)?;
468		// Stated before it is written: a compartment that the records name no key of would
469		// hold the secrets of a replica that never asked.
470		let rosters = self.rosters()?;
471		let encryption = decryption.encryption_key();
472		self.state_held_secrets(&rosters, (&keys, &encryption), Some(from), wall_millis, rng)?;
473		self.write_sealed_secrets(sealed, key)
474	}
475
476	/// Asks for the secrets from another replica than the one this one asked first, which
477	/// may have been lost: it takes them from `from` alone from now on.
478	///
479	/// # Errors
480	///
481	/// Returns [`NodeError::NotAsked`] if this replica did not ask for the secrets,
482	/// [`NodeError::WhichDevice`] if `from` holds none or is revoked, and an error if the
483	/// change cannot be saved.
484	pub fn ask_secrets_from(
485		&mut self,
486		from: EntityId,
487		wall_millis: u64,
488		rng: &mut impl CryptoRng,
489	) -> Result<(), NodeError> {
490		if self.secrets_state()? != SecretsState::Asked {
491			return Err(NodeError::NotAsked);
492		}
493		self.check_holder(from)?;
494		self.check_own_key()?;
495		let own = self.info.replica;
496		let personal = self.info.personal;
497		let roster = self.roster(personal)?;
498		if roster.keys_of(own).is_empty() || roster.secrets_from(own) == Some(from) {
499			return Ok(());
500		}
501		let operation = nibkeep_governance::state_secrets_from(own, from, rng);
502		self.commit(personal, vec![operation], wall_millis, rng)
503	}
504
505	/// After the first sync of a replica that asked for the secrets as it joined: states, at
506	/// the time `wall_millis`, that it takes them from the replica that added it, whose key
507	/// is `sponsor`, with the key of the secrets compartment it made, and takes those given;
508	/// only its own key may say whom it asks. If the records do not say that the replica that
509	/// added it holds the secrets, or this one is an AI agent's, it removes the compartment,
510	/// which holds none. Returns whether it asked.
511	pub(crate) fn ask_as_joined(
512		&mut self,
513		sponsor: &VerifyingKey,
514		wall_millis: u64,
515		rng: &mut impl CryptoRng,
516	) -> Result<bool, NodeError> {
517		let roster = self.roster(self.info.personal)?;
518		let from = roster
519			.owner_of(sponsor)
520			.filter(|&from| roster.secrets_holders().contains(&from));
521		let keys = match (&self.secrets_compartment, from) {
522			(Some(compartment), Some(_)) if !self.is_ai_agent()? => {
523				Some(self.key_file_on_disk()?.secrets(compartment)?)
524			}
525			_ => None,
526		};
527		let Some(keys) = keys else {
528			self.remove_secrets_compartment()?;
529			return Ok(false);
530		};
531		let encryption = keys.decryption.encryption_key();
532		let rosters = self.rosters()?;
533		self.state_held_secrets(&rosters, (&keys, &encryption), from, wall_millis, rng)?;
534		self.settle_secrets(wall_millis, rng)?;
535		Ok(true)
536	}
537
538	/// Locks the secrets, and removes the secrets compartment from the key file.
539	fn remove_secrets_compartment(&mut self) -> Result<(), NodeError> {
540		self.lock_secrets();
541		self.update_key_file(|key_file| {
542			key_file.remove_secrets();
543			Ok(())
544		})
545	}
546
547	/// Writes a secrets compartment sealed apart in the key file as it is on the disk, unless
548	/// it has one, and keeps it open. One that is not written leaves nothing in the keystore.
549	fn write_sealed_secrets(
550		&mut self,
551		sealed: SealedSecrets,
552		key: CompartmentKey,
553	) -> Result<(), NodeError> {
554		let mut sealed = Some(sealed);
555		self.update_key_file(|key_file| {
556			if key_file.secrets_protection().is_some() {
557				return Err(NodeError::SecretsSetUp);
558			}
559			if let Some(sealed) = sealed.take() {
560				key_file.put_secrets(sealed);
561			}
562			Ok(())
563		})?;
564		self.secrets_compartment = Some(key);
565		Ok(())
566	}
567
568	/// Gives the secrets keys this replica holds to `replica`, which asked for them from this
569	/// one, sealed to the key it asked with, at the time `wall_millis`: in each space that
570	/// both are replicas of, those keys that it was not given yet. The secrets must be
571	/// unlocked: the person confirmed. It checks all of it before it gives any. Returns how
572	/// many keys it gave.
573	///
574	/// # Errors
575	///
576	/// Returns [`NodeError::SecretsLocked`] if the secrets are locked, and
577	/// [`NodeError::SecretsElsewhere`] or [`NodeError::SecretsNowhere`] if this replica holds
578	/// none; [`NodeError::NotAsked`] if `replica` did not ask for them;
579	/// [`NodeError::WhichDevice`] if it asked another, or is this one, an AI agent's,
580	/// revoked, or no replica of the user's; [`NodeError::ForeignKey`] if this replica's
581	/// record lists a key that it did not make, so that what it gives would not count; and
582	/// an error if a change cannot be saved, in which case the spaces before it were given
583	/// theirs.
584	pub fn give_secrets(
585		&mut self,
586		replica: EntityId,
587		wall_millis: u64,
588		rng: &mut impl CryptoRng,
589	) -> Result<usize, NodeError> {
590		self.check_not_ai_agent("give secrets")?;
591		let personal = self.info.personal;
592		let own = self.info.replica;
593		if !self.secrets_unlocked(personal) {
594			return Err(match self.secrets_state()? {
595				SecretsState::Here => NodeError::SecretsLocked,
596				SecretsState::NotSetUp => NodeError::SecretsNowhere,
597				SecretsState::Asked | SecretsState::Elsewhere => NodeError::SecretsElsewhere,
598			});
599		}
600		if replica == own {
601			return Err(NodeError::WhichDevice(
602				"this device holds the secrets already".to_owned(),
603			));
604		}
605		let rosters = self.rosters()?;
606		let roster = &rosters[&personal];
607		if roster.keys_of(replica).is_empty() {
608			return Err(NodeError::WhichDevice(
609				"that is no device of yours".to_owned(),
610			));
611		}
612		let open = self.space(personal)?;
613		for key in roster.keys_of(replica) {
614			if open.stored.log().is_ai_agent(key, &open.keys)? {
615				return Err(NodeError::WhichDevice(
616					"an AI agent never gets the secrets".to_owned(),
617				));
618			}
619		}
620		if !self.is_remaining(personal, roster, replica)? {
621			return Err(NodeError::WhichDevice("that device is revoked".to_owned()));
622		}
623		match (
624			roster.secrets_encryption_of(replica),
625			roster.secrets_from(replica),
626		) {
627			(Some(_), Some(from)) if from == own => {}
628			(Some(_), Some(_)) => {
629				return Err(NodeError::WhichDevice(
630					"that device asks another of yours for the secrets".to_owned(),
631				));
632			}
633			_ => return Err(NodeError::NotAsked),
634		}
635		self.check_own_key()?;
636		let mut changes = Vec::new();
637		for (&space, roster) in &rosters {
638			// A space where it has not asked yet: it asks there as it next settles.
639			let Some(encryption) = roster
640				.secrets_encryption_of(replica)
641				.filter(|_| roster.secrets_from(replica) == Some(own))
642			else {
643				continue;
644			};
645			let held = self.space(space)?.keys.secrets_keys();
646			let has = given_by_the_one_asked(roster, replica);
647			let operations = gifts(&has, (space, replica), encryption, held, rng);
648			if !operations.is_empty() {
649				changes.push((space, operations));
650			}
651		}
652		let given = changes.iter().map(|(_, operations)| operations.len()).sum();
653		for (space, operations) in changes {
654			self.commit(space, operations, wall_millis, rng)?;
655		}
656		Ok(given)
657	}
658
659	/// Asks for the secrets of a shared space from `from`, the record there of a replica of
660	/// another member that holds them, which the person chose: states, at the time
661	/// `wall_millis`, this replica's secrets encryption key in the space and that it takes the
662	/// space's secrets from `from`. When the person of `from` chooses to, it gives them, with
663	/// [`Library::give_space_secrets`], and this replica takes them while its secrets are
664	/// unlocked. This user's own replicas pass a space's secrets on to each other by
665	/// themselves, and need not ask.
666	///
667	/// # Errors
668	///
669	/// Returns [`NodeError::NeverShared`] for a space with no members,
670	/// [`NodeError::SetUpSecretsFirst`] if this replica has no secrets compartment,
671	/// [`NodeError::SecretsLocked`] if it is locked, [`NodeError::SecretsSetUp`] if this
672	/// replica holds the space's secrets, [`NodeError::WhichDevice`] if `from` holds none, as
673	/// the records say, or is this replica or ended there, [`NodeError::Removed`] if this
674	/// replica's member left or was removed, [`NodeError::ForeignKey`] if its record lists a
675	/// key it did not make, and an error if this replica is an AI agent's or the change
676	/// cannot be saved.
677	pub fn ask_for_space_secrets(
678		&mut self,
679		space: SpaceId,
680		from: EntityId,
681		wall_millis: u64,
682		rng: &mut impl CryptoRng,
683	) -> Result<(), NodeError> {
684		self.check_not_ai_agent("hold secrets")?;
685		self.check_shared(space)?;
686		self.check_not_revoked(space)?;
687		let own_key = self.replica.signing.verifying_key();
688		{
689			let open = self.space(space)?;
690			if open.stored.log().is_removed(&own_key, &open.keys)? {
691				return Err(NodeError::Removed);
692			}
693		}
694		let compartment = self.open_compartment()?;
695		if self.secrets_unlocked(space) {
696			return Err(NodeError::SecretsSetUp);
697		}
698		let roster = self.roster(space)?;
699		let own = self.own_record(space)?;
700		let holds =
701			roster.secrets_holders().contains(&from) && self.is_remaining(space, &roster, from)?;
702		if from == own || !holds {
703			return Err(NodeError::WhichDevice(
704				"that device does not hold this space's secrets".to_owned(),
705			));
706		}
707		if roster.owner_of(&own_key) != Some(own) {
708			return Err(NodeError::ForeignKey);
709		}
710		let encryption = self
711			.key_file_on_disk()?
712			.secrets(&compartment)?
713			.decryption
714			.encryption_key();
715		let mut operations = Vec::new();
716		if roster.secrets_encryption_of(own) != Some(&encryption) {
717			operations.push(nibkeep_governance::state_secrets_key(own, &encryption, rng));
718		}
719		if roster.secrets_from(own) != Some(from) {
720			operations.push(nibkeep_governance::state_secrets_from(own, from, rng));
721		}
722		if operations.is_empty() {
723			return Ok(());
724		}
725		self.commit(space, operations, wall_millis, rng)
726	}
727
728	/// Gives the secrets of a shared space that this replica holds to `replica`, the record
729	/// there of another member's replica that asked this one for them, sealed to the key it
730	/// asked with, at the time `wall_millis`: those keys it was not given yet. The secrets
731	/// must be unlocked: the person confirmed. From then on this replica gives it the space's
732	/// new keys by itself, as it does to every replica known to hold them. Returns how many
733	/// keys it gave.
734	///
735	/// # Errors
736	///
737	/// Returns [`NodeError::NeverShared`] for a space with no members,
738	/// [`NodeError::SecretsLocked`] if the secrets are locked,
739	/// [`NodeError::SpaceSecretsElsewhere`] if this replica holds none of the space's;
740	/// [`NodeError::NotAsked`] if `replica` did not ask for them; [`NodeError::WhichDevice`]
741	/// if it asked another, or is this one, an AI agent's, or ended or no replica of the
742	/// space; [`NodeError::ForeignKey`] if this replica's record lists a key it did not make;
743	/// and an error if the change cannot be saved.
744	pub fn give_space_secrets(
745		&mut self,
746		space: SpaceId,
747		replica: EntityId,
748		wall_millis: u64,
749		rng: &mut impl CryptoRng,
750	) -> Result<usize, NodeError> {
751		self.check_not_ai_agent("give secrets")?;
752		self.check_shared(space)?;
753		self.check_not_revoked(space)?;
754		{
755			let open = self.space(space)?;
756			let own_key = self.replica.signing.verifying_key();
757			if open.stored.log().is_removed(&own_key, &open.keys)? {
758				return Err(NodeError::Removed);
759			}
760		}
761		if !self.secrets_unlocked(space) {
762			return Err(if self.secrets_compartment.is_some() {
763				NodeError::SpaceSecretsElsewhere
764			} else {
765				NodeError::SecretsLocked
766			});
767		}
768		let roster = self.roster(space)?;
769		let own = self.own_record(space)?;
770		if replica == own {
771			return Err(NodeError::WhichDevice(
772				"this device holds the secrets already".to_owned(),
773			));
774		}
775		if roster.keys_of(replica).is_empty() {
776			return Err(NodeError::WhichDevice(
777				"that is no device of the space".to_owned(),
778			));
779		}
780		{
781			let open = self.space(space)?;
782			for key in roster.keys_of(replica) {
783				if open.stored.log().is_ai_agent(key, &open.keys)? {
784					return Err(NodeError::WhichDevice(
785						"an AI agent never gets the secrets".to_owned(),
786					));
787				}
788			}
789		}
790		if !self.is_remaining(space, &roster, replica)? {
791			return Err(NodeError::WhichDevice(
792				"that device left the space, or was removed or revoked".to_owned(),
793			));
794		}
795		let encryption = match (
796			roster.secrets_encryption_of(replica),
797			roster.secrets_from(replica),
798		) {
799			(Some(encryption), Some(from)) if from == own => encryption.clone(),
800			(Some(_), Some(_)) => {
801				return Err(NodeError::WhichDevice(
802					"that device asks another for the secrets".to_owned(),
803				));
804			}
805			_ => return Err(NodeError::NotAsked),
806		};
807		if roster.owner_of(&self.replica.signing.verifying_key()) != Some(own) {
808			return Err(NodeError::ForeignKey);
809		}
810		let has = given_by_the_one_asked(&roster, replica);
811		let held = self.space(space)?.keys.secrets_keys();
812		let operations = gifts(&has, (space, replica), &encryption, held, rng);
813		let given = operations.len();
814		if given > 0 {
815			self.commit(space, operations, wall_millis, rng)?;
816		}
817		Ok(given)
818	}
819
820	/// While the secrets compartment is open: takes the secrets keys given to this replica,
821	/// by the replica it takes the secrets from, sealed to the key it asked with, if their
822	/// hashes are those stated; saves them, and opens the secret values. Then states,
823	/// at the time `wall_millis`, what the records do not say yet: that key, the replica it
824	/// takes the secrets from, and for one that set them up, the keys it holds; if that
825	/// cannot be saved, the next time tries again. A compartment that holds no secrets keys,
826	/// for a key that the records do not say it asks with, is removed, so that the replica can
827	/// ask anew: one that joined and stopped before it said so, or whose record lists a key
828	/// that it did not make. Does nothing while the compartment is closed, and on a replica
829	/// that is an AI agent's, revoked or not listed; if another program protected the
830	/// secrets anew, they are locked.
831	///
832	/// # Errors
833	///
834	/// Returns an error if the key file or a space cannot be read, or the keys taken saved.
835	pub fn settle_secrets(
836		&mut self,
837		wall_millis: u64,
838		rng: &mut impl CryptoRng,
839	) -> Result<(), NodeError> {
840		let Some(compartment) = self.secrets_compartment.clone() else {
841			return Ok(());
842		};
843		if self.is_ai_agent()? || !matches!(self.is_revoked(), Ok(false)) {
844			return Ok(());
845		}
846		let Ok(mut keys) = self.key_file_on_disk()?.secrets(&compartment) else {
847			// Another program protected them anew: they are locked until unlocked again.
848			self.lock_secrets();
849			return Ok(());
850		};
851		let own = self.info.replica;
852		let rosters = self.rosters()?;
853		if keys.spaces.is_empty()
854			&& rosters.get(&self.info.personal).is_some_and(|roster| {
855				roster.secrets_encryption_of(own) != Some(&keys.decryption.encryption_key())
856					|| roster.secrets_from(own).is_none()
857			}) {
858			return self.remove_secrets_compartment();
859		}
860		// The keys given to it: by the replica it asked, or with a link that a key it holds
861		// checks, from any replica.
862		let recipient = nibkeep_governance::secrets_recipient(&keys.decryption.encryption_key());
863		let given = self.secrets_given(&rosters, None, Some(recipient))?;
864		// Written only for a key that opens and is not held: a key that does not open is left
865		// alone, each time.
866		if take_given(&given, &mut keys.clone()) > 0 {
867			// Read again and written while no other program writes the key file.
868			let mut taken = None;
869			self.update_key_file(|key_file| {
870				let mut keys = key_file.secrets(&compartment)?;
871				take_given(&given, &mut keys);
872				keys.spaces.retain(|_, held| !held.is_empty());
873				key_file.update_secrets(&keys, &compartment, rng)?;
874				taken = Some(keys);
875				Ok(())
876			})?;
877			if let Some(taken) = taken {
878				keys = taken;
879				self.open_secrets(&keys)?;
880			}
881		}
882		// The replica it asked, in every space; a replica whose records do not say so yet, as
883		// when setting up its secrets was cut short, takes them from itself.
884		let from = rosters
885			.get(&self.info.personal)
886			.and_then(|roster| roster.secrets_from(own))
887			.or_else(|| keys.spaces.contains_key(&self.info.personal).then_some(own));
888		let encryption = keys.decryption.encryption_key();
889		let _ = self.state_held_secrets(&rosters, (&keys, &encryption), from, wall_millis, rng);
890		// A new secrets key where none is safe, and the keys it holds to the replicas known to
891		// hold the secrets that lack them; what fails, the next time tries again.
892		let _ = self.settle_secrets_keys(wall_millis, rng);
893		Ok(())
894	}
895
896	/// States on this replica's record, in each space where its key is its own, what the
897	/// records do not say yet: its secrets encryption key, in the personal space the replica
898	/// it takes the secrets from, if `from` names one, and, where it takes them from itself,
899	/// the secrets keys of `keys` sealed to it; in one change of each space. Where another key is listed on its
900	/// record, nothing it says of the secrets counts, so it says nothing.
901	fn state_held_secrets(
902		&mut self,
903		rosters: &BTreeMap<SpaceId, Roster>,
904		(keys, encryption): (&SecretsKeys, &EncryptionKey),
905		from: Option<EntityId>,
906		wall_millis: u64,
907		rng: &mut impl CryptoRng,
908	) -> Result<(), NodeError> {
909		let personal = self.info.personal;
910		let own_key = self.replica.signing.verifying_key();
911		// The personal space first, whose errors are told; another space where this fails
912		// says it the next time its secrets settle.
913		let mut spaces: Vec<SpaceId> = rosters.keys().copied().collect();
914		spaces.sort_by_key(|&space| space != personal);
915		for space in spaces {
916			let roster = &rosters[&space];
917			// Another space this replica left, or that cannot be read now, says nothing.
918			let ended =
919				|| -> Result<bool, NodeError> {
920					let open = self.space(space)?;
921					let log = open.stored.log();
922					Ok(log.is_revoked(&own_key, &open.keys)?
923						|| log.is_removed(&own_key, &open.keys)?)
924				};
925			if space != personal && !matches!(ended(), Ok(false)) {
926				continue;
927			}
928			let own = match self.own_record(space) {
929				Ok(own) => own,
930				Err(error) if space == personal => return Err(error),
931				Err(_) => continue,
932			};
933			if roster.owner_of(&own_key) != Some(own) {
934				continue;
935			}
936			let mut operations = Vec::new();
937			let anew = roster.secrets_encryption_of(own) != Some(encryption);
938			if anew {
939				operations.push(nibkeep_governance::state_secrets_key(own, encryption, rng));
940			}
941			// Whom it asked, the personal space says; in another, the replica that gave it a key
942			// it holds, as from any replica with a link, so that the records say it holds them.
943			let from = if space == personal {
944				from
945			} else if roster.secrets_from(own).is_none() && !anew {
946				let held = keys.spaces.get(&space);
947				let recipient = nibkeep_governance::secrets_recipient(encryption);
948				roster
949					.secrets_gifts(own)
950					.iter()
951					.filter(|gift| {
952						gift.counts && gift.sealed.recipient == recipient && gift.author != own_key
953					})
954					.filter(|gift| {
955						held.and_then(|held| held.get(&gift.sealed.epoch))
956							.is_some_and(|key| key_hash(key) == gift.sealed.hash)
957					})
958					.find_map(|gift| roster.replica_of(&gift.author))
959			} else {
960				None
961			};
962			if let Some(from) = from
963				&& roster.secrets_from(own) != Some(from)
964			{
965				operations.push(nibkeep_governance::state_secrets_from(own, from, rng));
966			}
967			if from.or(roster.secrets_from(own)) == Some(own) {
968				let held = keys.spaces.get(&space).into_iter().flatten();
969				let held = held.map(|(&epoch, key)| (epoch, key));
970				// Those that no statement gives it, as others may have, with a link; keys given
971				// to the key before count no more.
972				let recipient = nibkeep_governance::secrets_recipient(encryption);
973				let stated: BTreeSet<(u64, Hash)> = roster
974					.secrets_gifts(own)
975					.iter()
976					.filter(|gift| !anew && gift.counts && gift.sealed.recipient == recipient)
977					.map(|gift| (gift.sealed.epoch, gift.sealed.hash))
978					.collect();
979				operations.extend(gifts(&stated, (space, own), encryption, held, rng));
980			}
981			if !operations.is_empty() {
982				let committed = self.commit(space, operations, wall_millis, rng);
983				if space == personal {
984					committed?;
985				}
986			}
987		}
988		Ok(())
989	}
990
991	/// Unlocks the secrets: the secrets keys, after the person has confirmed, which open
992	/// the secret values of the spaces and seal new ones. Lock them again soon, with
993	/// [`Library::lock_secrets`]. Secrets keys that another replica gave this one since are
994	/// taken by [`Library::settle_secrets`], which apps call next.
995	///
996	/// # Errors
997	///
998	/// Returns an error if the library has no secrets compartment, `unlocker` does not
999	/// unlock it, or the key file cannot be read. A replica that asked for the secrets, and
1000	/// was not given them yet, unlocks a compartment without keys.
1001	pub fn unlock_secrets(&mut self, unlocker: &Unlocker<'_>) -> Result<(), NodeError> {
1002		let key = Self::secrets_key(&self.directory, unlocker)?;
1003		self.unlock_secrets_with(&key)
1004	}
1005
1006	/// The key of the secrets of the library in `directory`, after the person has confirmed,
1007	/// without opening the library: a keystore's prompt may take a while, during which other
1008	/// programs may use the library. [`Library::unlock_secrets_with`] unlocks them with it.
1009	///
1010	/// # Errors
1011	///
1012	/// Returns an error if the library has no secrets compartment, `unlocker` does not
1013	/// unlock it, or the key file cannot be read.
1014	pub fn secrets_key(
1015		directory: &Path,
1016		unlocker: &Unlocker<'_>,
1017	) -> Result<CompartmentKey, NodeError> {
1018		Ok(KeyFile::read(&directory.join(KEYS))?.unlock_secrets(unlocker)?)
1019	}
1020
1021	/// Unlocks the secrets with their key, as [`Library::unlock_secrets`] does.
1022	///
1023	/// # Errors
1024	///
1025	/// Returns an error if the library has no secrets compartment, `key` does not open it, as
1026	/// when another program protected it anew since, or the key file cannot be read.
1027	pub fn unlock_secrets_with(&mut self, key: &CompartmentKey) -> Result<(), NodeError> {
1028		// Another program may have given the library its secrets keys since it was opened.
1029		let keys = self.key_file_on_disk()?.secrets(key)?;
1030		self.open_secrets(&keys)?;
1031		self.secrets_compartment = Some(key.clone());
1032		Ok(())
1033	}
1034
1035	/// Unlocks the secrets with the key that a library opened again from [`Closed`] kept,
1036	/// if it kept one: whether they are unlocked now. If another program protected them anew
1037	/// since, the key opens them no longer, and is forgotten.
1038	///
1039	/// # Errors
1040	///
1041	/// Returns an error if the key file cannot be read, or the secret values cannot be
1042	/// opened.
1043	///
1044	/// [`Closed`]: crate::Closed
1045	pub fn unlock_kept_secrets(&mut self) -> Result<bool, NodeError> {
1046		let personal = self.personal_space();
1047		if self.secrets_unlocked(personal) {
1048			return Ok(true);
1049		}
1050		let Some(compartment) = self.secrets_compartment.clone() else {
1051			return Ok(false);
1052		};
1053		let Ok(keys) = self.key_file_on_disk()?.secrets(&compartment) else {
1054			self.secrets_compartment = None;
1055			return Ok(false);
1056		};
1057		self.open_secrets(&keys)?;
1058		self.secrets_compartment = Some(compartment);
1059		// A replica that asked holds no keys until they are given.
1060		Ok(self.secrets_unlocked(personal))
1061	}
1062
1063	/// Locks the secrets: forgets the secrets keys and the secret values they opened.
1064	pub fn lock_secrets(&mut self) {
1065		self.secrets_compartment = None;
1066		for open in self.spaces.values_mut() {
1067			open.keys.forget_secrets();
1068			open.stored.lock_secrets();
1069		}
1070	}
1071
1072	/// Gives the spaces their secrets keys, and opens their secret values.
1073	pub(super) fn open_secrets(&mut self, keys: &SecretsKeys) -> Result<(), NodeError> {
1074		for (space, epochs) in &keys.spaces {
1075			let Some(open) = self.spaces.get_mut(space) else {
1076				continue;
1077			};
1078			for (&epoch, key) in epochs {
1079				open.keys.insert_secrets(epoch, key.clone());
1080			}
1081			if let Err(error) = open.stored.unlock_secrets(&open.keys) {
1082				self.lock_secrets();
1083				return Err(error.into());
1084			}
1085		}
1086		// Each seals new secret values with its newest safe key.
1087		for &space in keys.spaces.keys() {
1088			if self.spaces.contains_key(&space) {
1089				let chosen = self
1090					.roster(space)
1091					.and_then(|roster| self.choose_secrets_key_with(space, &roster));
1092				if let Err(error) = chosen {
1093					self.lock_secrets();
1094					return Err(error);
1095				}
1096			}
1097		}
1098		Ok(())
1099	}
1100
1101	/// The key file as it is on the disk.
1102	pub(super) fn key_file_on_disk(&self) -> Result<KeyFile, NodeError> {
1103		Ok(KeyFile::read(&self.directory.join(KEYS))?)
1104	}
1105
1106	/// Whether a new passphrase for one compartment opens the other, the replica's or the
1107	/// secrets', as the key file on the disk has them: the two would then be one layer.
1108	pub(super) fn opens_the_other(
1109		&self,
1110		protection: &NewProtection<'_>,
1111		other: Compartment,
1112	) -> Result<bool, NodeError> {
1113		let NewProtection::Passphrase(passphrase, _) = protection else {
1114			return Ok(false);
1115		};
1116		let key_file = self.key_file_on_disk()?;
1117		let unlocker = Unlocker::Passphrase(passphrase);
1118		Ok(match other {
1119			Compartment::Replica => {
1120				matches!(key_file.replica_protection(), Protection::Passphrase { .. })
1121					&& key_file.unlock_replica(&unlocker).is_ok()
1122			}
1123			Compartment::Secrets => {
1124				matches!(
1125					key_file.secrets_protection(),
1126					Some(Protection::Passphrase { .. })
1127				) && key_file.unlock_secrets(&unlocker).is_ok()
1128			}
1129		})
1130	}
1131
1132	/// Changes the key file as it is on the disk, read again while no other program writes
1133	/// it, with `change`, and writes it, so that two programs never replace each other's
1134	/// keys. If the change fails, or writing does, the file is put back as it was, and a
1135	/// keystore key that only the change made is deleted. Keystore keys that the library's
1136	/// copy had still to delete are deleted.
1137	pub(super) fn update_key_file(
1138		&mut self,
1139		change: impl FnOnce(&mut KeyFile) -> Result<(), NodeError>,
1140	) -> Result<(), NodeError> {
1141		let lock_path = self.directory.join(KEYS_LOCK);
1142		let lock = File::options()
1143			.create(true)
1144			.truncate(false)
1145			.write(true)
1146			.open(&lock_path)
1147			.map_err(NodeError::file(&lock_path))?;
1148		lock.lock().map_err(NodeError::file(&lock_path))?;
1149		let path = self.directory.join(KEYS);
1150		let mut key_file = KeyFile::read(&path)?;
1151		let before = key_file.clone();
1152		if let Err(error) = change(&mut key_file) {
1153			key_file.restore(before);
1154			return Err(error);
1155		}
1156		key_file.take_obsolete(&mut self.key_file);
1157		if let Err(error) = key_file.write(&path) {
1158			key_file.restore(before);
1159			self.key_file.take_obsolete(&mut key_file);
1160			return Err(error.into());
1161		}
1162		self.key_file = key_file;
1163		// Closing the file releases the lock.
1164		drop(lock);
1165		Ok(())
1166	}
1167}
1168
1169/// The secrets keys that the replica that `replica` takes the secrets from gives it, by
1170/// number and hash.
1171fn given_by_the_one_asked(roster: &Roster, replica: EntityId) -> BTreeSet<(u64, Hash)> {
1172	roster
1173		.secrets_given_to(replica)
1174		.map(|sealed| (sealed.epoch, sealed.hash))
1175		.collect()
1176}
1177
1178/// The operations that give `replica` of `space` the secrets keys of `held` that `has` does
1179/// not name, by number and hash, sealed to `encryption`.
1180fn gifts<'a>(
1181	has: &BTreeSet<(u64, Hash)>,
1182	(space, replica): (SpaceId, EntityId),
1183	encryption: &EncryptionKey,
1184	held: impl Iterator<Item = (u64, &'a Key)>,
1185	rng: &mut impl CryptoRng,
1186) -> Vec<nibkeep_model::Operation> {
1187	let missing = held.filter(|(epoch, key)| !has.contains(&(*epoch, key_hash(key))));
1188	sealed_secrets_keys(missing, (space, replica), encryption, rng)
1189		.iter()
1190		.map(|sealed| nibkeep_governance::give_secrets_key(replica, sealed, rng))
1191		.collect()
1192}
1193
1194/// The secrets keys of `held`, of `space`, sealed to `encryption`, the secrets encryption
1195/// key of `replica`, each linked with itself, so that the replicas that hold it know that
1196/// this one does.
1197pub(super) fn sealed_secrets_keys<'a>(
1198	held: impl Iterator<Item = (u64, &'a Key)>,
1199	(space, replica): (SpaceId, EntityId),
1200	encryption: &EncryptionKey,
1201	rng: &mut impl CryptoRng,
1202) -> Vec<SealedSecretsKey> {
1203	held.map(|(epoch, key)| {
1204		let hash = key_hash(key);
1205		SealedSecretsKey::seal(
1206			encryption,
1207			space,
1208			replica,
1209			(epoch, key, hash),
1210			(space, epoch, key),
1211			rng,
1212		)
1213	})
1214	.collect()
1215}