//! The hub end to end: one-time links, pairing, roles enforced by the hub, secrets refused (P3). use lune_core::hub::{self, HubLink}; use lune_core::vault::{self, Vault}; use lune_core::{remote, secrets, state}; use std::collections::HashSet; use std::io::{BufRead, BufReader}; use std::process::{Child, Command, Stdio}; /// Hub credentials are process-wide (as in the app), so these tests take turns. static SERIAL: std::sync::Mutex<()> = std::sync::Mutex::new(()); struct HubProcess(Child); impl Drop for HubProcess { fn drop(&mut self) { let _ = self.0.kill(); } } fn start_hub(data: &std::path::Path) -> (HubProcess, String, String) { let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port(); let url = format!("http://127.0.0.1:{port}"); let mut child = Command::new(env!("CARGO_BIN_EXE_lunehub")) .env("LUNE_HUB_DATA", data) .env("LUNE_HUB_URL", &url) .env("LUNE_HUB_LISTEN", format!("127.0.0.1:{port}")) .env("LUNE_OWNER_NAME", "Sen") .stdout(Stdio::piped()) .spawn() .unwrap(); let mut link = String::new(); for line in BufReader::new(child.stdout.take().unwrap()).lines() { let line = line.unwrap(); if let Some(i) = line.find("http").filter(|_| line.contains("/join/")) { link = line[i..].split_whitespace().next().unwrap().to_string(); } if line.contains("listening") { break; } } (HubProcess(child), url, link) } fn as_device(url: &str, w: &hub::Welcome) -> HubLink { let link = HubLink { url: url.into(), device_id: w.device_id.clone(), key: w.key.clone() }; remote::set_hub(link.clone()); link } #[test] fn hub_lifecycle() { let _turn = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); let tmp = tempfile::TempDir::new().unwrap(); let (_hub, url, owner_link) = start_hub(&tmp.path().join("data")); // The owner link works once. let (_, sen) = hub::join(&owner_link, "Codex").unwrap(); assert_eq!(sen.person, "Sen"); assert!(hub::join(&owner_link, "Again").is_err()); let codex = as_device(&url, &sen); let devops = codex.create_vault("DevOps").unwrap(); // Pairing: a code works once, and the new device has its own key. let code = codex.pair().unwrap(); let hermes_w = hub::login(&url, &code, "Hermes").unwrap(); assert!(hub::login(&url, &code, "Again").is_err()); assert_ne!(hermes_w.key, sen.key); // Codex shares a note; Hermes receives it labeled Codex. as_device(&url, &sen); let (cfg, _, err) = vault::add("DevOps", &tmp.path().join("codex"), &devops.git_url, "Codex").unwrap(); assert_eq!(err, None); let a = Vault::open(&cfg, "Codex").unwrap(); std::fs::write(a.root.join("vm-list.md"), "web-1\n").unwrap(); a.save_changes(None, &HashSet::new()).unwrap(); a.sync().unwrap(); let hermes = as_device(&url, &hermes_w); assert_eq!(hermes.me().unwrap().vaults[0].role, "manage"); let (cfg_h, _, _) = vault::add("DevOps", &tmp.path().join("hermes"), &devops.git_url, "Hermes").unwrap(); let h = Vault::open(&cfg_h, "Hermes").unwrap(); assert_eq!(std::fs::read(h.root.join("vm-list.md")).unwrap(), b"web-1\n"); // Bob has Read: the hub refuses his changes even from a client that ignores its role. as_device(&url, &sen); let bob_link = codex.invite("Bob", &[("DevOps".into(), "read".into())]).unwrap(); let (_, bob_w) = hub::join(&bob_link, "Bob pc").unwrap(); as_device(&url, &bob_w); let (cfg_b, _, _) = vault::add("DevOps", &tmp.path().join("bob"), &devops.git_url, "Bob pc").unwrap(); let b = Vault::open(&cfg_b, "Bob pc").unwrap(); std::fs::write(b.root.join("bob.md"), "bob\n").unwrap(); b.save_changes(None, &HashSet::new()).unwrap(); assert!(b.sync().is_err(), "read access must not share"); state::write_role(&b.git_dir, "read").unwrap(); assert!(b.sync().unwrap().read_only); // A line this device calls "not a secret" is still refused by the hub until the hub hears it too. as_device(&url, &sen); std::fs::write(a.root.join("aws.md"), "aws_access_key_id = AKIAIOSFODNN7EXAMPLE\n").unwrap(); let hit = a.secret_holds().unwrap()[0].hits[0].clone(); secrets::allow(&a.git_dir, &hit, "aws.md").unwrap(); a.save_changes(None, &HashSet::new()).unwrap(); let err = format!("{:#}", a.sync().unwrap_err()); assert!(err.contains("aws.md line 1: possible AWS access key"), "{err}"); codex.not_a_secret(devops.id, &hit.line_hash).unwrap(); a.sync().unwrap(); let log: Vec = codex.log(50).unwrap().into_iter().map(|e| e.action).collect(); for action in ["joined", "device added", "vault created", "invite created", "change refused", "not a secret"] { assert!(log.iter().any(|a| a == action), "missing {action} in {log:?}"); } } // ---- Milestone 4: taking access back ---- use lune_core::config::Config; use lune_core::membership::arrive; fn device(url: &str, w: &hub::Welcome, label: &str, dir: &std::path::Path) -> Config { Config { device_name: Some(label.into()), vaults_dir: Some(dir.to_path_buf()), hub: Some(HubLink { url: url.into(), device_id: w.device_id.clone(), key: w.key.clone() }), ..Default::default() } } /// Runs one check-in for a device, as `lunesync run` does every 30 s. fn check_in(cfg: &mut Config) -> Vec { cfg.use_hub_credentials(); arrive(cfg).unwrap() } fn open(cfg: &Config, name: &str) -> Vault { let vc = cfg.find(name).unwrap_or_else(|| panic!("{name} missing")); cfg.use_hub_credentials(); Vault::open(vc, &cfg.device_label()).unwrap() } fn write_and_save(v: &Vault, file: &str, text: &str) { std::fs::write(v.root.join(file), text).unwrap(); v.save_changes(None, &HashSet::new()).unwrap(); } #[test] fn taking_access_back() { let _turn = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); let tmp = tempfile::TempDir::new().unwrap(); // Config::save writes here; each device's config lives in memory in this test. unsafe { std::env::set_var("LUNE_HOME", tmp.path().join("cfg")) }; let (_hub, url, owner_link) = start_hub(&tmp.path().join("data")); let (_, sen_w) = hub::join(&owner_link, "Codex").unwrap(); let mut sen = device(&url, &sen_w, "Codex", &tmp.path().join("sen")); let sen_hub = sen.hub.clone().unwrap(); sen.use_hub_credentials(); sen_hub.create_vault("DevOps").unwrap(); sen_hub.create_vault("Notes").unwrap(); check_in(&mut sen); write_and_save(&open(&sen, "DevOps"), "runbook.md", "restart\n"); open(&sen, "DevOps").sync().unwrap(); // 1. Alice edits DevOps while offline, then loses DevOps only. let link = sen_hub.invite("Alice", &[("DevOps".into(), "edit".into()), ("Notes".into(), "edit".into())]).unwrap(); let (_, alice_w) = hub::join(&link, "Alice laptop").unwrap(); let mut alice = device(&url, &alice_w, "Alice laptop", &tmp.path().join("alice")); assert_eq!(check_in(&mut alice).len(), 2); let a = open(&alice, "DevOps"); write_and_save(&a, "alice.md", "alice's unshared work\n"); std::fs::write(a.root.join("keys.md"), "aws_access_key_id = AKIAIOSFODNN7EXAMPLE\n").unwrap(); let alice_devops = a.root.clone(); drop(a); sen.use_hub_credentials(); assert_eq!(sen_hub.remove("Alice", "DevOps", false).unwrap(), 1); let said = check_in(&mut alice); assert!(said[0].contains("folder was deleted"), "{said:?}"); assert!(!alice_devops.exists()); assert!(alice.find("DevOps").is_none()); let n = open(&alice, "Notes"); write_and_save(&n, "still.md", "notes keep syncing\n"); n.sync().unwrap(); // 2. Sen reviews and keeps the handover; the secret never arrives, the work does. sen.use_hub_credentials(); let h = sen_hub.handovers().unwrap(); assert_eq!((h[0].person.as_str(), h[0].state.as_str()), ("Alice", "received")); let files = sen_hub.handover_show(h[0].id).unwrap(); assert!(files.iter().any(|f| f.ends_with("alice.md")) && files.iter().any(|f| f.ends_with("keys.md")), "{files:?}"); sen_hub.handover_decide(h[0].id, "keep").unwrap(); let s = open(&sen, "DevOps"); s.sync().unwrap(); assert_eq!(std::fs::read(s.root.join("alice.md")).unwrap(), b"alice's unshared work\n"); assert_eq!(std::fs::read(s.root.join("keys.md")).unwrap(), b"aws_access_key_id = [secret removed when leaving]\n"); // 3. Bob is removed from the team: everything stops; restored, he comes back with nothing. let link = sen_hub.invite("Bob", &[("DevOps".into(), "edit".into()), ("Notes".into(), "read".into())]).unwrap(); let (_, bob_w) = hub::join(&link, "Bob pc").unwrap(); let mut bob = device(&url, &bob_w, "Bob pc", &tmp.path().join("bob")); check_in(&mut bob); write_and_save(&open(&bob, "DevOps"), "bob.md", "bob was here\n"); sen.use_hub_credentials(); sen_hub.team_remove("Bob").unwrap(); let said = check_in(&mut bob); assert_eq!(said.len(), 2, "{said:?}"); assert!(bob.vaults.is_empty()); assert!(!tmp.path().join("bob/DevOps").exists() && !tmp.path().join("bob/Notes").exists()); let said = check_in(&mut bob); assert!(said[0].contains("removed from the hub"), "{said:?}"); assert!(bob.hub.is_none()); sen.use_hub_credentials(); let bob_handover = sen_hub.handovers().unwrap().into_iter().find(|h| h.person == "Bob" && h.state == "received").unwrap(); sen_hub.handover_decide(bob_handover.id, "discard").unwrap(); open(&sen, "DevOps").sync().unwrap(); assert!(!open(&sen, "DevOps").root.join("bob.md").exists()); assert!(sen_hub.grant("Bob", "Notes", "read").is_err(), "a removed person can't be granted access"); let back = sen_hub.team_restore("Bob").unwrap(); let (_, bob2) = hub::join(&back, "Bob new pc").unwrap(); let bob2 = HubLink { url: url.clone(), device_id: bob2.device_id, key: bob2.key }; assert!(bob2.me().unwrap().vaults.is_empty()); // 4. A switched-off device is removed and skipped: later it deletes its copy and sends nothing. sen.use_hub_credentials(); let code = sen_hub.pair().unwrap(); let old_w = hub::login(&url, &code, "Old laptop").unwrap(); let mut old = device(&url, &old_w, "Old laptop", &tmp.path().join("old")); check_in(&mut old); write_and_save(&open(&old, "DevOps"), "old.md", "never sent\n"); sen.use_hub_credentials(); sen_hub.remove_device("Old laptop", None).unwrap(); for h in sen_hub.handovers().unwrap().into_iter().filter(|h| h.device == "Old laptop") { assert_eq!(h.state, "waiting"); sen_hub.handover_decide(h.id, "skip").unwrap(); } check_in(&mut old); assert!(!tmp.path().join("old/DevOps").exists()); sen.use_hub_credentials(); assert!(sen_hub.handovers().unwrap().iter().filter(|h| h.device == "Old laptop").all(|h| h.state == "skipped")); assert!(check_in(&mut old)[0].contains("removed from the hub")); // 5. With "delete from devices" off, the copy stays, read-only and no longer synced. sen.use_hub_credentials(); sen_hub.vault_setting("Notes", false).unwrap(); sen_hub.remove("Alice", "Notes", false).unwrap(); let said = check_in(&mut alice); assert!(said[0].contains("read-only"), "{said:?}"); let kept = tmp.path().join("alice/Notes"); assert!(kept.join("still.md").exists()); assert!(std::fs::write(kept.join("new.md"), "x").is_err(), "folder should be read-only"); assert!(alice.vaults.is_empty()); sen.use_hub_credentials(); let log: Vec = sen_hub.log(200).unwrap().into_iter().map(|e| e.action).collect(); for action in ["access removed", "left vault", "handover kept", "removed from team", "handover discarded", "restored to team", "device removed", "handover skipped", "vault setting"] { assert!(log.iter().any(|a| a == action), "missing {action} in {log:?}"); } }