Skip to main content

second_brain_sync/keyring/
revocation.rs

1use std::collections::BTreeSet;
2use std::fmt;
3
4use anyhow::Result;
5use second_brain_core::keys::{
6    Epoch, EpochCause, IdentityKey, IdentityTag, Revocation, SignedRecord, SignedRevocation,
7    newest_epoch, wrap, wrap_for_recovery,
8};
9use serde::Serialize;
10
11use super::{IdentityMismatch, Keyring};
12use crate::crypto::{line_epoch, open_line};
13use crate::snapshot::SnapshotKey;
14
15/// A removal the caller asked for that can't be done, as opposed to a store
16/// failure.
17#[derive(Debug, Clone, PartialEq, Eq)]
18pub struct RemovalRefused(pub String);
19
20impl fmt::Display for RemovalRefused {
21    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
22        f.write_str(&self.0)
23    }
24}
25
26impl std::error::Error for RemovalRefused {}
27
28fn refused(message: impl Into<String>) -> anyhow::Error {
29    RemovalRefused(message.into()).into()
30}
31
32/// What `sb device remove` revokes, or would revoke.
33#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
34pub struct Removal {
35    pub target: String,
36    /// Every device the revocation newly revokes, the target included.
37    pub revoked: Vec<String>,
38    /// The epoch minted for the devices that remain; None for a preview.
39    pub epoch: Option<Epoch>,
40}
41
42impl Keyring<'_> {
43    /// What removing `target` would revoke, keeping `keep` and this device.
44    pub fn removal_preview(&self, target: &str, keep: &BTreeSet<String>) -> Result<Removal> {
45        let revocation = self.revocation_of(target, keep, 0)?;
46        Ok(Removal {
47            target: target.to_string(),
48            revoked: self.newly_reached(&revocation)?,
49            epoch: None,
50        })
51    }
52
53    /// Signs a revocation of `target` and of every device whose first row
54    /// it signed, transitively, except `keep` and this device, then mints
55    /// the next epoch for the devices that remain. Peers wrap it to each
56    /// other in their handshakes, never to a revoked device.
57    pub fn remove_device(
58        &self,
59        target: &str,
60        keep: &BTreeSet<String>,
61        now_micros: i64,
62    ) -> Result<Removal> {
63        let revocation = self.revocation_of(target, keep, now_micros)?;
64        let tag = IdentityTag::from(revocation.identity_tag.clone());
65        let revoked = self.newly_reached(&revocation)?;
66        self.vouch_for_kept(&revocation, &revoked)?;
67        let signed = revocation.sign(self.device.signing_key());
68        self.store
69            .put_revocation(&signed, &self.device.verifying_key())?;
70        self.store.apply_revocations(&tag)?;
71        let epoch = self.rotate_if_needed(now_micros)?;
72        Ok(Removal {
73            target: target.to_string(),
74            revoked,
75            epoch,
76        })
77    }
78
79    fn revocation_of(
80        &self,
81        target: &str,
82        keep: &BTreeSet<String>,
83        now_micros: i64,
84    ) -> Result<Revocation> {
85        let Some(tag) = &self.identity else {
86            return Err(refused(
87                "this device holds no sync identity, so it has no devices to remove",
88            ));
89        };
90        if target == self.own() {
91            return Err(refused(
92                "a device can't remove itself; run `sb device remove` on another device",
93            ));
94        }
95        let Some((_, revoked)) = self.member_row(target)? else {
96            return Err(refused(format!(
97                "no device {target} belongs to this sync identity"
98            )));
99        };
100        if revoked {
101            return Err(refused(format!("device {target} was already removed")));
102        }
103        let mut keep = keep.clone();
104        keep.insert(self.own().to_string());
105        Ok(Revocation {
106            identity_tag: tag.as_str().to_string(),
107            revoker: self.own().to_string(),
108            target: target.to_string(),
109            keep,
110            created_at_micros: now_micros,
111        })
112    }
113
114    /// Countersigns the first row of each kept device whose signer chain
115    /// runs through a device this revocation reaches, so peers that never
116    /// saw it can still take it from an active signer.
117    fn vouch_for_kept(&self, revocation: &Revocation, revoked: &[String]) -> Result<()> {
118        let tag = IdentityTag::from(revocation.identity_tag.clone());
119        let unkept = Revocation {
120            keep: BTreeSet::from([self.own().to_string()]),
121            ..revocation.clone()
122        };
123        let reached_without_keep = self.store.revoked_by_rule(&tag, Some(&unkept))?;
124        for id in &revocation.keep {
125            if id == self.own() || revoked.contains(id) || !reached_without_keep.contains(id) {
126                continue;
127            }
128            let Some(row) = self.store.device_record(id)? else {
129                continue;
130            };
131            if row.revoked || row.first.signatures.iter().any(|s| s.signer == self.own()) {
132                continue;
133            }
134            let mut first = row.first;
135            first.countersign(self.own(), self.device.signing_key());
136            self.store.insert_first_device_record(
137                &first,
138                self.own(),
139                &self.device.verifying_key(),
140            )?;
141        }
142        Ok(())
143    }
144
145    fn newly_reached(&self, revocation: &Revocation) -> Result<Vec<String>> {
146        let tag = IdentityTag::from(revocation.identity_tag.clone());
147        let before = self.store.revoked_by_rule(&tag, None)?;
148        let after = self.store.revoked_by_rule(&tag, Some(revocation))?;
149        Ok(after.difference(&before).cloned().collect())
150    }
151
152    /// A device's current row and whether it is revoked, when it belongs to
153    /// this identity.
154    pub(super) fn member_row(&self, machine_id: &str) -> Result<Option<(SignedRecord, bool)>> {
155        let Some(tag) = &self.identity else {
156            return Ok(None);
157        };
158        Ok(self
159            .store
160            .device_record(machine_id)?
161            .filter(|row| row.current.record.identity_tag == tag.as_str())
162            .map(|row| (row.current, row.revoked)))
163    }
164
165    pub(super) fn is_revoked(&self, machine_id: &str) -> Result<bool> {
166        Ok(self
167            .member_row(machine_id)?
168            .is_some_and(|(_, revoked)| revoked))
169    }
170
171    /// Refuses a sync with a revoked peer, and every sync once this device
172    /// is revoked itself.
173    pub(super) fn refuse_revoked(&self, peer: &str) -> Result<()> {
174        if self.is_revoked(self.own())? {
175            let own = self.device_name(self.own());
176            return Err(IdentityMismatch(format!(
177                "{own} was removed from its sync identity by another device, so it cannot sync \
178                 under this machine id; join another device's identity with `sb pair <code>` \
179                 on {own}, nothing was applied"
180            ))
181            .into());
182        }
183        if self.is_revoked(peer)? {
184            let peer = self.device_name(peer);
185            return Err(IdentityMismatch(format!(
186                "{peer} was removed from this sync identity with `sb device remove`, so it \
187                 cannot sync under its machine id; join it to another identity with \
188                 `sb pair <code>` on {peer}, nothing was applied"
189            ))
190            .into());
191        }
192        Ok(())
193    }
194
195    /// Takes each revocation signed by a device of this identity, revoked
196    /// or not. Revocations apply as a union, so peers end with the same
197    /// revoked set whatever order they arrive in. From a peer already
198    /// revoked here, only revocations of the devices that revoked it are
199    /// taken: that settles a race between a thief and its owner as a union,
200    /// which is also all a removed device can still do until its ssh access
201    /// is gone. Such a revocation reaches what its target signed, as any
202    /// revocation does.
203    pub(super) fn accept_revocations(
204        &self,
205        peer: &str,
206        revocations: &[SignedRevocation],
207        revoked_peer: bool,
208    ) -> Result<()> {
209        let Some(tag) = &self.identity else {
210            return Ok(());
211        };
212        let allowed = if revoked_peer {
213            Some(self.store.revokers_of(tag, peer)?)
214        } else {
215            None
216        };
217        for signed in revocations {
218            let revocation = &signed.revocation;
219            if revocation.identity_tag != tag.as_str() {
220                continue;
221            }
222            if allowed
223                .as_ref()
224                .is_some_and(|revokers| !revokers.contains(&revocation.target))
225            {
226                continue;
227            }
228            let Some((revoker, _)) = self.member_row(&revocation.revoker)? else {
229                tracing::debug!(
230                    "holding back the revocation of {} from {peer}: its revoker {} is unknown here",
231                    revocation.target,
232                    revocation.revoker
233                );
234                continue;
235            };
236            if let Err(e) = self
237                .store
238                .put_revocation(signed, &revoker.record.signing_public_key()?)
239            {
240                tracing::warn!("{peer} sent a revocation this device refuses: {e:#}");
241            }
242        }
243        self.store.apply_revocations(tag)?;
244        Ok(())
245    }
246
247    pub(super) fn causes(&self) -> Result<Vec<(Epoch, EpochCause)>> {
248        let Some(tag) = &self.identity else {
249            return Ok(Vec::new());
250        };
251        let held = self.held_epochs();
252        let mut causes = Vec::new();
253        for stored in self.store.key_epochs(tag)? {
254            if !held.contains(&stored.epoch) {
255                continue;
256            }
257            let cause = EpochCause::from_stored(stored.cause.as_deref())?;
258            if !cause.is_empty() {
259                causes.push((stored.epoch, cause));
260            }
261        }
262        Ok(causes)
263    }
264
265    fn revocation_ids(&self, tag: &IdentityTag) -> Result<BTreeSet<String>> {
266        Ok(self
267            .store
268            .revocations(tag)?
269            .iter()
270            .map(SignedRevocation::id)
271            .collect())
272    }
273
274    /// The cause a peer gave for `epoch`, when every revocation in it is
275    /// held here; None while one is missing, so the epoch waits. Its
276    /// retirements never hold it back, since storing the cause retires them.
277    pub(super) fn applicable_cause(
278        &self,
279        epoch: &Epoch,
280        causes: &[(Epoch, EpochCause)],
281    ) -> Result<Option<EpochCause>> {
282        let Some(tag) = &self.identity else {
283            return Ok(None);
284        };
285        let cause = causes
286            .iter()
287            .find(|(e, _)| e == epoch)
288            .map(|(_, cause)| cause.clone())
289            .unwrap_or_default();
290        let held = self.revocation_ids(tag)?;
291        Ok(cause.revocations.is_subset(&held).then_some(cause))
292    }
293
294    pub(super) fn fill_causes(
295        &self,
296        causes: &[(Epoch, EpochCause)],
297        now_micros: i64,
298    ) -> Result<()> {
299        let Some(tag) = &self.identity else {
300            return Ok(());
301        };
302        for (epoch, _) in causes {
303            if self.key(epoch).is_none() {
304                continue;
305            }
306            if let Some(cause) = self.applicable_cause(epoch, causes)? {
307                self.store
308                    .put_key_epoch(tag, epoch, Some(&cause.to_json()?), now_micros)?;
309            }
310        }
311        Ok(())
312    }
313
314    /// Mints the next epoch when this device holds a revocation, or a
315    /// retirement that calls for rotation, that its newest epoch's cause
316    /// lacks, or when that epoch is wrapped to a retired phrase here: after
317    /// a removal, when a concurrent rotation with another set wins, or when
318    /// a revoked device or retired phrase may hold the newest epoch. Two
319    /// devices minting at once mint equal sets, which settle by key id
320    /// without another round.
321    pub(super) fn rotate_if_needed(&self, now_micros: i64) -> Result<Option<Epoch>> {
322        let Some(tag) = &self.identity else {
323            return Ok(None);
324        };
325        let held_revocations = self.revocation_ids(tag)?;
326        let rotating = self.store.rotating_retirements(tag)?;
327        if (held_revocations.is_empty() && rotating.is_empty()) || self.is_revoked(self.own())? {
328            return Ok(None);
329        }
330        let reloaded = Keyring::load(self.store, self.data_dir)?;
331        let held = reloaded.held_epochs();
332        let Some(current) = newest_epoch(&held) else {
333            return Ok(None);
334        };
335        let covered = reloaded
336            .causes()?
337            .into_iter()
338            .find(|(epoch, _)| *epoch == current)
339            .is_some_and(|(_, cause)| {
340                held_revocations.is_subset(&cause.revocations)
341                    && rotating.is_subset(&cause.retirements)
342            });
343        if covered
344            && !self
345                .store
346                .epochs_wrapped_to_retired(tag)?
347                .contains(&current)
348        {
349            return Ok(None);
350        }
351        let number = held.iter().map(|e| e.number).max().unwrap_or(0) + 1;
352        let key = IdentityKey::generate()?;
353        let epoch = Epoch {
354            number,
355            key_id: key.key_id(),
356        };
357        let cause = EpochCause {
358            revocations: held_revocations,
359            retirements: self.store.retired_fingerprints()?,
360        };
361        self.store
362            .put_key_epoch(tag, &epoch, Some(&cause.to_json()?), now_micros)?;
363        self.store.put_envelope(&wrap(
364            &key,
365            number,
366            tag,
367            &self.device.age_recipient(),
368            Some(self.own().to_string()),
369        )?)?;
370        let recovery = self.store.recovery_recipients(tag)?;
371        wrap_for_recovery(self.store, tag, &[(epoch, &key)], &recovery)?;
372        tracing::info!(
373            "minted sync identity epoch {number} after a device removal or a recovery phrase \
374             retirement"
375        );
376        Ok(Some(epoch))
377    }
378
379    /// Opens wire lines from `peer`, refusing any under an epoch numbered
380    /// below its floor. Once `peer` seals under an epoch a revocation
381    /// caused, that epoch's number becomes its floor, so a holder of an
382    /// older epoch can't pose as it. Without a peer the floor is the newest
383    /// epoch a revocation caused here.
384    pub fn open_lines(&self, peer: Option<&str>, lines: &[String]) -> Result<Vec<Vec<u8>>> {
385        let opener = self.opener()?;
386        let epochs: Vec<Epoch> = lines.iter().filter_map(|line| line_epoch(line)).collect();
387        self.refuse_stale_epochs(peer, &epochs, "records")?;
388        let opened = lines
389            .iter()
390            .map(|line| open_line(&opener, line))
391            .collect::<Result<Vec<_>>>()?;
392        self.raise_frame_floor_from(peer, &epochs)?;
393        Ok(opened)
394    }
395
396    /// The key to open a snapshot `exporter` sealed under `epoch`, refused
397    /// under the floor and revocations `open_lines` applies to its frames.
398    pub fn snapshot_opening_key(&self, exporter: &str, epoch: &Epoch) -> Result<SnapshotKey> {
399        self.refuse_stale_epochs(Some(exporter), std::slice::from_ref(epoch), "a snapshot")?;
400        self.snapshot_key(epoch)
401    }
402
403    /// Raises `exporter`'s floor from a snapshot whose frames all opened,
404    /// as `open_lines` does from frames.
405    pub fn opened_snapshot(&self, exporter: &str, epoch: &Epoch) -> Result<()> {
406        self.raise_frame_floor_from(Some(exporter), std::slice::from_ref(epoch))
407    }
408
409    fn refuse_stale_epochs(&self, peer: Option<&str>, epochs: &[Epoch], what: &str) -> Result<()> {
410        let floor = match (peer, &self.identity) {
411            (Some(peer), Some(tag)) => {
412                self.refuse_revoked(peer)?;
413                self.store.frame_floor(tag, peer)?
414            }
415            _ => newest_epoch(self.causes()?.iter().map(|(epoch, _)| epoch)).map(|e| e.number),
416        };
417        let floor = floor.unwrap_or(0);
418        if let Some(stale) = epochs.iter().find(|epoch| epoch.number < floor) {
419            return Err(IdentityMismatch(format!(
420                "{} sealed {what} under key epoch {}, older than epoch {floor} it already used \
421                 after a device was removed; whoever sent them holds only a key from before the \
422                 removal, nothing was applied",
423                peer.unwrap_or("the sender"),
424                stale.number
425            ))
426            .into());
427        }
428        Ok(())
429    }
430
431    fn raise_frame_floor_from(&self, peer: Option<&str>, epochs: &[Epoch]) -> Result<()> {
432        if let (Some(peer), Some(tag)) = (peer, &self.identity) {
433            let caused: Vec<Epoch> = self.causes()?.into_iter().map(|(e, _)| e).collect();
434            let used = epochs
435                .iter()
436                .filter(|epoch| caused.contains(epoch))
437                .map(|epoch| epoch.number)
438                .max();
439            if let Some(number) = used {
440                self.store.raise_frame_floor(tag, peer, number)?;
441            }
442        }
443        Ok(())
444    }
445}