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:
@@ -29,6 +29,32 @@ pub struct Me {
|
||||
pub owner: bool,
|
||||
pub device_label: String,
|
||||
pub vaults: Vec<HubVault>,
|
||||
/// Vaults this device must leave (access ended).
|
||||
#[serde(default)]
|
||||
pub leaving: Vec<Departure>,
|
||||
}
|
||||
|
||||
/// A vault this device has to hand over and leave (A6).
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct Departure {
|
||||
pub id: i64,
|
||||
pub vault_id: i64,
|
||||
pub vault: String,
|
||||
pub delete_files: bool,
|
||||
/// A manager chose "delete without saving".
|
||||
pub without_saving: bool,
|
||||
}
|
||||
|
||||
/// A departure as a manager sees it.
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct Handover {
|
||||
pub id: i64,
|
||||
pub vault: String,
|
||||
pub person: String,
|
||||
pub device: String,
|
||||
/// waiting (device hasn't reported in), received (to review), kept, discarded, done, skipped
|
||||
pub state: String,
|
||||
pub at: i64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
@@ -153,6 +179,55 @@ impl HubLink {
|
||||
}
|
||||
}
|
||||
|
||||
impl HubLink {
|
||||
pub fn remove(&self, person: &str, vault: &str, without_saving: bool) -> Result<usize> {
|
||||
let v: Value = self.post("/api/remove", json!({"person": person, "vault": vault, "without_saving": without_saving}))?;
|
||||
Ok(v["devices"].as_u64().unwrap_or(0) as usize)
|
||||
}
|
||||
|
||||
pub fn remove_device(&self, label: &str, person: Option<&str>) -> Result<()> {
|
||||
let _: Value = self.post("/api/device/remove", json!({"label": label, "person": person}))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn team_remove(&self, person: &str) -> Result<()> {
|
||||
let _: Value = self.post("/api/team/remove", json!({ "person": person }))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Re-enables a removed person; returns a one-time sign-in link.
|
||||
pub fn team_restore(&self, person: &str) -> Result<String> {
|
||||
let v: Value = self.post("/api/team/restore", json!({ "person": person }))?;
|
||||
Ok(v["link"].as_str().unwrap_or_default().to_string())
|
||||
}
|
||||
|
||||
pub fn handovers(&self) -> Result<Vec<Handover>> {
|
||||
self.get("/api/handovers")
|
||||
}
|
||||
|
||||
/// Changed files in a received handover, as "added/changed/removed path".
|
||||
pub fn handover_show(&self, id: i64) -> Result<Vec<String>> {
|
||||
self.post("/api/handovers/show", json!({ "id": id }))
|
||||
}
|
||||
|
||||
/// keep, discard or skip.
|
||||
pub fn handover_decide(&self, id: i64, decision: &str) -> Result<String> {
|
||||
let v: Value = self.post("/api/handovers/decide", json!({"id": id, "decision": decision}))?;
|
||||
Ok(v["message"].as_str().unwrap_or_default().to_string())
|
||||
}
|
||||
|
||||
pub fn vault_setting(&self, vault: &str, delete_from_devices: bool) -> Result<()> {
|
||||
let _: Value = self.post("/api/vaults/settings", json!({"vault": vault, "delete_from_devices": delete_from_devices}))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Tells the hub this device has handed over (`head`, if anything) and is leaving.
|
||||
pub fn departure_done(&self, id: i64, head: Option<String>) -> Result<()> {
|
||||
let _: Value = self.post("/api/departures/done", json!({"id": id, "head": head}))?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Is `role` allowed to share changes?
|
||||
pub fn can_edit(role: &str) -> bool {
|
||||
role == "edit" || role == "manage"
|
||||
|
||||
@@ -5,6 +5,7 @@ pub use git2;
|
||||
pub mod config;
|
||||
pub mod guard;
|
||||
pub mod hub;
|
||||
pub mod membership;
|
||||
pub mod names;
|
||||
pub mod remote;
|
||||
pub mod runner;
|
||||
|
||||
177
core/src/membership.rs
Normal file
177
core/src/membership.rs
Normal 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(¬e.path);
|
||||
if let Ok(text) = std::fs::read_to_string(&path) {
|
||||
std::fs::write(&path, secrets::replace_with_pointer(&text, ¬e.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(())
|
||||
}
|
||||
@@ -67,6 +67,9 @@ fn default_key_files() -> Vec<PathBuf> {
|
||||
/// Turns a remote failure into plain words for `status` and the run log.
|
||||
pub fn describe_error(e: &anyhow::Error) -> String {
|
||||
if let Some(g) = e.downcast_ref::<git2::Error>() {
|
||||
if g.message().contains("status code: 403") {
|
||||
return "the hub says this device has no access to this vault (if access ended, it will leave shortly)".into();
|
||||
}
|
||||
if g.code() == ErrorCode::Auth {
|
||||
return "the remote didn't accept our sign-in (check your SSH key or Git credentials)".into();
|
||||
}
|
||||
|
||||
@@ -94,7 +94,12 @@ pub fn run(cfg: &VaultConfig, label: &str, poll: Duration, timing: Timing, log:
|
||||
let mut was_holding = false;
|
||||
let mut was_read_only = false;
|
||||
let mut announced: HashSet<String> = HashSet::new();
|
||||
let leaving = state::lune_dir(&vault.git_dir).join("leaving");
|
||||
loop {
|
||||
if leaving.exists() {
|
||||
say("access to this vault ended — stopped syncing it");
|
||||
return Ok(());
|
||||
}
|
||||
let first = rx.recv_timeout(Duration::from_millis(250));
|
||||
for ev in first.into_iter().chain(rx.try_iter()) {
|
||||
match ev {
|
||||
|
||||
@@ -381,6 +381,27 @@ impl Vault {
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Sends this device's whole history to `dst` on the remote (the hub's handover area for this device).
|
||||
pub fn hand_over(&self, dst: &str) -> Result<()> {
|
||||
let mut remote = self.repo.find_remote("origin")?;
|
||||
let rejected = RefCell::new(None::<String>);
|
||||
let mut cb = remote::callbacks();
|
||||
cb.push_update_reference(|_, status| {
|
||||
if let Some(s) = status {
|
||||
*rejected.borrow_mut() = Some(s.to_string());
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
let mut opts = PushOptions::new();
|
||||
opts.remote_callbacks(cb);
|
||||
remote.push(&[format!("+{}:{dst}", self.branch_ref())], Some(&mut opts))?;
|
||||
drop(opts);
|
||||
if let Some(why) = rejected.into_inner() {
|
||||
bail!("the hub didn't take the handover: {why}");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// One sync round: fetch, combine, write the result to disk, share local history.
|
||||
pub fn sync(&self) -> Result<SyncReport> {
|
||||
let mut report = SyncReport::default();
|
||||
@@ -467,33 +488,7 @@ impl Vault {
|
||||
|
||||
/// Resolves every clash in `index` without markers: "their" version in place, ours beside it (S4).
|
||||
fn keep_both(&self, index: &mut git2::Index, kept_both: &mut Vec<(String, String)>) -> Result<()> {
|
||||
if index.has_conflicts() {
|
||||
let conflicts: Vec<_> = index.conflicts()?.collect::<Result<_, _>>()?;
|
||||
for c in conflicts {
|
||||
for e in [&c.ancestor, &c.our, &c.their].into_iter().flatten() {
|
||||
let _ = index.conflict_remove(&names::bytes_path(&e.path));
|
||||
}
|
||||
match (c.our, c.their) {
|
||||
(Some(ours), Some(theirs)) if ours.path == theirs.path && ours.id != theirs.id => {
|
||||
let note = String::from_utf8_lossy(&theirs.path).into_owned();
|
||||
let copy = (1..)
|
||||
.map(|n| names::copy_name(¬e, &self.label, n))
|
||||
.find(|p| index.get_path(Path::new(p), 0).is_none())
|
||||
.unwrap();
|
||||
index.add(&stage0(&theirs, None))?;
|
||||
index.add(&stage0(&ours, Some(copy.as_bytes())))?;
|
||||
kept_both.push((note, copy));
|
||||
}
|
||||
// Different paths, or one side removed the note: keep whatever still exists.
|
||||
(ours, theirs) => {
|
||||
for e in [ours, theirs].into_iter().flatten() {
|
||||
index.add(&stage0(&e, None))?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
keep_both(index, &self.label, kept_both)
|
||||
}
|
||||
|
||||
/// Paths that differ only by letter case can't coexist on macOS/Windows. There, rename the extras so
|
||||
@@ -641,6 +636,38 @@ impl Vault {
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolves every clash in `index` without markers: "their" version in place, ours beside it labeled
|
||||
/// with `label` (S4). Used for syncing, undo, and keeping handovers on the hub.
|
||||
pub fn keep_both(index: &mut git2::Index, label: &str, kept_both: &mut Vec<(String, String)>) -> Result<()> {
|
||||
if index.has_conflicts() {
|
||||
let conflicts: Vec<_> = index.conflicts()?.collect::<Result<_, _>>()?;
|
||||
for c in conflicts {
|
||||
for e in [&c.ancestor, &c.our, &c.their].into_iter().flatten() {
|
||||
let _ = index.conflict_remove(&names::bytes_path(&e.path));
|
||||
}
|
||||
match (c.our, c.their) {
|
||||
(Some(ours), Some(theirs)) if ours.path == theirs.path && ours.id != theirs.id => {
|
||||
let note = String::from_utf8_lossy(&theirs.path).into_owned();
|
||||
let copy = (1..)
|
||||
.map(|n| names::copy_name(¬e, label, n))
|
||||
.find(|p| index.get_path(Path::new(p), 0).is_none())
|
||||
.unwrap();
|
||||
index.add(&stage0(&theirs, None))?;
|
||||
index.add(&stage0(&ours, Some(copy.as_bytes())))?;
|
||||
kept_both.push((note, copy));
|
||||
}
|
||||
// Different paths, or one side removed the note: keep whatever still exists.
|
||||
(ours, theirs) => {
|
||||
for e in [ours, theirs].into_iter().flatten() {
|
||||
index.add(&stage0(&e, None))?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn blob_ids(tree: Option<&git2::Tree>) -> HashSet<Oid> {
|
||||
let mut ids = HashSet::new();
|
||||
if let Some(t) = tree {
|
||||
|
||||
Reference in New Issue
Block a user