use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use anyhow::{Result, bail};
use second_brain_core::keys::valid_machine_id;
use second_brain_core::sqlite_store::SqliteStore;
use second_brain_sync::authorized_keys::{self, Grant};
use second_brain_sync::ssh::{
DevicePin, device_alias, known_hosts_path_in, pin_alias, unpin_devices,
};
#[derive(Default)]
pub struct DeviceAccess {
pub authorized_keys: Option<PathBuf>,
pub sb: PathBuf,
kick: AtomicBool,
}
#[derive(Default)]
pub struct Access {
pub grants: Vec<Grant>,
pub host_keys: Vec<(String, String)>,
pub cut: Vec<String>,
pub cut_pins: Vec<DevicePin>,
pub kept_pins: Vec<DevicePin>,
}
impl DeviceAccess {
pub fn for_this_user() -> Self {
let authorized_keys = home().map(|home| home.join(".ssh/authorized_keys"));
Self {
authorized_keys,
sb: installed_sb(),
kick: AtomicBool::new(false),
}
}
pub fn with_authorized_keys(path: PathBuf, sb: PathBuf) -> Self {
Self {
authorized_keys: Some(path),
sb,
kick: AtomicBool::new(false),
}
}
pub fn kick(&self) {
self.kick.store(true, Ordering::SeqCst);
}
pub fn take_kick(&self) -> bool {
self.kick.swap(false, Ordering::SeqCst)
}
pub fn reconcile(&self, sqlite: &SqliteStore, data_dir: &Path) -> Result<()> {
let access = access_of(sqlite)?;
let mut failed: Vec<String> = Vec::new();
if let Some(path) = &self.authorized_keys {
match authorized_keys::reconcile(path, &self.sb, &access.grants, &access.cut) {
Ok(change) => {
if !change.is_empty() {
tracing::info!(
"ssh access for devices: added {:?}, removed {:?}",
change.added,
change.removed
);
}
for (machine_id, reason) in &change.skipped {
tracing::warn!("no ssh access for device {machine_id}: {reason}");
}
}
Err(e) => failed.push(format!("updating {}: {e:#}", path.display())),
}
}
let known_hosts = known_hosts_path_in(data_dir);
if let Err(e) = unpin_devices(&known_hosts, &access.cut_pins, &access.kept_pins) {
failed.push(format!("unpinning cut devices' host keys: {e:#}"));
}
for (machine_id, host_key) in &access.host_keys {
if let Err(e) = pin_alias(
&known_hosts,
&device_alias(machine_id),
std::slice::from_ref(host_key),
) {
failed.push(format!("pinning {machine_id}'s host key: {e:#}"));
}
}
if failed.is_empty() {
Ok(())
} else {
bail!("{}", failed.join("; "))
}
}
pub fn sweep(&self, sqlite: &SqliteStore, data_dir: &Path) {
if let Err(e) = self.reconcile(sqlite, data_dir) {
tracing::warn!("cannot update device ssh access: {e:#}");
}
}
}
pub fn access_of(sqlite: &SqliteStore) -> Result<Access> {
let own = sqlite.machine_id().to_string();
let rows = sqlite.device_records()?;
let identity = rows
.iter()
.find(|row| row.current.record.machine_id == own)
.map(|row| row.current.record.identity_tag.clone());
let mut access = Access::default();
for row in rows {
let record = row.current.record;
if record.machine_id == own || !valid_machine_id(&record.machine_id) {
continue;
}
let pin = DevicePin {
alias: device_alias(&record.machine_id),
signed_host_key: record.ssh_host_key.clone(),
};
if row.revoked || Some(&record.identity_tag) != identity.as_ref() {
access.cut.push(record.machine_id);
access.cut_pins.push(pin);
continue;
}
access.kept_pins.push(pin);
if let Some(host_key) = record.ssh_host_key.clone() {
access.host_keys.push((record.machine_id.clone(), host_key));
}
if !record.ssh_public_key.is_empty() {
access.grants.push(Grant {
machine_id: record.machine_id,
ssh_public_key: record.ssh_public_key,
});
}
}
Ok(access)
}
fn installed_sb() -> PathBuf {
let beside = std::env::current_exe()
.ok()
.and_then(|exe| exe.parent().map(|dir| dir.join("sb")));
let cargo = home().map(|home| home.join(".cargo/bin/sb"));
beside
.iter()
.chain(cargo.iter())
.find(|path| path.exists())
.or(beside.as_ref())
.cloned()
.unwrap_or_else(|| PathBuf::from("sb"))
}
fn home() -> Option<PathBuf> {
std::env::var_os("HOME")
.filter(|home| !home.is_empty())
.map(PathBuf::from)
}