use std::sync::Mutex;
use anyhow::{Context, Result};
use second_brain_core::keys::{DeviceRecord, valid_host_key, valid_login};
use super::Keyring;
use crate::pairing::SshServer;
static OWN_ROW_WRITE: Mutex<()> = Mutex::new(());
impl Keyring<'_> {
pub(super) fn update_own_row(&self, edit: impl FnOnce(&mut DeviceRecord)) -> Result<bool> {
let _writing = OWN_ROW_WRITE
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
let own = self.own();
let current = self
.store
.device_record(own)?
.context("this device has no signed row")?
.current
.record;
let mut record = current.clone();
edit(&mut record);
if record == current {
return Ok(false);
}
record.version = current.version + 1;
self.store
.update_device_record(&record.sign(own, self.device.signing_key()))
}
pub fn sign_own_ssh(&self, ssh: &SshServer) -> Result<bool> {
if self.store.device_record(self.own())?.is_none() {
return Ok(false);
}
self.update_own_row(|record| {
if let Some(login) = ssh.login.as_ref().filter(|login| valid_login(login)) {
record.ssh_login = Some(login.clone());
}
if ssh.port != 0 {
record.ssh_port = Some(ssh.port);
}
if let Some(host_key) = ssh.row_host_key().filter(|key| valid_host_key(key)) {
record.ssh_host_key = Some(host_key.to_string());
}
})
}
}