Leave a team, delete a vault; keep tests out of the real settings

- A hub test unset LUNE_HOME for the whole test run, so later tests saved
  into the real user's config. Tests now always keep their own settings
  folder.
- Leaving a team: `lunesync leave` and the app's Leave hand over and remove
  this device there; a hub that's gone can be forgotten (folders stay).
- Deleting a vault (owner): everyone is removed the usual way, the history
  is archived on the hub and the name is freed. Canvas asks first.
- Connect this Mac says what to do when Lune isn't installed.
- Update checks skip http hubs instead of failing for all of them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-29 14:36:46 +07:00
parent 7d1437e3ec
commit 4f6414b256
16 changed files with 278 additions and 10 deletions

View File

@@ -105,6 +105,7 @@ pub fn open(data: &Path) -> Result<Connection> {
("invites", "account_id INTEGER"),
("devices", "last_seen INTEGER"),
("devices", "nudge INTEGER NOT NULL DEFAULT 0"),
("vaults", "archived INTEGER"),
] {
let _ = conn.execute(&format!("ALTER TABLE {table} ADD COLUMN {column}"), []);
}
@@ -208,7 +209,9 @@ pub fn new_device(conn: &Connection, account_id: i64, label: &str) -> Result<(St
}
pub fn vault_id(conn: &Connection, name: &str) -> Result<Option<(i64, String)>> {
Ok(conn.query_row("SELECT id, name FROM vaults WHERE name = ?1", [name], |r| Ok((r.get(0)?, r.get(1)?))).optional()?)
Ok(conn
.query_row("SELECT id, name FROM vaults WHERE name = ?1 AND archived IS NULL", [name], |r| Ok((r.get(0)?, r.get(1)?)))
.optional()?)
}
pub fn role(conn: &Connection, account_id: i64, vault_id: i64) -> Result<Option<String>> {

View File

@@ -240,6 +240,35 @@ pub async fn team_restore(State(hub): State<Shared>, headers: HeaderMap, Json(re
Ok(Json(json!({ "link": format!("{}/join/{token}", hub.url) })))
}
#[derive(Deserialize)]
pub struct DeleteVaultReq {
vault: String,
}
/// Deleting a vault (team owner): everyone is removed from it the usual way, so every device hands over what it
/// hadn't shared and removes its copy (A6, A7). The history stays archived on the hub; the name is free again.
pub async fn delete_vault(State(hub): State<Shared>, headers: HeaderMap, Json(req): Json<DeleteVaultReq>) -> ApiResult {
let caller = authenticate(&hub, &headers)?;
if !caller.owner {
return Err(denied("only the team owner can delete a vault"));
}
let conn = hub.db.lock().unwrap();
let (vault_id, vault) = db::vault_id(&conn, &req.vault)?.ok_or_else(|| bad(format!("no vault named {}", req.vault)))?;
conn.execute("DELETE FROM pending_removals WHERE vault_id = ?1", [vault_id])?;
let members: Vec<i64> = {
let mut stmt = conn.prepare("SELECT account_id FROM memberships WHERE vault_id = ?1")?;
stmt.query_map([vault_id], |r| r.get(0))?.collect::<Result<_, _>>()?
};
let mut devices = 0;
for account_id in members {
devices += apply_removal(&conn, &caller.who(), account_id, vault_id, false)?;
}
let archived = format!("{vault} (deleted {} #{vault_id})", chrono::Utc::now().format("%Y-%m-%d"));
conn.execute("UPDATE vaults SET archived = ?1, name = ?2 WHERE id = ?3", params![db::now(), archived, vault_id])?;
db::log(&conn, &caller.who(), "vault deleted", &format!("{vault} ({}; its history is archived on the hub)", devices_phrase(devices)))?;
Ok(Json(json!({ "devices": devices })))
}
#[derive(Deserialize)]
pub struct SettingsReq {
vault: String,

View File

@@ -109,6 +109,7 @@ async fn serve() -> Result<()> {
.route("/api/team/remove", post(leave::team_remove))
.route("/api/team/restore", post(leave::team_restore))
.route("/api/vaults/settings", post(leave::vault_settings))
.route("/api/vaults/delete", post(leave::delete_vault))
.route("/api/departures/done", post(leave::departure_done))
.route("/api/handovers", get(leave::handovers))
.route("/api/handovers/show", post(leave::handover_show))

View File

@@ -117,7 +117,7 @@ pub async fn canvas(State(hub): State<Shared>, headers: HeaderMap) -> ApiResult
let vault_rows: Vec<(i64, String, bool)> = {
let sql = if caller.owner {
"SELECT id, name, delete_from_devices FROM vaults ORDER BY created, id"
"SELECT id, name, delete_from_devices FROM vaults WHERE archived IS NULL ORDER BY created, id"
} else {
"SELECT v.id, v.name, v.delete_from_devices FROM vaults v JOIN memberships m ON m.vault_id = v.id
WHERE m.account_id = ?1 ORDER BY v.created, v.id"

View File

@@ -18,7 +18,14 @@ impl Drop for HubProcess {
}
}
/// A settings folder for every test that doesn't pick its own: check-ins save settings, and without
/// `LUNE_HOME` that would be the real user's.
static HOME: std::sync::OnceLock<tempfile::TempDir> = std::sync::OnceLock::new();
fn start_hub(data: &std::path::Path) -> (HubProcess, String, String) {
if std::env::var_os("LUNE_HOME").is_none() {
unsafe { std::env::set_var("LUNE_HOME", HOME.get_or_init(|| tempfile::TempDir::new().unwrap()).path()) };
}
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"))
@@ -473,6 +480,8 @@ fn releases_are_signed_on_the_hub_and_old_clients_are_asked_to_update() {
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();
// Check-ins save the settings; keep them in this test's folder.
unsafe { std::env::set_var("LUNE_HOME", tmp.path().join("cfg")) };
let (_own, own_url, own_link) = start_hub(&tmp.path().join("own"));
let (_work, work_url, work_link) = start_hub(&tmp.path().join("work"));
@@ -539,10 +548,76 @@ fn a_single_hub_config_from_before_moves_into_the_list() {
)
.unwrap();
let _turn = SERIAL.lock().unwrap_or_else(|e| e.into_inner());
// Put back whatever home the other tests use: without one, saving would write the real user's settings.
let before = std::env::var_os("LUNE_HOME");
unsafe { std::env::set_var("LUNE_HOME", tmp.path()) };
let c = Config::load().unwrap();
unsafe { std::env::remove_var("LUNE_HOME") };
match before {
Some(home) => unsafe { std::env::set_var("LUNE_HOME", home) },
None => unsafe { std::env::set_var("LUNE_HOME", tmp.path().join("unused")) },
}
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");
}
#[test]
fn deleting_a_vault_and_leaving_a_team() {
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);
let (_, sen_w) = hub::join(&owner_link, "Mac").unwrap();
let mut mac = device(&url, &sen_w, "Mac", &tmp.path().join("mac"));
mac.use_hub_credentials();
let sandbox = mac.hubs[0].create_vault("Sandbox").unwrap();
check_in(&mut mac);
let v = open(&mac, "Sandbox");
write_and_save(&v, "try.md", "hello\n");
v.sync().unwrap();
write_and_save(&v, "unshared.md", "not sent yet\n");
let folder = v.root.clone();
drop(v);
// Deleting: the device hands over what it hadn't shared, then its copy goes; the history stays on the hub.
assert_eq!(mac.hubs[0].delete_vault("Sandbox").unwrap(), 1);
let said = check_in(&mut mac);
assert!(!folder.exists(), "{said:?}");
assert!(mac.vaults.is_empty());
let repo = lune_core::git2::Repository::open_bare(data.join(format!("repos/{}.git", sandbox.id))).unwrap();
assert!(repo.references_glob("refs/handover/*").unwrap().count() == 1, "the unshared note was handed over");
// The name is free again, and a non-owner can't delete.
mac.use_hub_credentials();
assert_eq!(mac.hubs[0].create_vault("Sandbox").unwrap().name, "Sandbox");
let invite = mac.hubs[0].invite("Alice", &[("Sandbox".into(), "manage".into())]).unwrap();
let (_, alice_w) = hub::join(&invite, "Alice pc").unwrap();
let alice = as_device(&url, &alice_w);
assert!(alice.delete_vault("Sandbox").is_err());
// Leaving a team: the hub is told, the device's vaults leave, and the team is gone from this device.
let mut a = device(&url, &alice_w, "Alice pc", &tmp.path().join("alice"));
check_in(&mut a);
assert_eq!(a.vaults.len(), 1);
let alice_folder = a.vaults[0].path.clone();
let said = lune_core::membership::leave_hub(&mut a, &url, false).unwrap();
assert!(a.hubs.is_empty() && a.vaults.is_empty(), "{said:?}");
assert!(!alice_folder.exists());
mac.use_hub_credentials();
assert!(mac.hubs[0].members("Sandbox").unwrap().iter().all(|m| m.devices.is_empty() || m.person != "Alice"));
// A team whose hub is gone: leaving needs `forget`, and the folder stays.
let mut stale = device("http://127.0.0.1:9", &alice_w, "Old", &tmp.path().join("stale"));
let kept = tmp.path().join("stale-notes");
std::fs::create_dir_all(&kept).unwrap();
stale.vaults.push(lune_core::config::VaultConfig {
name: "Notes".into(),
path: kept.clone(),
remote: "http://127.0.0.1:9/git/1.git".into(),
branch: "main".into(),
hub_vault: Some(1),
hub_url: Some("http://127.0.0.1:9".into()),
});
assert!(lune_core::membership::leave_hub(&mut stale, "http://127.0.0.1:9", false).is_err());
lune_core::membership::leave_hub(&mut stale, "http://127.0.0.1:9", true).unwrap();
assert!(stale.hubs.is_empty() && stale.vaults.is_empty() && kept.exists());
}