use anyhow::{Context, Result};
use second_brain_core::keys::valid_machine_id;
use second_brain_sync::protocol::Hello;
use crate::api;
use crate::commands::doctor::cmd_whoami;
use crate::commands::sync::{
cmd_sync_export, cmd_sync_import_pinned, cmd_sync_snapshot_pinned, ensure_pinned,
};
const ALLOWED: [&str; 4] = ["whoami", "sync-export", "sync-import", "sync-snapshot"];
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum Served {
Whoami,
Export { after_seq: u64, hello: String },
Import,
SnapshotExport { hello: String },
SnapshotApply,
}
fn refusal(original: &str, reason: &str) -> anyhow::Error {
anyhow::anyhow!(
"sync-serve refused {original:?}: {reason}; allowed commands: {}",
ALLOWED.join(", ")
)
}
pub(crate) fn parse_machine_arg(args: &[String]) -> Result<String> {
let usage = || anyhow::anyhow!("usage: sb sync-serve --machine <id>");
let [flag, id] = args else {
return Err(usage());
};
if flag != "--machine" || !valid_machine_id(id) {
return Err(usage());
}
Ok(id.clone())
}
pub(crate) fn parse_served(original: &str) -> Result<Served> {
let mut tokens: Vec<&str> = original.split_ascii_whitespace().collect();
if tokens.is_empty() {
return Err(refusal(original, "no command"));
}
if !ALLOWED.contains(&tokens[0]) {
tokens.remove(0);
}
let Some((&sub, rest)) = tokens.split_first() else {
return Err(refusal(original, "no command"));
};
if !ALLOWED.contains(&sub) {
return Err(refusal(original, "command not allowed"));
}
let fail = |reason: &str| refusal(original, reason);
match sub {
"whoami" | "sync-import" if !rest.is_empty() => Err(fail("unexpected arguments")),
"whoami" => Ok(Served::Whoami),
"sync-import" => Ok(Served::Import),
"sync-export" => {
let (mut after_seq, mut hello) = (None, None);
let mut it = rest.iter();
while let Some(&flag) = it.next() {
let value = it.next().ok_or_else(|| fail("missing flag value"))?;
match flag {
"--after-seq" if after_seq.is_none() => {
after_seq = Some(
value
.parse::<u64>()
.map_err(|_| fail("--after-seq is not a number"))?,
);
}
"--hello" if hello.is_none() => hello = Some((*value).to_string()),
_ => return Err(fail("unexpected or repeated argument")),
}
}
match (after_seq, hello) {
(Some(after_seq), Some(hello)) => Ok(Served::Export { after_seq, hello }),
_ => Err(fail("sync-export needs --after-seq and --hello")),
}
}
_ => match rest {
["--apply"] => Ok(Served::SnapshotApply),
["--hello", hello] => Ok(Served::SnapshotExport {
hello: (*hello).to_string(),
}),
_ => Err(fail(
"sync-snapshot needs exactly one of --hello or --apply",
)),
},
}
}
#[derive(serde::Deserialize)]
struct DeviceRow {
machine_id: String,
#[serde(default)]
revoked: bool,
}
#[derive(serde::Deserialize)]
struct Devices {
devices: Vec<DeviceRow>,
}
fn ensure_active(devices: &[DeviceRow], pinned: &str) -> Result<()> {
match devices.iter().find(|d| d.machine_id == pinned) {
Some(device) if !device.revoked => Ok(()),
Some(_) => anyhow::bail!("sync-serve refused: device {pinned} is revoked"),
None => anyhow::bail!("sync-serve refused: device {pinned} is not paired here"),
}
}
fn ensure_hello_pinned(hello_arg: &str, pinned: &str) -> Result<()> {
let hello = Hello::from_arg(hello_arg).context("reading --hello")?;
ensure_pinned(Some(&hello.machine_id), pinned)
}
fn check_device_active(pinned: &str) -> Result<()> {
let client = api::client(std::time::Duration::from_secs(10))?;
let devices: Devices = api::daemon_ok(
client
.get(format!("{}/v1/devices", api::base_url()))
.send()
.context("asking the daemon for its devices")?,
)?
.json()
.context("reading the daemon's devices")?;
ensure_active(&devices.devices, pinned)
}
pub(crate) fn cmd_sync_serve(args: &[String]) -> Result<()> {
let pinned = parse_machine_arg(args)?;
let original = std::env::var("SSH_ORIGINAL_COMMAND").unwrap_or_default();
let served = parse_served(&original)?;
match &served {
Served::Export { hello, .. } | Served::SnapshotExport { hello } => {
ensure_hello_pinned(hello, &pinned)?;
}
_ => {}
}
check_device_active(&pinned)?;
match served {
Served::Whoami => cmd_whoami(),
Served::Export { after_seq, hello } => cmd_sync_export(after_seq, Some(&hello)),
Served::Import => cmd_sync_import_pinned(&pinned),
Served::SnapshotExport { hello } => cmd_sync_snapshot_pinned(Some(&hello), false, &pinned),
Served::SnapshotApply => cmd_sync_snapshot_pinned(None, true, &pinned),
}
}
#[cfg(test)]
mod tests {
use super::*;
const H: &str = "aGVsbG8";
fn export() -> Served {
Served::Export {
after_seq: 7,
hello: H.to_string(),
}
}
#[test]
fn allowed_forms_parse_with_and_without_a_program_path() {
for prefix in ["", "sb ", "/home/x/.cargo/bin/sb "] {
let cases = [
("whoami".to_string(), Served::Whoami),
("sync-import".to_string(), Served::Import),
(format!("sync-export --after-seq 7 --hello {H}"), export()),
(format!("sync-export --hello {H} --after-seq 7"), export()),
(
format!("sync-snapshot --hello {H}"),
Served::SnapshotExport {
hello: H.to_string(),
},
),
("sync-snapshot --apply".to_string(), Served::SnapshotApply),
];
for (command, want) in cases {
let line = format!("{prefix}{command}");
assert_eq!(parse_served(&line).unwrap(), want, "{line}");
}
}
}
#[test]
fn everything_else_is_refused_naming_the_allowed_commands() {
let refused = [
"",
" \t ",
"sync-status",
"sync-compact",
"sync-trust x",
"bash",
"sh -c whoami",
"sb sync-status",
"whoami extra",
"sync-import extra",
"sync-export --after-seq 1",
"sync-export --hello X",
"sync-export --after-seq 1 --after-seq 2 --hello X",
"sync-export --hello X --hello Y --after-seq 1",
"sync-export --after-seq nope --hello X",
"sync-export --after-seq 1 --hello",
"sync-export --after-seq 1 --hello X ; rm -rf ~",
"sync-export --after-seq 1 --hello X extra",
"sync-snapshot --hello X --apply",
"sync-snapshot --apply --apply",
"sync-snapshot --apply extra",
"sync-snapshot",
"sb sb whoami",
];
for line in refused {
let err = parse_served(line).expect_err(line).to_string();
assert!(err.contains("sync-import"), "{line}: {err}");
}
}
#[test]
fn machine_arg_takes_exactly_a_valid_id() {
let ok =
|a: &[&str]| parse_machine_arg(&a.iter().map(|s| s.to_string()).collect::<Vec<_>>());
assert_eq!(ok(&["--machine", "a1.B_c-2"]).unwrap(), "a1.B_c-2");
assert!(ok(&[]).is_err());
assert!(ok(&["--machine"]).is_err());
assert!(ok(&["--machine", ""]).is_err());
assert!(ok(&["--machine", "a b"]).is_err());
assert!(ok(&["--machine", "a;b"]).is_err());
assert!(ok(&["--machine", &"a".repeat(129)]).is_err());
assert!(ok(&["--other", "a"]).is_err());
assert!(ok(&["--machine", "a", "b"]).is_err());
}
fn row(id: &str, revoked: bool) -> DeviceRow {
DeviceRow {
machine_id: id.to_string(),
revoked,
}
}
#[test]
fn only_a_listed_unrevoked_device_is_allowed() {
let devices = [row("a", false), row("b", true)];
assert!(ensure_active(&devices, "a").is_ok());
assert!(
ensure_active(&devices, "b")
.unwrap_err()
.to_string()
.contains("revoked")
);
assert!(
ensure_active(&devices, "c")
.unwrap_err()
.to_string()
.contains("not paired")
);
}
fn hello(id: &str) -> Hello {
Hello {
machine_id: id.to_string(),
wall_micros: 0,
synced: true,
cursor: None,
held_origin_seq: None,
keys: None,
peer_in: None,
log_floor: 0,
head: 0,
applied: None,
merging: None,
}
}
#[test]
fn a_hello_naming_another_machine_is_refused() {
assert!(ensure_hello_pinned(&hello("a").to_arg(), "a").is_ok());
assert!(ensure_hello_pinned(&hello("b").to_arg(), "a").is_err());
assert!(ensure_hello_pinned("not-a-hello", "a").is_err());
}
}