Skip to main content

nibkeep_node/library/
revocation.rs

1//! Revoking replicas, the changes set aside for review, and the keys of the spaces: taking
2//! those sealed to this replica, giving those it holds to the replicas that lack them, and
3//! making new ones ([Identity](../../../../docs/spec/identity.md#4-revoking-replicas)).
4
5use std::collections::BTreeSet;
6
7use nibkeep_base::{EntityId, Hash, SpaceId};
8use nibkeep_crypto::rand_core::CryptoRng;
9use nibkeep_crypto::{DecryptionKey, EncryptionKey, Key, VerifyingKey, key_hash};
10use nibkeep_governance::{Code, Role, Roster, SealedSpaceKey};
11use nibkeep_log::ChangeId;
12use nibkeep_time::Timestamp;
13
14use super::Library;
15use super::sync::Replica;
16use crate::NodeError;
17
18/// A change that was set aside: its author was revoked by a replica that did not have it,
19/// or nobody listed its key; or, in a space with members, its author's member left, was
20/// removed or lost a role before they knew of it, or their role never allowed it.
21#[derive(Clone, Debug, PartialEq, Eq)]
22pub struct SetAside {
23	/// The change.
24	pub change: ChangeId,
25	/// The replica that made it, if the space names one with its key.
26	pub replica: Option<EntityId>,
27	/// In a space with members, the member whose replica made it, by the listings that the
28	/// change builds on.
29	pub member: Option<EntityId>,
30	/// When it was made, as its author says, in milliseconds since 1970.
31	pub millis: u64,
32	/// How many operations it holds, if this replica can read it.
33	pub operations: Option<usize>,
34	/// Whether it governs the space, such as by revoking a replica or adding one: such a
35	/// change is never accepted.
36	pub governs: bool,
37	/// Whether accepting it would make it count: an ordinary change that only a lowered role,
38	/// a removal or a revocation set aside, and, in a space with members, one that this
39	/// replica can read, so that an admin reviews what it does.
40	pub acceptable: bool,
41	/// The entities that it changes, if this replica can read it, each with its name: the one
42	/// the space shows, or else the one that the change gives it.
43	pub entities: Vec<(EntityId, Option<String>)>,
44}
45
46impl Library {
47	/// The user's replicas that `target` names: the replica with that ID, or the replicas
48	/// of the device with that ID or name, or the AI agent's replica of that name, revoked
49	/// ones included. A device's name names no AI agent's replica. An ID may be given by its
50	/// first eight characters or more, as lists show them.
51	///
52	/// # Errors
53	///
54	/// Returns [`NodeError::WhichDevice`] if `target` names no device or replica of the
55	/// user's, or several, and an error if the personal space cannot be read.
56	pub fn replicas_named(&self, target: &str) -> Result<Vec<Replica>, NodeError> {
57		named_among(self.replicas()?, target)
58	}
59
60	/// The replicas that revoking `target` revokes, as [`Library::replicas_named`] finds
61	/// them, those whose every key is revoked already left out.
62	///
63	/// # Errors
64	///
65	/// Returns the errors of [`Library::replicas_named`], and [`NodeError::WhichDevice`] if
66	/// `target` names this replica or its device.
67	pub fn to_revoke(&self, target: &str) -> Result<Vec<Replica>, NodeError> {
68		let mut chosen = self.replicas_named(target)?;
69		if chosen.iter().any(|replica| replica.this) {
70			return Err(NodeError::WhichDevice(
71				"this device cannot revoke itself; revoke it from another of yours".to_owned(),
72			));
73		}
74		chosen.retain(|replica| !replica.revoked);
75		Ok(chosen)
76	}
77
78	/// The numbers of the keys of a space that this replica holds, in order, and the number
79	/// of the one it writes with.
80	///
81	/// # Errors
82	///
83	/// Returns an error if the library has no such space.
84	pub fn space_key_numbers(&self, space: SpaceId) -> Result<(Vec<u64>, u64), NodeError> {
85		let open = self.space(space)?;
86		Ok((open.keys.epochs().collect(), open.keys.newest().0))
87	}
88
89	/// Whether this replica knows that it was revoked. A revoked replica seldom does: every
90	/// replica that knows of the revocation refuses to sync with it.
91	///
92	/// # Errors
93	///
94	/// Returns an error if the personal space cannot be read.
95	pub fn is_revoked(&self) -> Result<bool, NodeError> {
96		match self.check_not_revoked(self.info.personal) {
97			Ok(()) => Ok(false),
98			Err(NodeError::Revoked) => Ok(true),
99			Err(error) => Err(error),
100		}
101	}
102
103	/// Revokes replicas of the user, for good: no replica syncs with them any more, those of
104	/// their changes that this replica does not have are set aside, and the personal space
105	/// gets a new key, sealed to every replica that remains, so that they cannot read what is
106	/// added later. Each revocation names the key it revokes: every key that the replica's
107	/// record has, but this replica's own. The person confirms before the call. In every
108	/// other space and group where they are listed, it revokes them too, and the devices
109	/// that they added there and that the personal space does not list, which nothing tells
110	/// from one that a thief paired on them: returns the spaces and groups where it revoked
111	/// such a device.
112	///
113	/// # Errors
114	///
115	/// Returns [`NodeError::WhichDevice`] if a replica is this one or not the user's,
116	/// [`NodeError::Revoked`] if this replica was revoked itself, and an error if the keys or
117	/// the change cannot be saved.
118	pub fn revoke(
119		&mut self,
120		replicas: &[EntityId],
121		wall_millis: u64,
122		rng: &mut impl CryptoRng,
123	) -> Result<Vec<SpaceId>, NodeError> {
124		let personal = self.info.personal;
125		self.check_not_revoked(personal)?;
126		self.check_not_ai_agent("revoke devices")?;
127		let known: BTreeSet<EntityId> = self
128			.replicas()?
129			.into_iter()
130			.filter(|replica| !replica.this)
131			.map(|replica| replica.id)
132			.collect();
133		if let Some(unknown) = replicas.iter().find(|replica| !known.contains(replica)) {
134			return Err(NodeError::WhichDevice(format!(
135				"{unknown} is no other replica of yours"
136			)));
137		}
138		let own = self.replica.signing.verifying_key();
139		let roster = self.roster(personal)?;
140		let open = self.space(personal)?;
141		let log = open.stored.log();
142		let mut revoking = Vec::new();
143		for &replica in replicas {
144			for key in roster.keys_of(replica) {
145				if *key != own && !log.is_revoked(key, &open.keys)? {
146					revoking.push((replica, *key));
147				}
148			}
149		}
150		self.record_own_endpoint(wall_millis, rng)?;
151		let roster = self.roster(personal)?;
152		self.rotate(personal, &revoking, &roster, wall_millis, rng)?;
153		// And in every other space where they are listed, each with a new key. The personal
154		// space's revocation is made: a space where this fails revokes after the next sync.
155		let (elsewhere, _) = self.revoke_in_spaces_telling(wall_millis, rng);
156		// A new secrets key, if the secrets are unlocked here and a revoked replica may have
157		// held them; or else the first replica that unlocks them makes one.
158		let _ = self.settle_secrets(wall_millis, rng);
159		Ok(elsewhere)
160	}
161
162	/// Revokes one key of a replica of the user, whatever its record says, as
163	/// [`Library::revoke`] does.
164	pub(crate) fn revoke_key(
165		&mut self,
166		replica: EntityId,
167		key: &VerifyingKey,
168		wall_millis: u64,
169		rng: &mut impl CryptoRng,
170	) -> Result<(), NodeError> {
171		let personal = self.info.personal;
172		let roster = self.roster(personal)?;
173		self.rotate(personal, &[(replica, *key)], &roster, wall_millis, rng)
174	}
175
176	/// The changes set aside in the personal space, waiting for review, ordered by ID.
177	///
178	/// # Errors
179	///
180	/// Returns an error if the personal space cannot be read.
181	pub fn set_aside(&self) -> Result<Vec<SetAside>, NodeError> {
182		self.set_aside_in(self.info.personal)
183	}
184
185	/// The changes set aside in a space, waiting for review, ordered by ID.
186	///
187	/// # Errors
188	///
189	/// Returns an error if the space cannot be read.
190	pub fn set_aside_in(&self, space: SpaceId) -> Result<Vec<SetAside>, NodeError> {
191		let open = self.space(space)?;
192		let roster = open.stored.log().roster(&open.keys)?;
193		let log = open.stored.log();
194		let state = log.state();
195		let members = space != self.info.personal && self.has_members(space)?;
196		let mut set_aside = Vec::new();
197		for change in log.set_aside_changes()? {
198			let (Some(header), Some(review)) =
199				(log.change(change)?, log.review(change, &open.keys)?)
200			else {
201				continue;
202			};
203			let replica = roster.replica_of(header.author());
204			let payload = review.payload.as_ref();
205			let mut entities: Vec<(EntityId, Option<String>)> = Vec::new();
206			if let Some(payload) = payload {
207				for operation in payload.all_operations() {
208					let Some(entity) = operation.entity() else {
209						continue;
210					};
211					if entities.iter().any(|(listed, _)| *listed == entity) {
212						continue;
213					}
214					let name =
215						super::entities::display_name(state, &open.types, &self.languages, entity)?
216							.or_else(|| stated_name(payload, entity));
217					entities.push((entity, name));
218				}
219			}
220			set_aside.push(SetAside {
221				change,
222				replica,
223				member: if members { review.member } else { None },
224				millis: header.timestamp().millis(),
225				operations: payload.map(|payload| payload.all_operations().count()),
226				governs: header.kind() == nibkeep_log::Kind::Governing,
227				// A replica's acceptance of its own change counts for nothing.
228				acceptable: review.acceptable
229					&& *header.author() != self.replica.signing.verifying_key(),
230				entities,
231			});
232		}
233		Ok(set_aside)
234	}
235
236	/// Accepts changes that were set aside in the personal space, as
237	/// [`Library::accept_set_aside_in`] does there.
238	///
239	/// # Errors
240	///
241	/// Returns the errors of [`Library::accept_set_aside_in`].
242	pub fn accept_set_aside(
243		&mut self,
244		changes: &[ChangeId],
245		wall_millis: u64,
246		rng: &mut impl CryptoRng,
247	) -> Result<usize, NodeError> {
248		self.accept_set_aside_in(self.info.personal, changes, wall_millis, rng)
249	}
250
251	/// Accepts changes that were set aside in a space, so that they count after all, with
252	/// their own authors and times, in a change that governs the space: in a space with
253	/// members, as an admin of it. Only those that accepting makes count are accepted, as
254	/// [`SetAside::acceptable`] says: never one that governs the space, nor one of a key that
255	/// no replica of the space has. Returns how many were accepted. The person confirms
256	/// before the call, having seen what they do.
257	///
258	/// # Errors
259	///
260	/// Returns [`NodeError::AiAgentMayNot`] for an AI agent's replica,
261	/// [`NodeError::Revoked`] if this replica was revoked, [`NodeError::AdminsOnly`] in a
262	/// space with members if its member is no admin there, and an error if the space cannot
263	/// be read or the change saved.
264	pub fn accept_set_aside_in(
265		&mut self,
266		space: SpaceId,
267		changes: &[ChangeId],
268		wall_millis: u64,
269		rng: &mut impl CryptoRng,
270	) -> Result<usize, NodeError> {
271		self.observe_wall(wall_millis);
272		if space == self.info.personal || !self.has_members(space)? {
273			self.check_not_ai_agent("accept the changes of revoked devices")?;
274		} else {
275			self.check_settled_admin(space, "accept changes that were set aside")?;
276		}
277		let set_aside = self.set_aside_in(space)?;
278		let operations: Vec<_> = set_aside
279			.iter()
280			.filter(|aside| changes.contains(&aside.change) && aside.acceptable)
281			.filter_map(|aside| {
282				let replica = aside.replica?;
283				Some(nibkeep_governance::accept(
284					replica,
285					&aside.change.to_string(),
286					rng,
287				))
288			})
289			.collect();
290		let accepted = operations.len();
291		if accepted > 0 {
292			self.commit(space, operations, wall_millis, rng)?;
293			// What the accepted changes held may define types, or change the languages.
294			self.read_again(space)?;
295		}
296		Ok(accepted)
297	}
298
299	/// Settles the keys of the spaces after a sync: takes the keys sealed to this replica,
300	/// gives the keys it holds to the replicas that lack them, and makes a new key where its
301	/// newest is not safe, as after two revocations at the same time; and states that the
302	/// fields the types make secret are secret for good. A replica that is revoked, or that no
303	/// counting change lists, does nothing, and an AI agent's only takes its keys: the rest
304	/// governs the space, which it may not.
305	///
306	/// # Errors
307	///
308	/// Returns an error if a space cannot be read, or the keys or the changes saved.
309	pub fn settle_keys(
310		&mut self,
311		wall_millis: u64,
312		rng: &mut impl CryptoRng,
313	) -> Result<(), NodeError> {
314		// The spaces besides the personal one first, so that one taken now settles too; what
315		// fails there is told once the rest is done, which never waits for it.
316		let mut settled = self.settle_spaces(wall_millis, rng);
317		// Then the groups: the spaces they give, and the keys and anchors that they need; and
318		// the claims to the admin role that it saw.
319		let grouped = self.settle_groups(wall_millis, rng);
320		if settled.is_ok() {
321			settled = grouped;
322		}
323		let claimed = self.settle_claims(wall_millis, rng);
324		if settled.is_ok() {
325			settled = claimed;
326		}
327		// The personal space first; another space's error stops neither it nor the others.
328		for space in self.spaces() {
329			let result = self.settle_space(space, wall_millis, rng);
330			if space == self.info.personal {
331				result?;
332			} else if settled.is_ok() {
333				settled = result;
334			}
335		}
336		// The secrets keys given to it, while its secrets are unlocked. The sync is done; the
337		// next one, or unlocking the secrets, tries again.
338		let _ = self.settle_secrets(wall_millis, rng);
339		// The recovery file, for the codes that the personal space names now; and the codes
340		// that a newer one replaces, once every backup carries it.
341		let saved = self.save_recovery_file();
342		if settled.is_ok() {
343			settled = saved;
344		}
345		let replaced = self
346			.revoke_replaced_recovery_codes(false, wall_millis, rng)
347			.map(|_| ());
348		if settled.is_ok() {
349			settled = replaced;
350		}
351		// The drops that this device makes, which the sync may have moved on.
352		let dropped = self.settle_drops(wall_millis, rng);
353		if settled.is_ok() {
354			settled = dropped;
355		}
356		settled
357	}
358
359	/// Settles one space's keys after a sync, as [`Library::settle_keys`] says.
360	fn settle_space(
361		&mut self,
362		space: SpaceId,
363		wall_millis: u64,
364		rng: &mut impl CryptoRng,
365	) -> Result<(), NodeError> {
366		let open = self.space(space)?;
367		let log = open.stored.log();
368		let own = self.replica.signing.verifying_key();
369		if !log.is_governed(&open.keys)?
370			|| log.is_revoked(&own, &open.keys)?
371			|| !log.is_listed(&own, &open.keys)?
372		{
373			return Ok(());
374		}
375		// An AI agent's replica governs nothing, and one whose member left or was removed
376		// changes nothing there any more: each only takes the keys given it before.
377		if log.is_ai_agent(&own, &open.keys)? || log.is_removed(&own, &open.keys)? {
378			let roster = self.roster(space)?;
379			self.take_keys(space, &roster, rng)?;
380			self.choose_writing_key_with(space, &roster)?;
381			return Ok(());
382		}
383		// Others can only give keys to a record with an encryption key.
384		if space == self.info.personal {
385			self.record_own_endpoint(wall_millis, rng)?;
386		}
387		self.mark_secret_fields(space, wall_millis, rng)?;
388		// Giving keys out adds statements of keys, but no rotation.
389		let roster = self.roster(space)?;
390		self.take_keys(space, &roster, rng)?;
391		self.give_keys_with(space, &roster, wall_millis, rng)?;
392		if !self.choose_writing_key_with(space, &roster)? {
393			self.rotate(space, &[], &roster, wall_millis, rng)?;
394		}
395		Ok(())
396	}
397
398	/// Who the replicas of a space are, as its counting governing changes say.
399	pub(crate) fn roster(&self, space: SpaceId) -> Result<Roster, NodeError> {
400		let open = self.space(space)?;
401		let mut roster = open.stored.log().roster(&open.keys)?;
402		// The replicas that groups in the space list, at every level, on their records there,
403		// derived from the space and their keys, with the encryption keys that their records in
404		// the group state.
405		let listed = open.stored.log().listed_through_groups(&open.keys)?;
406		if listed.is_empty() {
407			return Ok(roster);
408		}
409		let groups: Vec<SpaceId> = self
410			.inner_groups(space)?
411			.into_iter()
412			.filter(|group| self.spaces.contains_key(group))
413			.collect();
414		let mut group_rosters = Vec::new();
415		for group in groups {
416			let open = self.space(group)?;
417			group_rosters.push((group, open.stored.log().roster(&open.keys)?));
418		}
419		for key in listed {
420			let encryption = group_rosters.iter().find_map(|(group, group_roster)| {
421				group_roster.encryption_of(nibkeep_governance::replica_record(*group, &key))
422			});
423			if let Some(encryption) = encryption {
424				roster.add_listed(
425					nibkeep_governance::replica_record(space, &key),
426					key,
427					encryption.clone(),
428				);
429			}
430		}
431		Ok(roster)
432	}
433
434	/// Chooses the key that each space writes with, as [`Library::choose_writing_key_with`]
435	/// says.
436	pub(crate) fn choose_writing_keys(&mut self) -> Result<(), NodeError> {
437		let spaces: Vec<SpaceId> = self.spaces.keys().copied().collect();
438		for space in spaces {
439			let roster = self.roster(space)?;
440			self.choose_writing_key_with(space, &roster)?;
441		}
442		Ok(())
443	}
444
445	/// Has a space write with the newest key that this replica holds and that is safe: whose
446	/// rotation a member's replica made, by the changes it builds on, and builds on every
447	/// counting revocation and every departure, so that whoever made it knew of each; the
448	/// newest is the one whose rotation came last, by time and then by ID, key 0's being the
449	/// space's first change. Returns whether one is safe; if none is, it writes with the
450	/// newest, until a new key is made.
451	fn choose_writing_key_with(
452		&mut self,
453		space: SpaceId,
454		roster: &Roster,
455	) -> Result<bool, NodeError> {
456		// A group holds no data to protect: every change of it is wrapped with its first key,
457		// which never changes, so that every replica of the spaces it is in reads its log
458		// ([technical design](../../../../docs/Technical-design.md#138-groups)).
459		if self.space(space)?.is_group()? {
460			let open = self
461				.spaces
462				.get_mut(&space)
463				.ok_or(NodeError::NoSpace(space))?;
464			open.keys.write_with(Some(0));
465			return Ok(true);
466		}
467		let open = self.space(space)?;
468		let log = open.stored.log();
469		let Some(root) = log.root()? else {
470			return Ok(true);
471		};
472		let Some(first) = log.change(root)? else {
473			return Ok(true);
474		};
475		let mut makers = Makers::of(open);
476		let mut candidates: Vec<((Timestamp, ChangeId), u64)> = Vec::new();
477		let mut counting: BTreeSet<ChangeId> = BTreeSet::new();
478		for (epoch, key) in open.keys.space_keys() {
479			if epoch == 0 {
480				candidates.push(((first.timestamp(), root), epoch));
481			} else if let Some(rotation) = roster.rotation(epoch, &key_hash(key))
482				&& makers.made(rotation.change)?
483			{
484				candidates.push(((rotation.at, rotation.change), epoch));
485				if rotation.counts {
486					counting.insert(rotation.change);
487				}
488			}
489		}
490		candidates.sort_by(|a, b| b.cmp(a));
491		let mut departures = log.revocations(&open.keys)?;
492		departures.extend(log.removals(&open.keys)?);
493		// A recovery code's revocation is a departure too: a key sealed to the code by one
494		// who had not heard of it is not written with.
495		departures.extend(
496			roster
497				.codes()
498				.flat_map(|code| code.revoked_by.iter().copied()),
499		);
500		// The newest first: it is usually the safe one, and the walks are few.
501		let mut writing = None;
502		for &((_, rotation), epoch) in &candidates {
503			if log.builds_on_all(rotation, &departures)? {
504				writing = Some(epoch);
505				break;
506			}
507		}
508		let safe = writing.is_some();
509		// Until a new key is made, the newest whose rotation counts, or key 0: never one made
510		// by someone as they were removed, which they hold.
511		let fallback = || {
512			candidates
513				.iter()
514				.find(|((_, rotation), epoch)| *epoch == 0 || counting.contains(rotation))
515				.map(|(_, epoch)| *epoch)
516		};
517		let Some(epoch) = writing.or_else(fallback) else {
518			return Ok(true);
519		};
520		let open = self
521			.spaces
522			.get_mut(&space)
523			.ok_or(NodeError::NoSpace(space))?;
524		open.keys.write_with(Some(epoch));
525		Ok(safe)
526	}
527
528	/// Takes the keys of a space that statements seal to this replica, of numbers it lacks,
529	/// where a member's replica made the statement and the key's rotation, by the changes
530	/// each builds on, whether they count or not, and their hashes are those that the
531	/// rotations name; saves them, and reads what they open. So it takes a key that a member
532	/// made while being removed, with which others may have written. Where a counting
533	/// statement names a number, only such statements give it, as the others give each key
534	/// again where it counts; a number that only statements that do not count name is taken
535	/// only if they agree on its key, so that someone who left cannot plant a key of their
536	/// own under the number of another.
537	fn take_keys(
538		&mut self,
539		space: SpaceId,
540		roster: &Roster,
541		rng: &mut impl CryptoRng,
542	) -> Result<(), NodeError> {
543		let own = self.own_record(space)?;
544		let taken = self.keys_sealed_to(space, roster, (own, &self.replica.decryption))?;
545		self.save_and_read_keys(space, &taken, rng)
546	}
547
548	/// Takes the keys of a space that statements seal to a recovery code, on its record
549	/// `record`, as [`Library::take_keys`] takes those sealed to this replica, opening them
550	/// with the code's decryption key: for a device that the code brings back. Returns how
551	/// many it took.
552	pub(crate) fn take_keys_of_code(
553		&mut self,
554		space: SpaceId,
555		roster: &Roster,
556		(record, decryption): (EntityId, &DecryptionKey),
557		rng: &mut impl CryptoRng,
558	) -> Result<usize, NodeError> {
559		let taken = self.keys_sealed_to(space, roster, (record, decryption))?;
560		self.save_and_read_keys(space, &taken, rng)?;
561		Ok(taken.len())
562	}
563
564	/// The keys of a space that statements seal to the record `record`, of numbers this
565	/// replica lacks, that open with `decryption`, as [`Library::take_keys`] says.
566	fn keys_sealed_to(
567		&self,
568		space: SpaceId,
569		roster: &Roster,
570		(record, decryption): (EntityId, &DecryptionKey),
571	) -> Result<Vec<(u64, Key)>, NodeError> {
572		let open = self.space(space)?;
573		let held: BTreeSet<u64> = open.keys.epochs().collect();
574		let mut makers = Makers::of(open);
575		// The statements that may give each number, with whether they and the rotation count.
576		let mut candidates: std::collections::BTreeMap<u64, Vec<(&SealedSpaceKey, bool)>> =
577			std::collections::BTreeMap::new();
578		for gift in roster.given_to(record) {
579			let sealed = &gift.sealed;
580			if held.contains(&sealed.epoch) {
581				continue;
582			}
583			let Some(rotation) = roster.rotation(sealed.epoch, &sealed.hash) else {
584				continue;
585			};
586			if !makers.made(gift.change)? || !makers.made(rotation.change)? {
587				continue;
588			}
589			candidates
590				.entry(sealed.epoch)
591				.or_default()
592				.push((sealed, gift.counts));
593		}
594		let mut taken: Vec<(u64, Key)> = Vec::new();
595		for (epoch, mut gifts) in candidates {
596			if gifts.iter().any(|(_, counts)| *counts) {
597				gifts.retain(|(_, counts)| *counts);
598			} else if gifts
599				.iter()
600				.any(|(sealed, _)| sealed.hash != gifts[0].0.hash)
601			{
602				continue;
603			}
604			for (sealed, _) in gifts {
605				if let Some(key) = sealed
606					.open(decryption, space, record)
607					.filter(|key| key_hash(key) == sealed.hash)
608				{
609					taken.push((epoch, key));
610					break;
611				}
612			}
613		}
614		Ok(taken)
615	}
616
617	/// Saves the keys `taken` of a space, and reads what they open: also what a key saved
618	/// before, by a run that stopped in between, opens.
619	fn save_and_read_keys(
620		&mut self,
621		space: SpaceId,
622		taken: &[(u64, Key)],
623		rng: &mut impl CryptoRng,
624	) -> Result<(), NodeError> {
625		if !taken.is_empty() {
626			self.save_space_keys(space, taken, rng)?;
627		}
628		let open = self
629			.spaces
630			.get_mut(&space)
631			.ok_or(NodeError::NoSpace(space))?;
632		open.stored.open_changes(&open.keys)?;
633		open.stored.open_blob_keys(&open.keys)?;
634		self.read_again(space)?;
635		Ok(())
636	}
637
638	/// Gives the keys of a space that this replica holds, as [`Library::give_keys_with`]
639	/// does.
640	pub(crate) fn give_keys(
641		&mut self,
642		space: SpaceId,
643		wall_millis: u64,
644		rng: &mut impl CryptoRng,
645	) -> Result<(), NodeError> {
646		let roster = self.roster(space)?;
647		self.give_keys_with(space, &roster, wall_millis, rng)
648	}
649
650	/// Gives the keys of a space that this replica holds, those whose rotations a member's
651	/// replica made, by the changes they build on, whatever later set them aside, to every
652	/// replica that remains, this one included, and every recovery code that stands, that has
653	/// no counting statement of them, in one change that governs the space: so that what was written with a key stays readable
654	/// to those who join later. Key 0 every replica holds already.
655	fn give_keys_with(
656		&mut self,
657		space: SpaceId,
658		roster: &Roster,
659		wall_millis: u64,
660		rng: &mut impl CryptoRng,
661	) -> Result<(), NodeError> {
662		let remaining = self.key_recipients(space, roster, &[])?;
663		let open = self.space(space)?;
664		let mut makers = Makers::of(open);
665		let mut given: Vec<(u64, &Key, Hash)> = Vec::new();
666		for (epoch, key) in open.keys.space_keys() {
667			let hash = key_hash(key);
668			if let Some(rotation) = roster.rotation(epoch, &hash)
669				&& makers.made(rotation.change)?
670			{
671				given.push((epoch, key, hash));
672			}
673		}
674		let mut operations = Vec::new();
675		for (replica, encryption) in remaining {
676			// Given only by a counting statement, so that a key set aside as it was made is
677			// given again where it counts, and wins over any other of its number.
678			let has: BTreeSet<(u64, Hash)> = roster
679				.given_to(replica)
680				.iter()
681				.filter(|gift| gift.counts)
682				.map(|gift| (gift.sealed.epoch, gift.sealed.hash))
683				.collect();
684			for &(epoch, key, hash) in &given {
685				if has.contains(&(epoch, hash)) {
686					continue;
687				}
688				let sealed =
689					SealedSpaceKey::seal(&encryption, space, replica, (epoch, key, hash), rng);
690				operations.push(nibkeep_governance::give_key(replica, &sealed, rng));
691			}
692		}
693		if operations.is_empty() {
694			return Ok(());
695		}
696		self.commit(space, operations, wall_millis, rng)
697	}
698
699	/// The replicas of a space that remain, but those of `revoking`, with their encryption
700	/// keys: those whose keys are listed and none revoked, whose members did not leave and
701	/// were not removed, nor AI agents' where the space allows none, and that have an
702	/// encryption key.
703	pub(super) fn remaining(
704		&self,
705		space: SpaceId,
706		roster: &Roster,
707		revoking: &[(EntityId, VerifyingKey)],
708	) -> Result<Vec<(EntityId, EncryptionKey)>, NodeError> {
709		let open = self.space(space)?;
710		let log = open.stored.log();
711		let mut remaining = Vec::new();
712		for replica in roster.replicas() {
713			if revoking.iter().any(|(revoked, _)| *revoked == replica) {
714				continue;
715			}
716			let mut stays = true;
717			for key in roster.keys_of(replica) {
718				stays &= log.is_listed(key, &open.keys)?
719					&& !log.is_revoked(key, &open.keys)?
720					&& !log.is_removed(key, &open.keys)?;
721			}
722			if !stays {
723				continue;
724			}
725			if let Some(encryption) = roster.encryption_of(replica) {
726				remaining.push((replica, encryption.clone()));
727			}
728		}
729		Ok(remaining)
730	}
731
732	/// Those that a key of a space is sealed to: the replicas that remain, as
733	/// [`Library::remaining`] finds them, and the recovery codes that stand, each on its
734	/// record with the encryption key that it signed, but those of `leaving`. A code is given
735	/// a space's keys as a replica is, while it stands and, in a space with members, while
736	/// its member has a role there: a member of the space itself, or of a group that gives
737	/// their keys a role there
738	/// ([technical design](../../../../docs/Technical-design.md#111-recovery-codes)).
739	pub(super) fn key_recipients(
740		&self,
741		space: SpaceId,
742		roster: &Roster,
743		leaving: &[(EntityId, VerifyingKey)],
744	) -> Result<Vec<(EntityId, EncryptionKey)>, NodeError> {
745		let mut recipients = self.remaining(space, roster, leaving)?;
746		recipients.extend(
747			self.code_recipients(space, roster, leaving)?
748				.into_iter()
749				.map(|code| (code.record, code.statement.encryption.clone())),
750		);
751		Ok(recipients)
752	}
753
754	/// The recovery codes that a key of a space is sealed to, as [`Library::key_recipients`]
755	/// says, but those of `leaving`.
756	pub(super) fn code_recipients<'r>(
757		&self,
758		space: SpaceId,
759		roster: &'r Roster,
760		leaving: &[(EntityId, VerifyingKey)],
761	) -> Result<Vec<&'r Code>, NodeError> {
762		let standing: Vec<&Code> = roster
763			.codes()
764			.filter(|code| code.stands() && !leaving.iter().any(|(left, _)| *left == code.record))
765			.collect();
766		// Most spaces name no code, and the members' roles cost a walk of the groups.
767		if standing.is_empty() || !self.has_members(space)? {
768			return Ok(standing);
769		}
770		let open = self.space(space)?;
771		let log = open.stored.log();
772		let direct = log.member_roles(&open.keys)?;
773		let through = log.group_member_roles(&open.keys)?;
774		Ok(standing
775			.into_iter()
776			.filter(|code| {
777				let member = &code.statement.member;
778				direct
779					.get(member)
780					.or_else(|| through.get(member))
781					.is_some_and(|role| *role != Role::None)
782			})
783			.collect())
784	}
785
786	/// Gives a space a new key, sealed to every replica that remains, this one included, and
787	/// revokes the keys of `revoking` in the same change. The key's number is a random one
788	/// that no key of the space has, so that keys made at the same time differ. The key is
789	/// saved before the change that gives it out.
790	pub(crate) fn rotate(
791		&mut self,
792		space: SpaceId,
793		revoking: &[(EntityId, VerifyingKey)],
794		roster: &Roster,
795		wall_millis: u64,
796		rng: &mut impl CryptoRng,
797	) -> Result<(), NodeError> {
798		self.rotate_revoking(space, revoking, &[], roster, wall_millis, rng)
799	}
800
801	/// Gives a space a new key, as [`Library::rotate`] does, and revokes in the same change
802	/// the replicas' keys of `revoking` and the recovery codes of `codes`, each by its record
803	/// and its recovery key: none of them is given the new key.
804	pub(crate) fn rotate_revoking(
805		&mut self,
806		space: SpaceId,
807		revoking: &[(EntityId, VerifyingKey)],
808		codes: &[(EntityId, VerifyingKey)],
809		roster: &Roster,
810		wall_millis: u64,
811		rng: &mut impl CryptoRng,
812	) -> Result<(), NodeError> {
813		let open = self.space(space)?;
814		// Every number the space knows: the keys held, and those that statements name.
815		let mut known: BTreeSet<u64> = open.keys.epochs().collect();
816		known.extend(roster.numbers());
817		let epoch = loop {
818			let mut random = [0; 8];
819			rng.fill_bytes(&mut random);
820			let epoch = u64::from_le_bytes(random);
821			if !known.contains(&epoch) {
822				break epoch;
823			}
824		};
825		let key = Key::generate(rng);
826		let hash = key_hash(&key);
827		let mut operations = nibkeep_governance::revoke(revoking, rng);
828		for (record, key) in codes {
829			operations.push(nibkeep_governance::revoke_recovery_code(*record, key, rng));
830		}
831		let leaving: Vec<(EntityId, VerifyingKey)> =
832			revoking.iter().chain(codes).copied().collect();
833		for (replica, encryption) in self.key_recipients(space, roster, &leaving)? {
834			let sealed =
835				SealedSpaceKey::seal(&encryption, space, replica, (epoch, &key, hash), rng);
836			operations.push(nibkeep_governance::give_key(replica, &sealed, rng));
837		}
838		self.save_space_keys(space, &[(epoch, key)], rng)?;
839		self.commit(space, operations, wall_millis, rng)?;
840		let roster = self.roster(space)?;
841		self.choose_writing_key_with(space, &roster)?;
842		Ok(())
843	}
844
845	/// Saves keys of a space with the replica's other keys, in the key file as it is on the
846	/// disk, and gives them to the space.
847	fn save_space_keys(
848		&mut self,
849		space: SpaceId,
850		keys: &[(u64, Key)],
851		rng: &mut impl CryptoRng,
852	) -> Result<(), NodeError> {
853		let compartment = self.compartment.clone();
854		let mut saved = None;
855		self.update_key_file(|key_file| {
856			let mut replica = key_file.replica(&compartment)?;
857			let epochs = replica.spaces.entry(space).or_default();
858			for (epoch, key) in keys {
859				epochs.insert(*epoch, key.clone());
860			}
861			key_file.set_replica(&replica, &compartment, rng)?;
862			saved = Some(replica.spaces);
863			Ok(())
864		})?;
865		if let Some(spaces) = saved {
866			self.replica.spaces = spaces;
867		}
868		let open = self
869			.spaces
870			.get_mut(&space)
871			.ok_or(NodeError::NoSpace(space))?;
872		for (epoch, key) in keys {
873			open.keys.insert(*epoch, key.clone());
874		}
875		Ok(())
876	}
877}
878
879/// Which of a space's changes that give keys out a member's replica made, by the changes
880/// they build on, as found so far: a key, or a gift of one, counts only if one did
881/// ([technical design](../../../../docs/Technical-design.md#13-sharing)).
882pub(super) struct Makers<'a> {
883	stored: &'a nibkeep_store::StoredLog,
884	keys: &'a nibkeep_log::SpaceKeys,
885	found: std::collections::BTreeMap<ChangeId, bool>,
886}
887
888impl<'a> Makers<'a> {
889	pub(super) fn of(open: &'a super::Space) -> Self {
890		Self {
891			stored: &open.stored,
892			keys: &open.keys,
893			found: std::collections::BTreeMap::new(),
894		}
895	}
896
897	/// Whether a member's replica made a change, by the changes it builds on.
898	pub(super) fn made(&mut self, change: ChangeId) -> Result<bool, NodeError> {
899		if let Some(&made) = self.found.get(&change) {
900			return Ok(made);
901		}
902		let made = self.stored.log().author_was_a_member(change, self.keys)?;
903		self.found.insert(change, made);
904		Ok(made)
905	}
906}
907
908/// The name that a change's payload gives an entity, in full, if it states one.
909fn stated_name(payload: &nibkeep_log::Payload, entity: EntityId) -> Option<String> {
910	payload
911		.all_operations()
912		.find_map(|operation| match operation {
913			nibkeep_model::Operation::Assert { statement, .. }
914				if statement.entity == entity && statement.field == nibkeep_model::fields::NAME =>
915			{
916				match &statement.value {
917					nibkeep_model::Value::Name(name) => Some(name.full().to_owned()),
918					other => other.as_text().map(str::to_owned),
919				}
920			}
921			_ => None,
922		})
923}
924
925/// The replicas of `replicas` that `target` names, as [`Library::replicas_named`] says.
926pub(super) fn named_among(replicas: Vec<Replica>, target: &str) -> Result<Vec<Replica>, NodeError> {
927	let is_target = |id: EntityId| {
928		let id = id.to_string();
929		id == target || (target.len() >= 8 && id.starts_with(target))
930	};
931	let mut named: BTreeSet<EntityId> = BTreeSet::new();
932	for replica in &replicas {
933		if is_target(replica.id) {
934			named.insert(replica.id);
935		}
936		if let Some(device) = replica.device.filter(|&device| is_target(device)) {
937			named.insert(device);
938		}
939	}
940	if named.is_empty() {
941		// An AI agent's replica is named by its own name, so that its device, which pairing
942		// names after the computer it runs on, never makes a device's name ambiguous.
943		named = replicas
944			.iter()
945			.filter(|replica| !replica.ai_agent && replica.device_name.as_deref() == Some(target))
946			.filter_map(|replica| replica.device)
947			.collect();
948		named.extend(
949			replicas
950				.iter()
951				.filter(|replica| replica.ai_agent && replica.name.as_deref() == Some(target))
952				.map(|replica| replica.id),
953		);
954	}
955	if named.len() > 1 {
956		return Err(NodeError::WhichDevice(format!(
957			"{target} names several devices or replicas; give more of the ID of the one you mean"
958		)));
959	}
960	let Some(&named) = named.first() else {
961		return Err(NodeError::WhichDevice(format!(
962			"no device or replica of yours is {target}"
963		)));
964	};
965	Ok(replicas
966		.into_iter()
967		.filter(|replica| replica.id == named || replica.device == Some(named))
968		.collect())
969}