use std::collections::BTreeSet;
use std::fmt;
use anyhow::Result;
use second_brain_core::keys::{
Epoch, EpochCause, IdentityKey, IdentityTag, Revocation, SignedRecord, SignedRevocation,
newest_epoch, wrap, wrap_for_recovery,
};
use serde::Serialize;
use super::{IdentityMismatch, Keyring};
use crate::crypto::{line_epoch, open_line};
use crate::snapshot::SnapshotKey;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RemovalRefused(pub String);
impl fmt::Display for RemovalRefused {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl std::error::Error for RemovalRefused {}
fn refused(message: impl Into<String>) -> anyhow::Error {
RemovalRefused(message.into()).into()
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Removal {
pub target: String,
pub revoked: Vec<String>,
pub epoch: Option<Epoch>,
}
impl Keyring<'_> {
pub fn removal_preview(&self, target: &str, keep: &BTreeSet<String>) -> Result<Removal> {
let revocation = self.revocation_of(target, keep, 0)?;
Ok(Removal {
target: target.to_string(),
revoked: self.newly_reached(&revocation)?,
epoch: None,
})
}
pub fn remove_device(
&self,
target: &str,
keep: &BTreeSet<String>,
now_micros: i64,
) -> Result<Removal> {
let revocation = self.revocation_of(target, keep, now_micros)?;
let tag = IdentityTag::from(revocation.identity_tag.clone());
let revoked = self.newly_reached(&revocation)?;
self.vouch_for_kept(&revocation, &revoked)?;
let signed = revocation.sign(self.device.signing_key());
self.store
.put_revocation(&signed, &self.device.verifying_key())?;
self.store.apply_revocations(&tag)?;
let epoch = self.rotate_if_needed(now_micros)?;
Ok(Removal {
target: target.to_string(),
revoked,
epoch,
})
}
fn revocation_of(
&self,
target: &str,
keep: &BTreeSet<String>,
now_micros: i64,
) -> Result<Revocation> {
let Some(tag) = &self.identity else {
return Err(refused(
"this device holds no sync identity, so it has no devices to remove",
));
};
if target == self.own() {
return Err(refused(
"a device can't remove itself; run `sb device remove` on another device",
));
}
let Some((_, revoked)) = self.member_row(target)? else {
return Err(refused(format!(
"no device {target} belongs to this sync identity"
)));
};
if revoked {
return Err(refused(format!("device {target} was already removed")));
}
let mut keep = keep.clone();
keep.insert(self.own().to_string());
Ok(Revocation {
identity_tag: tag.as_str().to_string(),
revoker: self.own().to_string(),
target: target.to_string(),
keep,
created_at_micros: now_micros,
})
}
fn vouch_for_kept(&self, revocation: &Revocation, revoked: &[String]) -> Result<()> {
let tag = IdentityTag::from(revocation.identity_tag.clone());
let unkept = Revocation {
keep: BTreeSet::from([self.own().to_string()]),
..revocation.clone()
};
let reached_without_keep = self.store.revoked_by_rule(&tag, Some(&unkept))?;
for id in &revocation.keep {
if id == self.own() || revoked.contains(id) || !reached_without_keep.contains(id) {
continue;
}
let Some(row) = self.store.device_record(id)? else {
continue;
};
if row.revoked || row.first.signatures.iter().any(|s| s.signer == self.own()) {
continue;
}
let mut first = row.first;
first.countersign(self.own(), self.device.signing_key());
self.store.insert_first_device_record(
&first,
self.own(),
&self.device.verifying_key(),
)?;
}
Ok(())
}
fn newly_reached(&self, revocation: &Revocation) -> Result<Vec<String>> {
let tag = IdentityTag::from(revocation.identity_tag.clone());
let before = self.store.revoked_by_rule(&tag, None)?;
let after = self.store.revoked_by_rule(&tag, Some(revocation))?;
Ok(after.difference(&before).cloned().collect())
}
pub(super) fn member_row(&self, machine_id: &str) -> Result<Option<(SignedRecord, bool)>> {
let Some(tag) = &self.identity else {
return Ok(None);
};
Ok(self
.store
.device_record(machine_id)?
.filter(|row| row.current.record.identity_tag == tag.as_str())
.map(|row| (row.current, row.revoked)))
}
pub(super) fn is_revoked(&self, machine_id: &str) -> Result<bool> {
Ok(self
.member_row(machine_id)?
.is_some_and(|(_, revoked)| revoked))
}
pub(super) fn refuse_revoked(&self, peer: &str) -> Result<()> {
if self.is_revoked(self.own())? {
let own = self.device_name(self.own());
return Err(IdentityMismatch(format!(
"{own} was removed from its sync identity by another device, so it cannot sync \
under this machine id; join another device's identity with `sb pair <code>` \
on {own}, nothing was applied"
))
.into());
}
if self.is_revoked(peer)? {
let peer = self.device_name(peer);
return Err(IdentityMismatch(format!(
"{peer} was removed from this sync identity with `sb device remove`, so it \
cannot sync under its machine id; join it to another identity with \
`sb pair <code>` on {peer}, nothing was applied"
))
.into());
}
Ok(())
}
pub(super) fn accept_revocations(
&self,
peer: &str,
revocations: &[SignedRevocation],
revoked_peer: bool,
) -> Result<()> {
let Some(tag) = &self.identity else {
return Ok(());
};
let allowed = if revoked_peer {
Some(self.store.revokers_of(tag, peer)?)
} else {
None
};
for signed in revocations {
let revocation = &signed.revocation;
if revocation.identity_tag != tag.as_str() {
continue;
}
if allowed
.as_ref()
.is_some_and(|revokers| !revokers.contains(&revocation.target))
{
continue;
}
let Some((revoker, _)) = self.member_row(&revocation.revoker)? else {
tracing::debug!(
"holding back the revocation of {} from {peer}: its revoker {} is unknown here",
revocation.target,
revocation.revoker
);
continue;
};
if let Err(e) = self
.store
.put_revocation(signed, &revoker.record.signing_public_key()?)
{
tracing::warn!("{peer} sent a revocation this device refuses: {e:#}");
}
}
self.store.apply_revocations(tag)?;
Ok(())
}
pub(super) fn causes(&self) -> Result<Vec<(Epoch, EpochCause)>> {
let Some(tag) = &self.identity else {
return Ok(Vec::new());
};
let held = self.held_epochs();
let mut causes = Vec::new();
for stored in self.store.key_epochs(tag)? {
if !held.contains(&stored.epoch) {
continue;
}
let cause = EpochCause::from_stored(stored.cause.as_deref())?;
if !cause.is_empty() {
causes.push((stored.epoch, cause));
}
}
Ok(causes)
}
fn revocation_ids(&self, tag: &IdentityTag) -> Result<BTreeSet<String>> {
Ok(self
.store
.revocations(tag)?
.iter()
.map(SignedRevocation::id)
.collect())
}
pub(super) fn applicable_cause(
&self,
epoch: &Epoch,
causes: &[(Epoch, EpochCause)],
) -> Result<Option<EpochCause>> {
let Some(tag) = &self.identity else {
return Ok(None);
};
let cause = causes
.iter()
.find(|(e, _)| e == epoch)
.map(|(_, cause)| cause.clone())
.unwrap_or_default();
let held = self.revocation_ids(tag)?;
Ok(cause.revocations.is_subset(&held).then_some(cause))
}
pub(super) fn fill_causes(
&self,
causes: &[(Epoch, EpochCause)],
now_micros: i64,
) -> Result<()> {
let Some(tag) = &self.identity else {
return Ok(());
};
for (epoch, _) in causes {
if self.key(epoch).is_none() {
continue;
}
if let Some(cause) = self.applicable_cause(epoch, causes)? {
self.store
.put_key_epoch(tag, epoch, Some(&cause.to_json()?), now_micros)?;
}
}
Ok(())
}
pub(super) fn rotate_if_needed(&self, now_micros: i64) -> Result<Option<Epoch>> {
let Some(tag) = &self.identity else {
return Ok(None);
};
let held_revocations = self.revocation_ids(tag)?;
let rotating = self.store.rotating_retirements(tag)?;
if (held_revocations.is_empty() && rotating.is_empty()) || self.is_revoked(self.own())? {
return Ok(None);
}
let reloaded = Keyring::load(self.store, self.data_dir)?;
let held = reloaded.held_epochs();
let Some(current) = newest_epoch(&held) else {
return Ok(None);
};
let covered = reloaded
.causes()?
.into_iter()
.find(|(epoch, _)| *epoch == current)
.is_some_and(|(_, cause)| {
held_revocations.is_subset(&cause.revocations)
&& rotating.is_subset(&cause.retirements)
});
if covered
&& !self
.store
.epochs_wrapped_to_retired(tag)?
.contains(¤t)
{
return Ok(None);
}
let number = held.iter().map(|e| e.number).max().unwrap_or(0) + 1;
let key = IdentityKey::generate()?;
let epoch = Epoch {
number,
key_id: key.key_id(),
};
let cause = EpochCause {
revocations: held_revocations,
retirements: self.store.retired_fingerprints()?,
};
self.store
.put_key_epoch(tag, &epoch, Some(&cause.to_json()?), now_micros)?;
self.store.put_envelope(&wrap(
&key,
number,
tag,
&self.device.age_recipient(),
Some(self.own().to_string()),
)?)?;
let recovery = self.store.recovery_recipients(tag)?;
wrap_for_recovery(self.store, tag, &[(epoch, &key)], &recovery)?;
tracing::info!(
"minted sync identity epoch {number} after a device removal or a recovery phrase \
retirement"
);
Ok(Some(epoch))
}
pub fn open_lines(&self, peer: Option<&str>, lines: &[String]) -> Result<Vec<Vec<u8>>> {
let opener = self.opener()?;
let epochs: Vec<Epoch> = lines.iter().filter_map(|line| line_epoch(line)).collect();
self.refuse_stale_epochs(peer, &epochs, "records")?;
let opened = lines
.iter()
.map(|line| open_line(&opener, line))
.collect::<Result<Vec<_>>>()?;
self.raise_frame_floor_from(peer, &epochs)?;
Ok(opened)
}
pub fn snapshot_opening_key(&self, exporter: &str, epoch: &Epoch) -> Result<SnapshotKey> {
self.refuse_stale_epochs(Some(exporter), std::slice::from_ref(epoch), "a snapshot")?;
self.snapshot_key(epoch)
}
pub fn opened_snapshot(&self, exporter: &str, epoch: &Epoch) -> Result<()> {
self.raise_frame_floor_from(Some(exporter), std::slice::from_ref(epoch))
}
fn refuse_stale_epochs(&self, peer: Option<&str>, epochs: &[Epoch], what: &str) -> Result<()> {
let floor = match (peer, &self.identity) {
(Some(peer), Some(tag)) => {
self.refuse_revoked(peer)?;
self.store.frame_floor(tag, peer)?
}
_ => newest_epoch(self.causes()?.iter().map(|(epoch, _)| epoch)).map(|e| e.number),
};
let floor = floor.unwrap_or(0);
if let Some(stale) = epochs.iter().find(|epoch| epoch.number < floor) {
return Err(IdentityMismatch(format!(
"{} sealed {what} under key epoch {}, older than epoch {floor} it already used \
after a device was removed; whoever sent them holds only a key from before the \
removal, nothing was applied",
peer.unwrap_or("the sender"),
stale.number
))
.into());
}
Ok(())
}
fn raise_frame_floor_from(&self, peer: Option<&str>, epochs: &[Epoch]) -> Result<()> {
if let (Some(peer), Some(tag)) = (peer, &self.identity) {
let caused: Vec<Epoch> = self.causes()?.into_iter().map(|(e, _)| e).collect();
let used = epochs
.iter()
.filter(|epoch| caused.contains(epoch))
.map(|epoch| epoch.number)
.max();
if let Some(number) = used {
self.store.raise_frame_floor(tag, peer, number)?;
}
}
Ok(())
}
}