use std::collections::HashSet;
use std::fs;
use std::path::Path;
use std::sync::{Mutex, PoisonError};
use anyhow::{Context, Result, bail};
use base64::Engine;
use base64::engine::general_purpose::STANDARD;
use second_brain_core::keys::valid_machine_id;
use crate::ssh::write_atomic;
pub const TAG_PREFIX: &str = "second-brain:";
const KEY_TYPE: &str = "ssh-ed25519";
static WRITE_LOCK: Mutex<()> = Mutex::new(());
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Grant {
pub machine_id: String,
pub ssh_public_key: String,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Change {
pub added: Vec<String>,
pub removed: Vec<String>,
pub skipped: Vec<(String, String)>,
}
impl Change {
pub fn is_empty(&self) -> bool {
self.added.is_empty() && self.removed.is_empty()
}
}
fn shell_word(path: &str) -> String {
let plain = path
.bytes()
.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'/' | b'.' | b'_' | b'+' | b'-'));
if plain {
path.to_string()
} else {
format!("'{}'", path.replace('\'', "'\\''"))
}
}
pub fn forced_line(sb: &Path, grant: &Grant) -> Result<String> {
let id = &grant.machine_id;
if !valid_machine_id(id) {
bail!("machine id {id:?} is not 1 to 128 of A-Z a-z 0-9 . _ -");
}
let mut fields = grant.ssh_public_key.split_whitespace();
let (Some(key_type), Some(key)) = (fields.next(), fields.next()) else {
bail!("ssh public key must be `{KEY_TYPE} <base64>`");
};
if key_type != KEY_TYPE {
bail!("ssh public key type {key_type:?} is not {KEY_TYPE}");
}
let blob = STANDARD
.decode(key)
.context("ssh public key is not valid base64")?;
if blob.is_empty() {
bail!("ssh public key is empty");
}
let sb = sb.to_str().context("sb path is not valid UTF-8")?;
if sb.is_empty()
|| sb
.chars()
.any(|c| matches!(c, '"' | '\\' | '\n' | '\r' | '\0'))
{
bail!("sb path {sb:?} holds a character that cannot go in an authorized_keys command");
}
Ok(format!(
"command=\"{} sync-serve --machine {id}\",restrict {KEY_TYPE} {key} {TAG_PREFIX}{id}",
shell_word(sb)
))
}
fn tagged_id(segment: &[u8]) -> Option<String> {
let text = String::from_utf8_lossy(segment);
let last = text.split_whitespace().next_back()?;
let id = last.strip_prefix(TAG_PREFIX)?;
(!id.is_empty()).then(|| id.to_string())
}
fn read_bytes(path: &Path) -> Result<Option<Vec<u8>>> {
match fs::read(path) {
Ok(bytes) => Ok(Some(bytes)),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
Err(e) => Err(e).with_context(|| format!("reading {}", path.display())),
}
}
pub fn reconcile(path: &Path, sb: &Path, grants: &[Grant], cut: &[String]) -> Result<Change> {
let cut: HashSet<&str> = cut.iter().map(String::as_str).collect();
let mut wanted: Vec<(&str, String)> = Vec::new();
let mut skipped = Vec::new();
for grant in grants
.iter()
.filter(|g| !cut.contains(g.machine_id.as_str()))
{
if wanted.iter().any(|(id, _)| *id == grant.machine_id) {
continue;
}
match forced_line(sb, grant) {
Ok(line) => wanted.push((grant.machine_id.as_str(), line)),
Err(e) => skipped.push((grant.machine_id.clone(), format!("{e:#}"))),
}
}
let _guard = WRITE_LOCK.lock().unwrap_or_else(PoisonError::into_inner);
let original = read_bytes(path)?;
let data = original.as_deref().unwrap_or_default();
let mut out: Vec<u8> = Vec::with_capacity(data.len());
let mut emitted: HashSet<String> = HashSet::new();
let mut change = Change {
skipped,
..Change::default()
};
for segment in data.split_inclusive(|b| *b == b'\n') {
let Some(id) = tagged_id(segment) else {
out.extend_from_slice(segment);
continue;
};
let Some((_, line)) = wanted.iter().find(|(want, _)| *want == id) else {
if !change.removed.contains(&id) {
change.removed.push(id);
}
continue;
};
if !emitted.insert(id.clone()) {
continue;
}
let current = String::from_utf8_lossy(segment);
if current.trim_end_matches(['\n', '\r']) == line {
out.extend_from_slice(segment);
} else {
out.extend_from_slice(line.as_bytes());
out.push(b'\n');
change.added.push(id);
}
}
for (id, line) in &wanted {
if emitted.contains(*id) {
continue;
}
if out.last().is_some_and(|b| *b != b'\n') {
out.push(b'\n');
}
out.extend_from_slice(line.as_bytes());
out.push(b'\n');
change.added.push((*id).to_string());
}
if out == data {
return Ok(change);
}
write_atomic(path, &out, None)?;
Ok(change)
}
pub fn granted(path: &Path) -> Result<Vec<String>> {
let data = read_bytes(path)?.unwrap_or_default();
Ok(data.split(|b| *b == b'\n').filter_map(tagged_id).collect())
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
use std::os::unix::fs::PermissionsExt;
use std::path::PathBuf;
const KEY_A: &str =
"ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOMqqnkVzrm0SdG6UOoqKLsabgH5C9okWi0dh2l9GKJl";
const KEY_B: &str =
"ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOMqqnkVzrm0SdG6UOoqKLsabgH5C9okWi0dh2l9GKJm";
const FOREIGN: &str = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQC0 alice@laptop";
fn grant(id: &str, key: &str) -> Grant {
Grant {
machine_id: id.to_string(),
ssh_public_key: key.to_string(),
}
}
fn sb() -> PathBuf {
PathBuf::from("/usr/local/bin/sb")
}
fn line(id: &str, key: &str) -> String {
forced_line(&sb(), &grant(id, key)).unwrap()
}
#[test]
fn forced_line_has_exact_shape() {
assert_eq!(
line("m-1", KEY_A),
format!(
"command=\"/usr/local/bin/sb sync-serve --machine m-1\",restrict {KEY_A} second-brain:m-1"
)
);
}
#[test]
fn forced_line_drops_key_comment() {
let with_comment = format!("{KEY_A} laptop comment");
assert_eq!(line("m-1", &with_comment), line("m-1", KEY_A));
}
#[test]
fn forced_line_single_quotes_path_with_space() {
let l = forced_line(Path::new("/opt/my sb/sb"), &grant("m", KEY_A)).unwrap();
assert!(l.starts_with("command=\"'/opt/my sb/sb' sync-serve --machine m\",restrict "));
}
#[test]
fn forced_line_refuses_bad_input() {
for id in ["", "a b", "a\nb", "a\"b", "a/b", &"x".repeat(129)] {
assert!(forced_line(&sb(), &grant(id, KEY_A)).is_err(), "id {id:?}");
}
for key in [
"",
"ssh-rsa AAAAB3NzaC1yc2E=",
"ssh-ed25519",
"ssh-ed25519 !!!notbase64",
"ecdsa-sha2-nistp256 AAAA",
] {
assert!(forced_line(&sb(), &grant("m", key)).is_err(), "key {key:?}");
}
for path in ["/a\"b/sb", "/a\\b/sb", "/a\nb/sb", "/a\0b/sb"] {
assert!(
forced_line(Path::new(path), &grant("m", KEY_A)).is_err(),
"path {path:?}"
);
}
}
#[test]
fn one_grant_adds_one_tagged_line_and_keeps_foreign() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("authorized_keys");
let original = format!("# mine\n\n{FOREIGN}\n");
fs::write(&path, &original).unwrap();
let change = reconcile(&path, &sb(), &[grant("m-1", KEY_A)], &[]).unwrap();
assert_eq!(change.added, vec!["m-1".to_string()]);
assert!(change.removed.is_empty());
let now = fs::read_to_string(&path).unwrap();
assert_eq!(now, format!("{original}{}\n", line("m-1", KEY_A)));
assert_eq!(granted(&path).unwrap(), vec!["m-1".to_string()]);
}
#[test]
fn missing_final_newline_is_handled() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("authorized_keys");
fs::write(&path, FOREIGN).unwrap();
reconcile(&path, &sb(), &[grant("m-1", KEY_A)], &[]).unwrap();
assert_eq!(
fs::read_to_string(&path).unwrap(),
format!("{FOREIGN}\n{}\n", line("m-1", KEY_A))
);
}
#[test]
fn second_reconcile_changes_nothing_and_keeps_mtime() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("authorized_keys");
fs::write(&path, format!("{FOREIGN}\n")).unwrap();
let grants = [grant("m-1", KEY_A)];
reconcile(&path, &sb(), &grants, &[]).unwrap();
let before = fs::metadata(&path).unwrap().modified().unwrap();
std::thread::sleep(std::time::Duration::from_millis(20));
let change = reconcile(&path, &sb(), &grants, &[]).unwrap();
assert!(change.is_empty());
assert_eq!(fs::metadata(&path).unwrap().modified().unwrap(), before);
}
#[test]
fn cut_removes_only_that_id() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("authorized_keys");
fs::write(&path, format!("{FOREIGN}\n")).unwrap();
let grants = [grant("m-1", KEY_A), grant("m-2", KEY_B)];
reconcile(&path, &sb(), &grants, &[]).unwrap();
let change = reconcile(&path, &sb(), &grants[1..], &["m-1".to_string()]).unwrap();
assert_eq!(change.removed, vec!["m-1".to_string()]);
assert!(change.added.is_empty());
assert_eq!(
fs::read_to_string(&path).unwrap(),
format!("{FOREIGN}\n{}\n", line("m-2", KEY_B))
);
}
#[test]
fn changed_key_or_sb_path_replaces_line() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("authorized_keys");
reconcile(&path, &sb(), &[grant("m-1", KEY_A)], &[]).unwrap();
reconcile(&path, &sb(), &[grant("m-1", KEY_B)], &[]).unwrap();
assert_eq!(
fs::read_to_string(&path).unwrap(),
format!("{}\n", line("m-1", KEY_B))
);
let other = Path::new("/home/u/.cargo/bin/sb");
reconcile(&path, other, &[grant("m-1", KEY_B)], &[]).unwrap();
let expected = forced_line(other, &grant("m-1", KEY_B)).unwrap();
assert_eq!(fs::read_to_string(&path).unwrap(), format!("{expected}\n"));
}
#[test]
fn duplicate_tagged_lines_collapse() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("authorized_keys");
let l = line("m-1", KEY_A);
fs::write(&path, format!("{l}\n{FOREIGN}\n{l}\n")).unwrap();
reconcile(&path, &sb(), &[grant("m-1", KEY_A)], &[]).unwrap();
assert_eq!(
fs::read_to_string(&path).unwrap(),
format!("{l}\n{FOREIGN}\n")
);
}
#[test]
fn symlinked_file_is_written_through() {
let dir = tempfile::tempdir().unwrap();
let target = dir.path().join("real_keys");
fs::write(&target, format!("{FOREIGN}\n")).unwrap();
let link = dir.path().join("authorized_keys");
std::os::unix::fs::symlink(&target, &link).unwrap();
reconcile(&link, &sb(), &[grant("m-1", KEY_A)], &[]).unwrap();
assert!(
fs::symlink_metadata(&link)
.unwrap()
.file_type()
.is_symlink()
);
assert!(
fs::read_to_string(&target)
.unwrap()
.contains("second-brain:m-1")
);
}
#[test]
fn modes_new_and_existing() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join(".ssh").join("authorized_keys");
reconcile(&path, &sb(), &[grant("m-1", KEY_A)], &[]).unwrap();
let mode = |p: &Path| fs::metadata(p).unwrap().permissions().mode() & 0o777;
assert_eq!(mode(&path), 0o600);
assert_eq!(mode(path.parent().unwrap()), 0o700);
fs::set_permissions(&path, fs::Permissions::from_mode(0o644)).unwrap();
reconcile(&path, &sb(), &[grant("m-2", KEY_B)], &[]).unwrap();
assert_eq!(mode(&path), 0o644);
}
#[test]
fn missing_file_with_only_cuts_is_not_created() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join(".ssh").join("authorized_keys");
let change = reconcile(&path, &sb(), &[], &["m-1".to_string()]).unwrap();
assert!(change.is_empty());
assert!(!path.exists());
assert!(!path.parent().unwrap().exists());
assert!(granted(&path).unwrap().is_empty());
}
#[test]
fn a_bad_grant_is_skipped_and_the_rest_still_apply() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("authorized_keys");
fs::write(&path, format!("{}\n", line("gone", KEY_B))).unwrap();
let change = reconcile(
&path,
&sb(),
&[grant("bad id", KEY_A), grant("good", KEY_A)],
&["gone".to_string()],
)
.unwrap();
assert_eq!(granted(&path).unwrap(), vec!["good".to_string()]);
assert_eq!(change.removed, vec!["gone".to_string()]);
assert_eq!(
change
.skipped
.iter()
.map(|(id, _)| id.as_str())
.collect::<Vec<_>>(),
vec!["bad id"]
);
}
#[test]
fn a_tagged_line_with_no_grant_is_dropped() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("authorized_keys");
fs::write(
&path,
format!(
"{}\n{FOREIGN}\n{}\n",
line("gone", KEY_A),
line("kept", KEY_B)
),
)
.unwrap();
let change = reconcile(&path, &sb(), &[grant("kept", KEY_B)], &[]).unwrap();
assert_eq!(change.removed, vec!["gone".to_string()]);
assert_eq!(
fs::read_to_string(&path).unwrap(),
format!("{FOREIGN}\n{}\n", line("kept", KEY_B))
);
}
#[test]
fn granted_lists_ids_in_file_order() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("authorized_keys");
fs::write(
&path,
format!(
"{}\n{FOREIGN}\n{}\n",
line("zed", KEY_A),
line("abe", KEY_B)
),
)
.unwrap();
assert_eq!(
granted(&path).unwrap(),
vec!["zed".to_string(), "abe".to_string()]
);
}
}