Skip to main content

second_brain_sync/keyring/
retirement.rs

1use anyhow::Result;
2use second_brain_core::keys::{
3    Epoch, Retirement, SignedRetirement, recovery_fingerprint, valid_fingerprint,
4};
5use serde::Serialize;
6
7use super::Keyring;
8use super::revocation::RemovalRefused;
9
10/// What `sb recovery remove` retired.
11#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
12pub struct Retired {
13    pub fingerprint: String,
14    /// The epoch minted so no newer key opens with the phrase; None when
15    /// this device holds no epoch to rotate from.
16    pub epoch: Option<Epoch>,
17}
18
19fn refused(message: impl Into<String>) -> anyhow::Error {
20    RemovalRefused(message.into()).into()
21}
22
23impl Keyring<'_> {
24    /// Signs a retirement of the recovery phrase with `fingerprint`, mints
25    /// the next epoch without wrapping it to that phrase, and deletes this
26    /// device's envelopes for it. Peers apply it from the handshake.
27    pub fn retire_recovery(&self, fingerprint: &str, now_micros: i64) -> Result<Retired> {
28        let Some(tag) = &self.identity else {
29            return Err(refused(
30                "this device holds no sync identity, so it has no recovery phrase to remove",
31            ));
32        };
33        let fingerprint = fingerprint.trim().to_ascii_lowercase();
34        if !valid_fingerprint(&fingerprint) {
35            return Err(refused(format!(
36                "{fingerprint:?} is not a recovery phrase fingerprint; `sb recovery` lists them"
37            )));
38        }
39        if self.is_revoked(self.own())? {
40            return Err(refused(
41                "this device was removed from its sync identity, so it cannot remove a recovery \
42                 phrase",
43            ));
44        }
45        if self.store.retired_fingerprints()?.contains(&fingerprint) {
46            return Err(refused(format!(
47                "recovery phrase {fingerprint} was already removed"
48            )));
49        }
50        if !self.phrase_known(&fingerprint)? {
51            return Err(refused(format!(
52                "no device of this sync identity lists recovery phrase {fingerprint}; \
53                 `sb recovery` lists them"
54            )));
55        }
56        let signed = Retirement {
57            identity_tag: tag.as_str().to_string(),
58            retirer: self.own().to_string(),
59            fingerprint: fingerprint.clone(),
60            created_at_micros: now_micros,
61        }
62        .sign(self.device.signing_key());
63        self.store
64            .put_retirement(&signed, &self.device.verifying_key())?;
65        let epoch = self.apply_retirements(now_micros)?;
66        Ok(Retired { fingerprint, epoch })
67    }
68
69    /// Listed in the row of a device not revoked, or wrapped to here.
70    fn phrase_known(&self, fingerprint: &str) -> Result<bool> {
71        let Some(tag) = &self.identity else {
72            return Ok(false);
73        };
74        let listed = self.store.device_records()?.into_iter().any(|row| {
75            !row.revoked
76                && row.current.record.identity_tag == tag.as_str()
77                && row
78                    .current
79                    .record
80                    .recovery_fingerprints
81                    .iter()
82                    .any(|f| f == fingerprint)
83        });
84        Ok(listed
85            || self
86                .store
87                .recovery_recipients(tag)?
88                .iter()
89                .any(|r| recovery_fingerprint(&r.to_string()) == fingerprint))
90    }
91
92    /// Takes each retirement signed by a device of this identity, revoked or
93    /// not, since a retirement only shrinks who decrypts.
94    pub(super) fn accept_retirements(
95        &self,
96        peer: &str,
97        retirements: &[SignedRetirement],
98    ) -> Result<()> {
99        let Some(tag) = &self.identity else {
100            return Ok(());
101        };
102        for signed in retirements {
103            let retirement = &signed.retirement;
104            if retirement.identity_tag != tag.as_str() {
105                continue;
106            }
107            let Some((retirer, _)) = self.member_row(&retirement.retirer)? else {
108                tracing::debug!(
109                    "holding back the retirement of recovery phrase {} from {peer}: its retirer \
110                     {} is unknown here",
111                    retirement.fingerprint,
112                    retirement.retirer
113                );
114                continue;
115            };
116            if let Err(e) = self
117                .store
118                .put_retirement(signed, &retirer.record.signing_public_key()?)
119            {
120                tracing::warn!("{peer} sent a retirement this device refuses: {e:#}");
121            }
122        }
123        self.store.mark_rotating_retirements(tag)?;
124        Ok(())
125    }
126
127    /// Mints the next epoch when a held retirement asks for one, then
128    /// deletes every envelope to a retired phrase; minting goes first so
129    /// the check sees an envelope to it in the newest epoch.
130    pub(super) fn apply_retirements(&self, now_micros: i64) -> Result<Option<Epoch>> {
131        let Some(tag) = &self.identity else {
132            return Ok(None);
133        };
134        self.store.note_named_retirements(tag)?;
135        self.store.mark_rotating_retirements(tag)?;
136        let epoch = self.rotate_if_needed(now_micros)?;
137        let deleted = self.store.delete_retired_envelopes()?;
138        if deleted > 0 {
139            tracing::info!("deleted {deleted} envelopes wrapped to a retired recovery phrase");
140        }
141        Ok(epoch)
142    }
143}