Skip to main content

nibkeep_node/library/
claims.rs

1//! Claims to the admin role ([technical design: claims]): when the admins of a space are gone,
2//! a direct member who can edit claims the role. Every other member's replica shows that it
3//! saw the claim, as soon as it holds it; the claim takes effect 30 days after another
4//! member first saw it, unless an admin rejects it in time, and for 30 days after that the new
5//! admin can only undo. Once the claim is settled, the claimant's replica states the role on
6//! its own record.
7//!
8//! [technical design: claims]: ../../../../docs/Technical-design.md#139-claims-to-the-admin-role
9
10use std::collections::BTreeSet;
11
12use nibkeep_base::{EntityId, SpaceId, StatementId};
13use nibkeep_crypto::rand_core::CryptoRng;
14use nibkeep_governance::replica_record;
15use nibkeep_log::ChangeId;
16use nibkeep_model::{Operation, Statement, Value, fields};
17
18use super::Library;
19use super::entities::display_name;
20use crate::{MemberRole, NodeError};
21
22/// A claim to the admin role in a space, as a program shows it.
23#[derive(Clone, Debug, PartialEq, Eq)]
24pub struct ClaimInSpace {
25	/// The claimant's record.
26	pub claimant: EntityId,
27	/// Their name there.
28	pub name: Option<String>,
29	/// When they made it, in milliseconds since the Unix epoch, by their clock.
30	pub made: u64,
31	/// When another member's device first saw it, if one did.
32	pub seen: Option<u64>,
33	/// When it takes effect, 30 days after it was first seen.
34	pub effective: Option<u64>,
35	/// When it is settled, 30 days after that.
36	pub settled: Option<u64>,
37	/// Whether an admin's rejection, seen in time, voids it.
38	pub rejected: bool,
39}
40
41/// What a claim gives a member now, by the wall clock.
42#[derive(Clone, Copy, Debug, PartialEq, Eq)]
43pub(crate) enum ClaimNow {
44	/// The member is an admin by it, and can only undo.
45	Undoing,
46	/// The member is an admin by it, for good.
47	Settled,
48}
49
50impl Library {
51	/// The claims to the admin role in a shared space, with their claimants' names.
52	///
53	/// # Errors
54	///
55	/// Returns [`NodeError::NeverShared`] for the personal space, and an error if the space
56	/// cannot be read.
57	pub fn claims(&self, space: SpaceId) -> Result<Vec<ClaimInSpace>, NodeError> {
58		self.check_shared(space)?;
59		let open = self.space(space)?;
60		let log = open.stored.log();
61		let state = log.state();
62		let mut claims = Vec::new();
63		for claim in log.claims(&open.keys)? {
64			claims.push(ClaimInSpace {
65				claimant: claim.claimant,
66				name: display_name(state, &open.types, &self.languages, claim.claimant)?,
67				made: claim.made.millis(),
68				seen: claim.seen.map(nibkeep_time::Timestamp::millis),
69				effective: claim.effective.map(nibkeep_time::Timestamp::millis),
70				settled: claim.settled.map(nibkeep_time::Timestamp::millis),
71				rejected: claim.rejected,
72			});
73		}
74		Ok(claims)
75	}
76
77	/// What a claim gives a member of a shared space now, by the latest wall clock time the
78	/// library was given, if it makes them an admin.
79	pub(crate) fn claim_now(
80		&self,
81		space: SpaceId,
82		member: EntityId,
83	) -> Result<Option<ClaimNow>, NodeError> {
84		let now = self.wall.get();
85		let open = self.space(space)?;
86		let mut best = None;
87		for claim in open.stored.log().claims(&open.keys)? {
88			if claim.claimant != member || claim.rejected {
89				continue;
90			}
91			match (claim.effective, claim.settled) {
92				(_, Some(settled)) if settled.millis() <= now => {
93					return Ok(Some(ClaimNow::Settled));
94				}
95				(Some(effective), _) if effective.millis() <= now => best = Some(ClaimNow::Undoing),
96				_ => {}
97			}
98		}
99		Ok(best)
100	}
101
102	/// Claims the admin role of a shared space, as a direct member who is an editor there,
103	/// when its admins are gone: every member sees the claim, which takes effect 30 days after
104	/// another member's device first sees it, unless an admin rejects it, and for 30 days
105	/// after that this user can only undo.
106	///
107	/// # Errors
108	///
109	/// Returns [`NodeError::NeverShared`] for the personal space, [`NodeError::Revoked`] if
110	/// this replica is revoked there, [`NodeError::AiAgentMayNot`] for an AI agent's replica,
111	/// [`NodeError::ClaimNeedsDirect`] if this replica's user is no direct member there,
112	/// [`NodeError::ClaimNeedsEditor`] if they are no editor, and an error if the change
113	/// cannot be saved.
114	pub fn claim_admin(
115		&mut self,
116		space: SpaceId,
117		wall_millis: u64,
118		rng: &mut impl CryptoRng,
119	) -> Result<(), NodeError> {
120		let own = self.check_claim(space)?;
121		let operation = Operation::assert(Statement::new(
122			StatementId::random(rng),
123			own,
124			fields::CLAIM,
125			Value::Boolean(true),
126		));
127		self.commit(space, vec![operation], wall_millis, rng)
128	}
129
130	/// Checks that this replica's user may claim the admin role of a shared space now, as
131	/// before saying what claiming would do, and returns their member.
132	///
133	/// # Errors
134	///
135	/// The errors of [`Library::claim_admin`] but those of saving.
136	pub fn check_claim(&self, space: SpaceId) -> Result<EntityId, NodeError> {
137		self.check_shared(space)?;
138		self.check_not_revoked(space)?;
139		self.check_not_ai_agent("claim the admin role")?;
140		let own = self.member_in(space)?.ok_or(NodeError::ClaimNeedsDirect)?;
141		let role = {
142			let open = self.space(space)?;
143			open.stored
144				.log()
145				.member_roles(&open.keys)?
146				.get(&own)
147				.copied()
148		};
149		if role != Some(MemberRole::Editor) {
150			return Err(NodeError::ClaimNeedsEditor);
151		}
152		Ok(own)
153	}
154
155	/// Rejects, as an admin of a shared space, the claims to the admin role that a member
156	/// made there: if another member's device sees the rejection within 30 days after a
157	/// claim took effect, the claim counts for nothing, nor what the member did as an admin.
158	///
159	/// # Errors
160	///
161	/// Returns [`NodeError::AdminsOnly`] if this replica's member is no admin there, for
162	/// good, [`NodeError::NoClaim`] if the member made no claim there that stands and is not
163	/// settled, which no rejection undoes, and an error if the change cannot be saved.
164	pub fn reject_claim(
165		&mut self,
166		space: SpaceId,
167		member: EntityId,
168		wall_millis: u64,
169		rng: &mut impl CryptoRng,
170	) -> Result<(), NodeError> {
171		self.observe_wall(wall_millis);
172		self.check_settled_admin(space, "reject claims")?;
173		let now = self.wall.get();
174		let claims: Vec<ChangeId> = {
175			let open = self.space(space)?;
176			open.stored
177				.log()
178				.claims(&open.keys)?
179				.into_iter()
180				.filter(|claim| {
181					claim.claimant == member
182						&& !claim.rejected
183						&& claim.settled.is_none_or(|settled| settled.millis() > now)
184				})
185				.map(|claim| claim.claim)
186				.collect()
187		};
188		if claims.is_empty() {
189			return Err(NodeError::NoClaim(member.to_string()));
190		}
191		let operations = claims
192			.iter()
193			.map(|claim| {
194				Operation::assert(Statement::new(
195					StatementId::random(rng),
196					member,
197					fields::REJECTED,
198					Value::Text(claim.to_string()),
199				))
200			})
201			.collect();
202		self.commit(space, operations, wall_millis, rng)
203	}
204
205	/// After a sync: shows, in each shared space this replica is in, that it saw each claim
206	/// and each rejection of another member's, as soon as it holds one; and states the admin
207	/// role on its own member's record once a claim of theirs is settled.
208	pub(crate) fn settle_claims(
209		&mut self,
210		wall_millis: u64,
211		rng: &mut impl CryptoRng,
212	) -> Result<(), NodeError> {
213		if self.is_ai_agent()? {
214			return Ok(());
215		}
216		let spaces: Vec<SpaceId> = self.spaces.keys().copied().collect();
217		// One space's error stops none of the others; the first is told at the end.
218		let mut first_error = Ok(());
219		for space in spaces {
220			if space == self.info.personal
221				|| !self.has_members(space).unwrap_or(false)
222				|| self.check_not_revoked(space).is_err()
223			{
224				continue;
225			}
226			let settled = self
227				.see_claims(space, wall_millis, rng)
228				.and_then(|()| self.take_settled_claim(space, wall_millis, rng));
229			if first_error.is_ok() {
230				first_error = settled;
231			}
232		}
233		first_error
234	}
235
236	/// Shows that this replica saw each claim and rejection in a space that another member
237	/// made, and that it has not shown it saw yet.
238	fn see_claims(
239		&mut self,
240		space: SpaceId,
241		wall_millis: u64,
242		rng: &mut impl CryptoRng,
243	) -> Result<(), NodeError> {
244		let own_key = self.replica.signing.verifying_key();
245		{
246			let open = self.space(space)?;
247			let log = open.stored.log();
248			if log.claims(&open.keys)?.is_empty()
249				|| !log.is_listed(&own_key, &open.keys)?
250				|| log.is_removed(&own_key, &open.keys)?
251			{
252				return Ok(());
253			}
254		}
255		let own = self.user_member(space)?;
256		let (_, owners) = self.users_and_owners(space)?;
257		let record = replica_record(space, &own_key);
258		let mut seen = BTreeSet::new();
259		let mut unseen = BTreeSet::new();
260		{
261			let open = self.space(space)?;
262			let log = open.stored.log();
263			for governing in log.governing_statements(&open.keys)? {
264				let field = &governing.statement.field;
265				if *field == fields::SEEN && governing.author == own_key {
266					seen.extend(governing.statement.value.as_text().map(str::to_owned));
267				} else if governing.counts
268					&& (*field == fields::CLAIM || *field == fields::REJECTED)
269					&& governing.author != own_key
270				{
271					// A member's own claim, or their own rejection, they do not see.
272					let by_own = if *field == fields::CLAIM {
273						Some(governing.statement.entity) == own
274					} else {
275						own.is_some() && owners.get(governing.author.as_bytes()).copied() == own
276					};
277					if !by_own {
278						unseen.insert(governing.change.to_string());
279					}
280				}
281			}
282		}
283		unseen.retain(|change| !seen.contains(change));
284		if unseen.is_empty() {
285			return Ok(());
286		}
287		let operations = unseen
288			.into_iter()
289			.map(|change| {
290				Operation::assert(Statement::new(
291					StatementId::random(rng),
292					record,
293					fields::SEEN,
294					Value::Text(change),
295				))
296			})
297			.collect();
298		self.commit(space, operations, wall_millis, rng)
299	}
300
301	/// States the admin role on this replica's member's record in a space, once a claim of
302	/// theirs is settled and the record does not say so yet: so the space keeps an admin by
303	/// its records, which the rules of never being without one go by.
304	fn take_settled_claim(
305		&mut self,
306		space: SpaceId,
307		wall_millis: u64,
308		rng: &mut impl CryptoRng,
309	) -> Result<(), NodeError> {
310		let Some(own) = self.member_in(space)? else {
311			return Ok(());
312		};
313		let role = {
314			let open = self.space(space)?;
315			open.stored
316				.log()
317				.member_roles(&open.keys)?
318				.get(&own)
319				.copied()
320		};
321		// A claimant lowered or removed since takes nothing.
322		if role != Some(MemberRole::Editor)
323			|| self.claim_now(space, own)? != Some(ClaimNow::Settled)
324		{
325			return Ok(());
326		}
327		self.set_role(space, own, MemberRole::Admin, wall_millis, rng)
328	}
329}