Milestone 4: taking access back

Removing someone from a vault, a device, or the team opens departures
on the hub. Each device stops syncing, saves, goes read-only, hands
unshared work over (secrets redacted), and deletes the folder only if
the app created it. Managers review handovers (show/keep/discard/skip);
removed devices may only hand over, then their key is retired. Adds the
delete-from-devices vault setting and team restore.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-29 06:14:28 +07:00
parent 2b4ca84a6b
commit 4025726083
16 changed files with 1222 additions and 133 deletions

177
core/src/membership.rs Normal file
View File

@@ -0,0 +1,177 @@
//! Keeping this device in line with its hub memberships: vaults arrive, and vaults whose access ended
//! are handed over and leave (A6).
use crate::config::Config;
use crate::hub::{self, Departure, HubLink};
use crate::secrets;
use crate::state;
use crate::vault::{self, Vault};
use anyhow::{Result, bail};
use std::path::Path;
use std::time::{Duration, Instant};
/// What a leaving note gets instead of a secret: the secret itself is never sent or kept (P1).
const REDACTED: &str = "[secret removed when leaving]";
/// New vaults arrive, same-named local vaults move onto the hub, roles refresh, and vaults whose access
/// ended are handed over and leave. Returns what happened, in plain words.
pub fn arrive(config: &mut Config) -> Result<Vec<String>> {
let Some(h) = config.hub.clone() else { return Ok(vec![]) };
let me = match h.me() {
Ok(me) => me,
Err(e) if format!("{e}").contains("isn't signed in") => {
// The hub no longer knows this device: it was removed and has nothing left to hand over.
config.hub = None;
config.vaults.retain(|v| v.hub_vault.is_none());
config.save()?;
return Ok(vec!["This device was removed from the hub. Vaults on other remotes keep syncing.".into()]);
}
Err(e) => return Err(e),
};
let label = config.device_label();
let mut said = vec![];
for d in &me.leaving {
said.push(leave(config, &h, d)?);
}
for hv in me.vaults {
if let Some(vc) = config.vaults.iter().find(|v| v.hub_vault == Some(hv.id)) {
let v = Vault::open(vc, &label)?;
state::write_role(&v.git_dir, &hv.role)?;
continue;
}
if let Some(vc) = config.vaults.iter_mut().find(|v| v.hub_vault.is_none() && v.name.eq_ignore_ascii_case(&hv.name)) {
let v = Vault::open(vc, &label)?;
let _op = state::op_lock(&v.git_dir)?;
v.relink(&hv.git_url)?;
state::write_role(&v.git_dir, &hv.role)?;
v.join_unrelated()?;
vc.remote = hv.git_url.clone();
vc.hub_vault = Some(hv.id);
config.save()?;
said.push(format!("{} now syncs through the hub", hv.name));
continue;
}
let path = config.vaults_dir().join(&hv.name);
if path.exists() && std::fs::read_dir(&path)?.next().is_some() && !path.join(".git").exists() {
said.push(format!("{} can't arrive: {} already has other files in it", hv.name, path.display()));
continue;
}
let (mut cfg, _, err) = vault::add(&hv.name, &path, &hv.git_url, &label)?;
cfg.hub_vault = Some(hv.id);
state::write_role(&path.join(".git"), &hv.role)?;
config.vaults.push(cfg);
config.save()?;
let note = if hub::can_edit(&hv.role) { String::new() } else { " (read access)".into() };
said.push(format!("{} arrived in {}{note}", hv.name, path.display()));
if let Some(e) = err {
said.push(format!(" not synced yet: {e}"));
}
}
Ok(said)
}
/// Leaves one vault: stop syncing, save, make read-only, hand over what wasn't shared, and once the
/// hub has it, delete the folder if the app created it.
pub fn leave(config: &mut Config, link: &HubLink, d: &Departure) -> Result<String> {
let label = config.device_label();
let Some(vc) = config.vaults.iter().find(|v| v.hub_vault == Some(d.vault_id)).cloned() else {
link.departure_done(d.id, None)?;
return Ok(format!("Access to {} ended (it wasn't on this device)", d.vault));
};
let v = Vault::open(&vc, &label)?;
let lune = state::lune_dir(&v.git_dir);
std::fs::create_dir_all(&lune)?;
std::fs::write(lune.join("leaving"), d.id.to_string())?;
// Wait for this vault's runner to notice and stop.
let deadline = Instant::now() + Duration::from_secs(60);
let _running = loop {
if let Some(lock) = state::try_run_lock(&v.git_dir)? {
break lock;
}
if Instant::now() > deadline {
bail!("{} is still busy syncing; will try leaving again shortly", d.vault);
}
std::thread::sleep(Duration::from_millis(250));
};
let _op = state::op_lock(&v.git_dir)?;
let mut head = None;
if !d.without_saving {
for note in v.secret_holds()? {
let path = v.root.join(&note.path);
if let Ok(text) = std::fs::read_to_string(&path) {
std::fs::write(&path, secrets::replace_with_pointer(&text, &note.hits, None, REDACTED))?;
}
}
v.save_unguarded(Some(&format!("Saved on {label} before leaving")))?;
}
set_read_only(&v.root, true)?;
if !d.without_saving
&& let Some(h) = v.head_commit()?
{
v.hand_over(&format!("refs/handover/{}", d.id))?;
head = Some(h.id().to_string());
}
link.departure_done(d.id, head)?;
let created = state::read_marker(&v.git_dir).is_some_and(|m| m.created_folder && m.managed_by == "lune");
config.vaults.retain(|x| x.path != vc.path);
config.save()?;
let sent = if d.without_saving { "nothing was sent" } else { "anything unshared was handed over" };
if d.delete_files && created {
set_read_only(&v.root, false)?;
drop(v);
// remove_dir_all removes links themselves, never what they point to (A9).
std::fs::remove_dir_all(&vc.path)?;
Ok(format!("Access to {} ended: {sent}, and the folder was deleted", d.vault))
} else {
let _ = std::fs::remove_file(lune.join("leaving"));
let why = if created { "this vault keeps copies on devices" } else { "you added this folder yourself" };
Ok(format!("Access to {} ended: {sent}. The folder stays at {}, read-only and no longer synced ({why})", d.vault, vc.path.display()))
}
}
/// Adds or removes write permission on everything in the vault folder except `.git`.
fn set_read_only(root: &Path, read_only: bool) -> Result<()> {
fn walk(dir: &Path, read_only: bool, top: bool) -> Result<()> {
for entry in std::fs::read_dir(dir)? {
let entry = entry?;
if top && entry.file_name() == ".git" {
continue;
}
let meta = entry.path().symlink_metadata()?;
if meta.file_type().is_symlink() {
continue;
}
if meta.is_dir() {
walk(&entry.path(), read_only, false)?;
}
let mut perms = meta.permissions();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let mode = perms.mode();
perms.set_mode(if read_only { mode & !0o222 } else { mode | 0o200 });
}
#[cfg(not(unix))]
perms.set_readonly(read_only);
std::fs::set_permissions(entry.path(), perms)?;
}
Ok(())
}
walk(root, read_only, true)?;
let mut perms = std::fs::metadata(root)?.permissions();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let mode = perms.mode();
perms.set_mode(if read_only { mode & !0o222 } else { mode | 0o200 });
}
#[cfg(not(unix))]
perms.set_readonly(read_only);
std::fs::set_permissions(root, perms)?;
Ok(())
}