//! 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()), hubs: vec![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.hubs[0].clone(); 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.hubs.is_empty()); 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:?}"); } } // ---- Milestone 5: the canvas's sessions and the Undo window ---- #[test] fn canvas_session_and_undo_window() { 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")); let (_, sen_w) = hub::join(&owner_link, "Codex").unwrap(); let codex = as_device(&url, &sen_w); codex.create_vault("DevOps").unwrap(); let link = codex.invite("Alice", &[("DevOps".into(), "edit".into())]).unwrap(); hub::join(&link, "Alice laptop").unwrap(); as_device(&url, &sen_w); let agent: ureq::Agent = ureq::Agent::config_builder().http_status_as_error(false).build().into(); // Sign in with a pairing code: the browser gets a session cookie. let res = agent.post(format!("{url}/api/web/signin")).send_json(serde_json::json!({ "code": codex.pair().unwrap() })).unwrap(); assert_eq!(res.status(), 200); let cookie = res.headers().get("set-cookie").unwrap().to_str().unwrap().to_string(); assert!(cookie.contains("HttpOnly") && cookie.contains("SameSite=Strict"), "{cookie}"); let session = cookie.split(';').next().unwrap().to_string(); // Without the canvas header, a cookie alone gets nothing (no cross-site requests). let res = agent.get(format!("{url}/api/canvas")).header("Cookie", &session).call().unwrap(); assert_eq!(res.status(), 403); let canvas = |agent: &ureq::Agent| -> serde_json::Value { agent.get(format!("{url}/api/canvas")).header("Cookie", &session).header("X-Lune", "1").call().unwrap().body_mut().read_json().unwrap() }; let c = canvas(&agent); assert_eq!(c["me"]["person"], "Sen"); assert_eq!(c["members"].as_array().unwrap().len(), 2); let post = |path: &str, body: serde_json::Value| -> serde_json::Value { agent.post(format!("{url}{path}")).header("Cookie", &session).header("X-Lune", "1").send_json(body).unwrap().body_mut().read_json().unwrap() }; let alice_has_devops = || codex.members("DevOps").unwrap().iter().any(|m| m.person == "Alice"); // Pull the ribbon, then Undo inside the window: nothing happened. let pending = post("/api/remove", serde_json::json!({"person": "Alice", "vault": "DevOps", "delay_seconds": 2}))["pending"].as_i64().unwrap(); assert!(alice_has_devops(), "still a member during the Undo window"); post("/api/remove/undo", serde_json::json!({ "pending": pending })); std::thread::sleep(std::time::Duration::from_millis(3500)); assert!(alice_has_devops()); // Pull again and let the window pass: the removal goes through. post("/api/remove", serde_json::json!({"person": "Alice", "vault": "DevOps", "delay_seconds": 1})); std::thread::sleep(std::time::Duration::from_millis(3000)); assert!(!alice_has_devops()); let undo = post("/api/remove/undo", serde_json::json!({ "pending": pending })); assert!(undo["error"].as_str().unwrap().contains("too late")); // Signing out ends the session. post("/api/web/signout", serde_json::json!({})); let res = agent.get(format!("{url}/api/canvas")).header("Cookie", &session).header("X-Lune", "1").call().unwrap(); assert_eq!(res.status(), 401); } // ---- Milestone 6: freshness, Nudge, tidying on the canvas ---- #[test] fn health_nudge_and_tidy() { 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")); let (_, sen_w) = hub::join(&owner_link, "Codex").unwrap(); let codex = as_device(&url, &sen_w); let devops = codex.create_vault("DevOps").unwrap(); let hermes_w = hub::login(&url, &codex.pair().unwrap(), "Hermes").unwrap(); // The same lines changed on two devices: the hub's copy keeps both. as_device(&url, &sen_w); let (cfg_a, _, _) = vault::add("DevOps", &tmp.path().join("codex"), &devops.git_url, "Codex").unwrap(); let a = Vault::open(&cfg_a, "Codex").unwrap(); std::fs::write(a.root.join("runbook.md"), "restart: TODO\n").unwrap(); a.save_changes(None, &HashSet::new()).unwrap(); a.sync().unwrap(); let hermes = as_device(&url, &hermes_w); let (cfg_h, _, _) = vault::add("DevOps", &tmp.path().join("hermes"), &devops.git_url, "Hermes").unwrap(); let h = Vault::open(&cfg_h, "Hermes").unwrap(); as_device(&url, &sen_w); std::fs::write(a.root.join("runbook.md"), "restart: systemctl\n").unwrap(); a.save_changes(None, &HashSet::new()).unwrap(); a.sync().unwrap(); as_device(&url, &hermes_w); std::fs::write(h.root.join("runbook.md"), "restart: docker\n").unwrap(); h.save_changes(None, &HashSet::new()).unwrap(); h.sync().unwrap(); // Codex reports something waiting; Hermes never reports. let codex = as_device(&url, &sen_w); std::fs::write(a.root.join("draft.md"), "unsaved\n").unwrap(); codex .report(&[hub::VaultHealth { vault_id: devops.id, last_synced: Some(1), waiting: 1, held_secrets: 0, holding: false }]) .unwrap(); let agent: ureq::Agent = ureq::Agent::config_builder().http_status_as_error(false).build().into(); let res = agent.post(format!("{url}/api/web/signin")).send_json(serde_json::json!({ "code": codex.pair().unwrap() })).unwrap(); let session = res.headers().get("set-cookie").unwrap().to_str().unwrap().split(';').next().unwrap().to_string(); let get = |path: &str| -> serde_json::Value { agent.get(format!("{url}{path}")).header("Cookie", &session).header("X-Lune", "1").call().unwrap().body_mut().read_json().unwrap() }; let post = |path: &str, body: serde_json::Value| -> serde_json::Value { agent.post(format!("{url}{path}")).header("Cookie", &session).header("X-Lune", "1").send_json(body).unwrap().body_mut().read_json().unwrap() }; let canvas = get("/api/canvas"); let devices = canvas["people"][0]["devices"].as_array().unwrap().clone(); let status = |label: &str| devices.iter().find(|d| d["label"] == label).unwrap()["health"]["status"].clone(); assert_eq!(status("Codex"), "behind"); assert_eq!(status("Hermes"), "offline"); let tidy = canvas["vaults"][0]["tidy"].as_array().unwrap().clone(); assert_eq!(tidy.len(), 1, "{canvas}"); let copy = tidy[0]["copy"].as_str().unwrap().to_string(); // Nudge reaches Hermes exactly once. let hermes_id = devices.iter().find(|d| d["label"] == "Hermes").unwrap()["id"].as_str().unwrap().to_string(); post("/api/nudge", serde_json::json!({ "device_id": hermes_id })); as_device(&url, &hermes_w); assert!(hermes.me().unwrap().nudge); assert!(!hermes.me().unwrap().nudge); // Compare side by side, then keep the copy's version: the copy disappears everywhere. let c = post("/api/tidy/compare", serde_json::json!({ "vault": "DevOps", "copy": copy })); assert_eq!(c["note_text"], "restart: systemctl\n"); assert_eq!(c["copy_text"], "restart: docker\n"); let r = post("/api/tidy/resolve", serde_json::json!({ "vault": "DevOps", "copy": copy, "keep": "copy" })); assert!(r["message"].as_str().unwrap().contains("kept Hermes's version"), "{r}"); as_device(&url, &sen_w); a.save_changes(None, &HashSet::new()).unwrap(); a.sync().unwrap(); assert_eq!(std::fs::read(a.root.join("runbook.md")).unwrap(), b"restart: docker\n"); assert!(!a.root.join(©).exists()); assert!(get("/api/canvas")["vaults"][0]["tidy"].as_array().unwrap().is_empty()); } fn lunehub(data: &std::path::Path, args: &[&str]) -> std::process::Output { Command::new(env!("CARGO_BIN_EXE_lunehub")) .args(args) .env("LUNE_HUB_DATA", data) .env("LUNE_RELEASE_PASSWORD", "test only") .output() .unwrap() } #[test] fn releases_are_signed_on_the_hub_and_old_clients_are_asked_to_update() { use base64::Engine; let _turn = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); let tmp = tempfile::TempDir::new().unwrap(); let data = tmp.path().join("data"); let (_hub, url, owner_link) = start_hub(&data); // The key is made on the hub; only the public half leaves it. let made = lunehub(&data, &["release", "keygen"]); assert!(made.status.success(), "{}", String::from_utf8_lossy(&made.stderr)); let pubkey = String::from_utf8(made.stdout).unwrap().lines().last().unwrap().trim().to_string(); assert!(!lunehub(&data, &["release", "keygen"]).status.success(), "a second key would orphan every app"); let update = tmp.path().join("Lune.app.tar.gz"); let dmg = tmp.path().join("Lune.dmg"); for v in ["0.1.0", "0.2.0", "0.3.0"] { std::fs::write(&update, format!("app {v}")).unwrap(); std::fs::write(&dmg, format!("dmg {v}")).unwrap(); let out = lunehub(&data, &["release", "publish", v, update.to_str().unwrap(), dmg.to_str().unwrap(), "Notes"]); assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); } let again = lunehub(&data, &["release", "publish", "0.2.5", update.to_str().unwrap(), dmg.to_str().unwrap()]); assert!(!again.status.success(), "versions only go up"); // The updater's question: 0.2.0 gets 0.3.0, signed with the hub's key, version bound in the signature. let agent = ureq::Agent::config_builder().http_status_as_error(false).build().new_agent(); let mut res = agent.get(format!("{url}/api/update/darwin/aarch64/0.2.0")).call().unwrap(); assert_eq!(res.status(), 200); let offer: serde_json::Value = res.body_mut().read_json().unwrap(); assert_eq!(offer["version"], "0.3.0"); let bytes = agent.get(offer["url"].as_str().unwrap()).call().unwrap().body_mut().read_to_vec().unwrap(); assert_eq!(bytes, b"app 0.3.0"); let b64 = |s: &str| String::from_utf8(base64::engine::general_purpose::STANDARD.decode(s).unwrap()).unwrap(); let pk = minisign::PublicKeyBox::from_string(&b64(&pubkey)).unwrap().into_public_key().unwrap(); let sig = minisign::SignatureBox::from_string(&b64(offer["signature"].as_str().unwrap())).unwrap(); assert!(sig.trusted_comment().unwrap().contains("\tversion:0.3.0")); minisign::verify(&pk, &sig, std::io::Cursor::new(&bytes), true, false, false).unwrap(); assert_eq!(agent.get(format!("{url}/api/update/darwin/aarch64/0.3.0")).call().unwrap().status(), 204); let mut dl = agent.get(format!("{url}/download/mac")).call().unwrap(); assert_eq!(dl.body_mut().read_to_vec().unwrap(), b"dmg 0.3.0"); // A second hub (a workplace) offers the same signed release without ever holding the key. let work = tmp.path().join("work"); std::fs::create_dir_all(&work).unwrap(); let imported = lunehub(&work, &["release", "import", data.join("releases/0.3.0").to_str().unwrap()]); assert!(imported.status.success(), "{}", String::from_utf8_lossy(&imported.stderr)); assert!(!work.join("release/update.key").exists()); assert_eq!(std::fs::read(work.join("releases/0.3.0/release.json")).unwrap(), std::fs::read(data.join("releases/0.3.0/release.json")).unwrap()); // 0.1.0 is two releases behind: it keeps its place on the team but can't sync until it updates. remote::set_client_version("0.3.0"); let (_, sen) = hub::join(&owner_link, "Codex").unwrap(); let codex = as_device(&url, &sen); let devops = codex.create_vault("DevOps").unwrap(); let (cfg, _, _) = vault::add("DevOps", &tmp.path().join("codex"), &devops.git_url, "Codex").unwrap(); let v = Vault::open(&cfg, "Codex").unwrap(); remote::set_client_version("0.1.0"); assert!(format!("{:#}", codex.me().unwrap_err()).contains(remote::TOO_OLD)); std::fs::write(v.root.join("note.md"), "kept while outdated\n").unwrap(); assert!(v.save_changes(None, &HashSet::new()).unwrap().is_some(), "saving locally goes on"); assert_eq!(remote::describe_error(&v.sync().unwrap_err()), remote::TOO_OLD); // One release behind still syncs. remote::set_client_version("0.2.0"); assert_eq!(codex.me().unwrap().vaults.len(), 1); v.sync().unwrap(); assert_eq!(v.waiting_files().unwrap(), 0); remote::set_client_version(env!("CARGO_PKG_VERSION")); } #[test] fn one_device_on_two_hubs_keeps_the_teams_apart() { let _turn = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); let tmp = tempfile::TempDir::new().unwrap(); let (_own, own_url, own_link) = start_hub(&tmp.path().join("own")); let (_work, work_url, work_link) = start_hub(&tmp.path().join("work")); // Sen's own hub, with a Notes vault and a second device to read it from. let (_, sen_w) = hub::join(&own_link, "Mac").unwrap(); let mut mac = device(&own_url, &sen_w, "Mac", &tmp.path().join("mac")); mac.use_hub_credentials(); mac.hubs[0].create_vault("Notes").unwrap(); let code = mac.hubs[0].pair().unwrap(); let hermes_w = hub::login(&own_url, &code, "Hermes").unwrap(); let mut hermes = device(&own_url, &hermes_w, "Hermes", &tmp.path().join("hermes")); // The workplace hub (its owner is also called Sen by the test hub) has a Notes too; it invites Mov Sen. let (_, boss_w) = hub::join(&work_link, "Boss pc").unwrap(); let mut boss = device(&work_url, &boss_w, "Boss pc", &tmp.path().join("boss")); boss.use_hub_credentials(); boss.hubs[0].create_vault("Notes").unwrap(); let invite = boss.hubs[0].invite("Mov Sen", &[("Notes".into(), "edit".into())]).unwrap(); let (url, w) = hub::join(&invite, "Mac").unwrap(); mac.hubs.push(HubLink { url, device_id: w.device_id, key: w.key }); // Both arrive, in separate folders, each tied to its own hub. let said = check_in(&mut mac); assert_eq!(mac.vaults.len(), 2, "{said:?}"); let own_notes = mac.vaults.iter().find(|v| v.hub_url.as_deref() == Some(own_url.as_str())).unwrap().clone(); let work_notes = mac.vaults.iter().find(|v| v.hub_url.as_deref() == Some(work_url.as_str())).unwrap().clone(); assert_ne!(own_notes.path, work_notes.path); mac.use_hub_credentials(); let label = mac.device_label(); let (a, b) = (Vault::open(&own_notes, &label).unwrap(), Vault::open(&work_notes, &label).unwrap()); write_and_save(&a, "home.md", "mine\n"); write_and_save(&b, "work.md", "the company's\n"); a.sync().unwrap(); b.sync().unwrap(); check_in(&mut hermes); let h = open(&hermes, "Notes"); h.sync().unwrap(); assert!(h.root.join("home.md").exists() && !h.root.join("work.md").exists()); check_in(&mut boss); let bn = open(&boss, "Notes"); bn.sync().unwrap(); assert!(bn.root.join("work.md").exists() && !bn.root.join("home.md").exists()); // The workplace takes Sen's access back: only that folder leaves. boss.use_hub_credentials(); boss.hubs[0].remove("Mov Sen", "Notes", false).unwrap(); check_in(&mut mac); assert!(!work_notes.path.exists()); assert_eq!(std::fs::read(own_notes.path.join("home.md")).unwrap(), b"mine\n"); assert_eq!(mac.vaults.len(), 1); let a = open(&mac, "Notes"); write_and_save(&a, "home.md", "still mine\n"); a.sync().unwrap(); } #[test] fn a_single_hub_config_from_before_moves_into_the_list() { let tmp = tempfile::TempDir::new().unwrap(); std::fs::write( tmp.path().join("config.toml"), "device_name = \"Mac\"\n\n[hub]\nurl = \"https://hub.example\"\ndevice_id = \"dev_1\"\nkey = \"k\"\n\n\ [[vault]]\nname = \"Notes\"\npath = \"/tmp/notes\"\nremote = \"https://hub.example/git/1.git\"\nbranch = \"main\"\nhub_vault = 1\n", ) .unwrap(); let _turn = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); unsafe { std::env::set_var("LUNE_HOME", tmp.path()) }; let c = Config::load().unwrap(); unsafe { std::env::remove_var("LUNE_HOME") }; assert_eq!(c.hubs.len(), 1); assert_eq!(c.vaults[0].hub_url.as_deref(), Some("https://hub.example")); assert_eq!(c.hub_of(&c.vaults[0]).unwrap().device_id, "dev_1"); }