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:
@@ -52,13 +52,13 @@ impl From<rusqlite::Error> for ApiError {
|
||||
}
|
||||
}
|
||||
|
||||
type ApiResult = Result<Json<Value>, ApiError>;
|
||||
pub type ApiResult = Result<Json<Value>, ApiError>;
|
||||
|
||||
fn bad(msg: impl Into<String>) -> ApiError {
|
||||
pub fn bad(msg: impl Into<String>) -> ApiError {
|
||||
ApiError(StatusCode::BAD_REQUEST, msg.into())
|
||||
}
|
||||
|
||||
fn denied(msg: impl Into<String>) -> ApiError {
|
||||
pub fn denied(msg: impl Into<String>) -> ApiError {
|
||||
ApiError(StatusCode::FORBIDDEN, msg.into())
|
||||
}
|
||||
|
||||
@@ -71,13 +71,23 @@ pub fn credentials(headers: &HeaderMap) -> Option<(String, String)> {
|
||||
Some((id.to_string(), key.to_string()))
|
||||
}
|
||||
|
||||
pub fn authenticate(hub: &Hub, headers: &HeaderMap) -> Result<Caller, ApiError> {
|
||||
/// The signed-in device, including one that was removed and may only hand over.
|
||||
pub fn authenticate_any(hub: &Hub, headers: &HeaderMap) -> Result<Caller, ApiError> {
|
||||
let unknown = || ApiError(StatusCode::UNAUTHORIZED, "this device isn't signed in to the hub".into());
|
||||
let (id, key) = credentials(headers).ok_or_else(unknown)?;
|
||||
let conn = hub.db.lock().unwrap();
|
||||
db::caller(&conn, &id, &key)?.ok_or_else(unknown)
|
||||
}
|
||||
|
||||
/// The signed-in device, if it still has normal access.
|
||||
pub fn authenticate(hub: &Hub, headers: &HeaderMap) -> Result<Caller, ApiError> {
|
||||
let caller = authenticate_any(hub, headers)?;
|
||||
if !caller.active {
|
||||
return Err(denied("this device was removed from the hub"));
|
||||
}
|
||||
Ok(caller)
|
||||
}
|
||||
|
||||
const ROLES: [&str; 3] = ["read", "edit", "manage"];
|
||||
|
||||
fn check_label(label: &str) -> Result<String, ApiError> {
|
||||
@@ -89,7 +99,7 @@ fn check_label(label: &str) -> Result<String, ApiError> {
|
||||
}
|
||||
|
||||
/// Owners can manage every vault; others need the Manage role on it.
|
||||
fn can_manage(conn: &Connection, caller: &Caller, vault_id: i64) -> Result<bool, ApiError> {
|
||||
pub fn can_manage(conn: &Connection, caller: &Caller, vault_id: i64) -> Result<bool, ApiError> {
|
||||
Ok(caller.owner || db::role(conn, caller.account_id, vault_id)?.as_deref() == Some("manage"))
|
||||
}
|
||||
|
||||
@@ -97,6 +107,9 @@ fn welcome(person: &str, device_id: String, key: String) -> ApiResult {
|
||||
Ok(Json(json!({ "person": person, "device_id": device_id, "key": key })))
|
||||
}
|
||||
|
||||
/// person, owner, grants (JSON), expires, used, account to restore
|
||||
type InviteRow = (String, bool, String, i64, Option<i64>, Option<i64>);
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct JoinReq {
|
||||
token: String,
|
||||
@@ -107,14 +120,14 @@ pub async fn join(State(hub): State<Shared>, Json(req): Json<JoinReq>) -> ApiRes
|
||||
let label = check_label(&req.device_label)?;
|
||||
let mut conn = hub.db.lock().unwrap();
|
||||
let tx = conn.transaction()?;
|
||||
let invite: Option<(String, bool, String, i64, Option<i64>)> = tx
|
||||
let invite: Option<InviteRow> = tx
|
||||
.query_row(
|
||||
"SELECT person, owner, grants, expires, used FROM invites WHERE token_hash = ?1",
|
||||
"SELECT person, owner, grants, expires, used, account_id FROM invites WHERE token_hash = ?1",
|
||||
[db::hash(&req.token)],
|
||||
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?)),
|
||||
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?, r.get(5)?)),
|
||||
)
|
||||
.optional()?;
|
||||
let Some((person, owner, grants, expires, used)) = invite else {
|
||||
let Some((person, owner, grants, expires, used, restored)) = invite else {
|
||||
return Err(denied("that invite link isn't valid"));
|
||||
};
|
||||
if used.is_some() {
|
||||
@@ -123,12 +136,18 @@ pub async fn join(State(hub): State<Shared>, Json(req): Json<JoinReq>) -> ApiRes
|
||||
if expires < db::now() {
|
||||
return Err(denied("that invite link has expired — ask for a new one"));
|
||||
}
|
||||
let taken: bool = tx.query_row("SELECT COUNT(*) > 0 FROM accounts WHERE name = ?1", [&person], |r| r.get(0))?;
|
||||
if taken {
|
||||
return Err(denied(format!("{person} already has an account — pair a device instead")));
|
||||
}
|
||||
tx.execute("INSERT INTO accounts (name, owner, created) VALUES (?1, ?2, ?3)", params![person, owner, db::now()])?;
|
||||
let account_id = tx.last_insert_rowid();
|
||||
let account_id = match restored {
|
||||
// A sign-in link for a restored account adds a device to it.
|
||||
Some(id) => id,
|
||||
None => {
|
||||
let taken: bool = tx.query_row("SELECT COUNT(*) > 0 FROM accounts WHERE name = ?1", [&person], |r| r.get(0))?;
|
||||
if taken {
|
||||
return Err(denied(format!("{person} already has an account — pair a device instead")));
|
||||
}
|
||||
tx.execute("INSERT INTO accounts (name, owner, created) VALUES (?1, ?2, ?3)", params![person, owner, db::now()])?;
|
||||
tx.last_insert_rowid()
|
||||
}
|
||||
};
|
||||
let grants: Vec<(i64, String)> = serde_json::from_str(&grants).map_err(anyhow::Error::from)?;
|
||||
let mut granted = vec![];
|
||||
for (vault_id, role) in &grants {
|
||||
@@ -139,7 +158,7 @@ pub async fn join(State(hub): State<Shared>, Json(req): Json<JoinReq>) -> ApiRes
|
||||
tx.execute("UPDATE invites SET used = ?1 WHERE token_hash = ?2", params![db::now(), db::hash(&req.token)])?;
|
||||
let (device_id, key) = db::new_device(&tx, account_id, &label)?;
|
||||
let who = format!("{person} ({label})");
|
||||
let what = if owner { "as team owner".to_string() } else if granted.is_empty() { "with no vaults".into() } else { granted.join(", ") };
|
||||
let what = if restored.is_some() { "to come back after being restored".to_string() } else if owner { "as team owner".to_string() } else if granted.is_empty() { "with no vaults".into() } else { granted.join(", ") };
|
||||
db::log(&tx, &who, "joined", &format!("accepted the invite {what}"))?;
|
||||
db::log(&tx, &who, "device added", &format!("{label} (first device)"))?;
|
||||
tx.commit()?;
|
||||
@@ -189,8 +208,25 @@ pub async fn pair(State(hub): State<Shared>, headers: HeaderMap) -> ApiResult {
|
||||
}
|
||||
|
||||
pub async fn me(State(hub): State<Shared>, headers: HeaderMap) -> ApiResult {
|
||||
let caller = authenticate(&hub, &headers)?;
|
||||
let caller = authenticate_any(&hub, &headers)?;
|
||||
let conn = hub.db.lock().unwrap();
|
||||
let mut stmt = conn.prepare(
|
||||
"SELECT d.id, d.vault_id, v.name, d.delete_files, d.without_saving FROM departures d JOIN vaults v ON v.id = d.vault_id
|
||||
WHERE d.device_id = ?1 AND d.state = 'waiting'",
|
||||
)?;
|
||||
let leaving: Vec<Value> = stmt
|
||||
.query_map([&caller.device_id], |r| {
|
||||
Ok(json!({
|
||||
"id": r.get::<_, i64>(0)?, "vault_id": r.get::<_, i64>(1)?, "vault": r.get::<_, String>(2)?,
|
||||
"delete_files": r.get::<_, bool>(3)?, "without_saving": r.get::<_, bool>(4)?
|
||||
}))
|
||||
})?
|
||||
.collect::<Result<_, _>>()?;
|
||||
if !caller.active {
|
||||
return Ok(Json(json!({
|
||||
"person": caller.person, "owner": false, "device_label": caller.device_label, "vaults": [], "leaving": leaving
|
||||
})));
|
||||
}
|
||||
let mut stmt = conn.prepare(
|
||||
"SELECT v.id, v.name, m.role FROM memberships m JOIN vaults v ON v.id = m.vault_id WHERE m.account_id = ?1 ORDER BY v.name",
|
||||
)?;
|
||||
@@ -201,7 +237,8 @@ pub async fn me(State(hub): State<Shared>, headers: HeaderMap) -> ApiResult {
|
||||
.map(|(id, name, role)| json!({ "id": id, "name": name, "role": role, "git_url": hub.git_url(id) }))
|
||||
.collect();
|
||||
Ok(Json(json!({
|
||||
"person": caller.person, "owner": caller.owner, "device_label": caller.device_label, "vaults": vaults
|
||||
"person": caller.person, "owner": caller.owner, "device_label": caller.device_label, "vaults": vaults,
|
||||
"leaving": leaving
|
||||
})))
|
||||
}
|
||||
|
||||
@@ -321,6 +358,10 @@ pub async fn grant(State(hub): State<Shared>, headers: HeaderMap, Json(req): Jso
|
||||
.query_row("SELECT id, name FROM accounts WHERE name = ?1", [req.person.trim()], |r| Ok((r.get(0)?, r.get(1)?)))
|
||||
.optional()?
|
||||
.ok_or_else(|| bad(format!("nobody named {} has joined yet — invite them first", req.person.trim())))?;
|
||||
let disabled: bool = conn.query_row("SELECT disabled FROM accounts WHERE id = ?1", [account_id], |r| r.get(0))?;
|
||||
if disabled {
|
||||
return Err(bad(format!("{person} was removed from the team — `lunesync team restore {person}` first")));
|
||||
}
|
||||
let before = db::role(&conn, account_id, g.0)?;
|
||||
db::grant(&conn, account_id, g.0, &g.2)?;
|
||||
let detail = match before {
|
||||
@@ -350,7 +391,7 @@ pub async fn members(State(hub): State<Shared>, headers: HeaderMap, Json(req): J
|
||||
stmt.query_map([id], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)))?.collect::<Result<_, _>>()?;
|
||||
let mut out = vec![];
|
||||
for (account_id, person, role) in rows {
|
||||
let mut d = conn.prepare("SELECT label FROM devices WHERE account_id = ?1 ORDER BY created")?;
|
||||
let mut d = conn.prepare("SELECT label FROM devices WHERE account_id = ?1 AND removed = 0 ORDER BY created")?;
|
||||
let devices: Vec<String> = d.query_map([account_id], |r| r.get(0))?.collect::<Result<_, _>>()?;
|
||||
out.push(json!({ "person": person, "role": role, "devices": devices }));
|
||||
}
|
||||
|
||||
@@ -51,6 +51,17 @@ CREATE TABLE IF NOT EXISTS not_secrets (
|
||||
fingerprint TEXT NOT NULL,
|
||||
PRIMARY KEY (vault_id, fingerprint)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS departures (
|
||||
id INTEGER PRIMARY KEY,
|
||||
vault_id INTEGER NOT NULL,
|
||||
account_id INTEGER NOT NULL,
|
||||
device_id TEXT NOT NULL,
|
||||
delete_files INTEGER NOT NULL,
|
||||
without_saving INTEGER NOT NULL DEFAULT 0,
|
||||
state TEXT NOT NULL,
|
||||
created INTEGER NOT NULL,
|
||||
updated INTEGER NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS log (
|
||||
id INTEGER PRIMARY KEY,
|
||||
at INTEGER NOT NULL,
|
||||
@@ -64,6 +75,15 @@ pub fn open(data: &Path) -> Result<Connection> {
|
||||
let conn = Connection::open(data.join("hub.sqlite"))?;
|
||||
conn.busy_timeout(std::time::Duration::from_secs(5))?;
|
||||
conn.execute_batch(SCHEMA)?;
|
||||
// Columns added after Milestone 3; adding one that exists fails harmlessly.
|
||||
for (table, column) in [
|
||||
("accounts", "disabled INTEGER NOT NULL DEFAULT 0"),
|
||||
("devices", "removed INTEGER NOT NULL DEFAULT 0"),
|
||||
("vaults", "delete_from_devices INTEGER NOT NULL DEFAULT 1"),
|
||||
("invites", "account_id INTEGER"),
|
||||
] {
|
||||
let _ = conn.execute(&format!("ALTER TABLE {table} ADD COLUMN {column}"), []);
|
||||
}
|
||||
Ok(conn)
|
||||
}
|
||||
|
||||
@@ -99,6 +119,8 @@ pub struct Caller {
|
||||
pub account_id: i64,
|
||||
pub person: String,
|
||||
pub owner: bool,
|
||||
/// False once the device was removed or the person removed from the team: it may only hand over.
|
||||
pub active: bool,
|
||||
}
|
||||
|
||||
impl Caller {
|
||||
@@ -111,11 +133,19 @@ impl Caller {
|
||||
pub fn caller(conn: &Connection, device_id: &str, key: &str) -> Result<Option<Caller>> {
|
||||
Ok(conn
|
||||
.query_row(
|
||||
"SELECT d.id, d.label, a.id, a.name, a.owner FROM devices d JOIN accounts a ON a.id = d.account_id
|
||||
WHERE d.id = ?1 AND d.key_hash = ?2",
|
||||
"SELECT d.id, d.label, a.id, a.name, a.owner, d.removed = 0 AND a.disabled = 0
|
||||
FROM devices d JOIN accounts a ON a.id = d.account_id
|
||||
WHERE d.id = ?1 AND d.key_hash = ?2 AND d.key_hash != ''",
|
||||
params![device_id, hash(key)],
|
||||
|r| {
|
||||
Ok(Caller { device_id: r.get(0)?, device_label: r.get(1)?, account_id: r.get(2)?, person: r.get(3)?, owner: r.get(4)? })
|
||||
Ok(Caller {
|
||||
device_id: r.get(0)?,
|
||||
device_label: r.get(1)?,
|
||||
account_id: r.get(2)?,
|
||||
person: r.get(3)?,
|
||||
owner: r.get(4)?,
|
||||
active: r.get(5)?,
|
||||
})
|
||||
},
|
||||
)
|
||||
.optional()?)
|
||||
@@ -171,3 +201,37 @@ pub fn owner_invite(conn: &Connection, person: &str) -> Result<Option<String>> {
|
||||
)?;
|
||||
Ok(Some(token))
|
||||
}
|
||||
|
||||
/// Opens a departure (A6) for each of the person's devices (or just `device`) for one vault.
|
||||
/// Returns how many devices will hand over and leave.
|
||||
pub fn depart(conn: &Connection, account_id: i64, vault_id: i64, device: Option<&str>, without_saving: bool) -> Result<usize> {
|
||||
let delete_files: bool = conn.query_row("SELECT delete_from_devices FROM vaults WHERE id = ?1", [vault_id], |r| r.get(0))?;
|
||||
let mut stmt = conn.prepare("SELECT id FROM devices WHERE account_id = ?1 AND key_hash != ''")?;
|
||||
let devices: Vec<String> = stmt.query_map([account_id], |r| r.get(0))?.collect::<Result<_, _>>()?;
|
||||
let mut n = 0;
|
||||
for d in devices.iter().filter(|d| device.is_none_or(|x| x == d.as_str())) {
|
||||
conn.execute(
|
||||
"INSERT INTO departures (vault_id, account_id, device_id, delete_files, without_saving, state, created, updated)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5, 'waiting', ?6, ?6)",
|
||||
params![vault_id, account_id, d, delete_files, without_saving, now()],
|
||||
)?;
|
||||
n += 1;
|
||||
}
|
||||
Ok(n)
|
||||
}
|
||||
|
||||
/// A removed device whose departures are all done can't do anything any more: its key stops working.
|
||||
pub fn retire_if_finished(conn: &Connection, device_id: &str) -> Result<bool> {
|
||||
let inactive: bool = conn.query_row(
|
||||
"SELECT d.removed = 1 OR a.disabled = 1 FROM devices d JOIN accounts a ON a.id = d.account_id WHERE d.id = ?1",
|
||||
[device_id],
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
let pending: i64 =
|
||||
conn.query_row("SELECT COUNT(*) FROM departures WHERE device_id = ?1 AND state = 'waiting'", [device_id], |r| r.get(0))?;
|
||||
if inactive && pending == 0 {
|
||||
conn.execute("UPDATE devices SET key_hash = '', removed = 1 WHERE id = ?1", [device_id])?;
|
||||
return Ok(true);
|
||||
}
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
@@ -73,17 +73,28 @@ async fn handle(
|
||||
};
|
||||
|
||||
let Some((id, key)) = credentials(&headers) else { return Ok(ask_for_key()) };
|
||||
let (caller, role, vault_name) = {
|
||||
let (caller, role, handover, vault_name) = {
|
||||
let conn = hub.db.lock().unwrap();
|
||||
let Some(caller) = db::caller(&conn, &id, &key)? else { return Ok(ask_for_key()) };
|
||||
let role = db::role(&conn, caller.account_id, vault_id)?;
|
||||
let role = if caller.active { db::role(&conn, caller.account_id, vault_id)? } else { None };
|
||||
// A device whose access ended may still send its handover, and nothing else (A6).
|
||||
let handover: Option<i64> = conn
|
||||
.query_row(
|
||||
"SELECT id FROM departures WHERE device_id = ?1 AND vault_id = ?2 AND state = 'waiting' AND without_saving = 0
|
||||
ORDER BY id DESC LIMIT 1",
|
||||
rusqlite::params![caller.device_id, vault_id],
|
||||
|r| r.get(0),
|
||||
)
|
||||
.ok();
|
||||
let name: Option<String> =
|
||||
conn.query_row("SELECT name FROM vaults WHERE id = ?1", [vault_id], |r| r.get(0)).ok();
|
||||
(caller, role, name)
|
||||
(caller, role, handover, name)
|
||||
};
|
||||
let vault_name = vault_name.ok_or_else(not_found)?;
|
||||
let Some(role) = role else {
|
||||
return Err(ApiError(StatusCode::FORBIDDEN, format!("{} isn't a member of {vault_name}", caller.person)));
|
||||
let role = match (role, handover) {
|
||||
(Some(role), _) => role,
|
||||
(None, Some(_)) if writing => "handover".to_string(),
|
||||
_ => return Err(ApiError(StatusCode::FORBIDDEN, format!("{} has no access to {vault_name}", caller.person))),
|
||||
};
|
||||
if writing && role == "read" {
|
||||
let conn = hub.db.lock().unwrap();
|
||||
@@ -105,6 +116,7 @@ async fn handle(
|
||||
.env("REMOTE_ADDR", "127.0.0.1")
|
||||
.env("LUNE_HUB_DATA", &hub.data)
|
||||
.env("LUNE_ACTOR", caller.who())
|
||||
.env("LUNE_HANDOVER_REF", if role == "handover" { format!("refs/handover/{}", handover.unwrap_or(0)) } else { String::new() })
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::inherit());
|
||||
|
||||
@@ -22,11 +22,17 @@ pub fn pre_receive() -> Result<bool> {
|
||||
let conn = db::open(&data)?;
|
||||
let allowed = db::not_secrets(&conn, vault_id)?;
|
||||
|
||||
let handover = std::env::var("LUNE_HANDOVER_REF").unwrap_or_default();
|
||||
let mut found = vec![];
|
||||
for line in std::io::stdin().lock().lines() {
|
||||
let line = line?;
|
||||
let mut parts = line.split_whitespace();
|
||||
let (Some(_old), Some(new), Some(_name)) = (parts.next(), parts.next(), parts.next()) else { continue };
|
||||
let (Some(_old), Some(new), Some(name)) = (parts.next(), parts.next(), parts.next()) else { continue };
|
||||
// Leaving devices may only fill their own handover; nobody else writes to the handover area.
|
||||
if (!handover.is_empty() && name != handover) || (handover.is_empty() && name.starts_with("refs/handover/")) {
|
||||
eprintln!("lune: that place isn't open to this device");
|
||||
return Ok(false);
|
||||
}
|
||||
let new = Oid::from_str(new)?;
|
||||
if new.is_zero() {
|
||||
continue;
|
||||
|
||||
405
hub/src/leave.rs
Normal file
405
hub/src/leave.rs
Normal file
@@ -0,0 +1,405 @@
|
||||
//! Taking access back (M4): removing people from vaults, devices, and the team; handovers and their review.
|
||||
|
||||
use crate::api::{ApiResult, Shared, authenticate, authenticate_any, bad, can_manage, denied};
|
||||
use crate::db;
|
||||
use anyhow::{Context, Result};
|
||||
use axum::Json;
|
||||
use axum::extract::State;
|
||||
use axum::http::HeaderMap;
|
||||
use lune_core::git2::{Oid, Repository, Signature};
|
||||
use rusqlite::{Connection, OptionalExtension, params};
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
use std::path::Path;
|
||||
|
||||
fn account(conn: &Connection, person: &str) -> Result<Option<(i64, String, bool, bool)>> {
|
||||
Ok(conn
|
||||
.query_row("SELECT id, name, owner, disabled FROM accounts WHERE name = ?1", [person.trim()], |r| {
|
||||
Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?))
|
||||
})
|
||||
.optional()?)
|
||||
}
|
||||
|
||||
fn devices_phrase(n: usize) -> String {
|
||||
match n {
|
||||
0 => "no devices to clean up".into(),
|
||||
1 => "1 device will hand over and leave".into(),
|
||||
n => format!("{n} devices will hand over and leave"),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct RemoveReq {
|
||||
person: String,
|
||||
vault: String,
|
||||
#[serde(default)]
|
||||
without_saving: bool,
|
||||
}
|
||||
|
||||
/// Removes a person from one vault (A5). Their other vaults are untouched.
|
||||
pub async fn remove(State(hub): State<Shared>, headers: HeaderMap, Json(req): Json<RemoveReq>) -> ApiResult {
|
||||
let caller = authenticate(&hub, &headers)?;
|
||||
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)))?;
|
||||
if !can_manage(&conn, &caller, vault_id)? {
|
||||
return Err(denied(format!("you need Manage on {vault} to remove people from it")));
|
||||
}
|
||||
let (account_id, person, owner, _) = account(&conn, &req.person)?.ok_or_else(|| bad(format!("nobody named {}", req.person)))?;
|
||||
if owner && account_id != caller.account_id {
|
||||
return Err(denied("the team owner can't be removed from a vault by someone else"));
|
||||
}
|
||||
if db::role(&conn, account_id, vault_id)?.is_none() {
|
||||
return Err(bad(format!("{person} isn't a member of {vault}")));
|
||||
}
|
||||
conn.execute("DELETE FROM memberships WHERE account_id = ?1 AND vault_id = ?2", [account_id, vault_id])?;
|
||||
let n = db::depart(&conn, account_id, vault_id, None, req.without_saving)?;
|
||||
let how = if req.without_saving { " without saving" } else { "" };
|
||||
db::log(&conn, &caller.who(), "access removed", &format!("{person} from {vault}{how} ({})", devices_phrase(n)))?;
|
||||
Ok(Json(json!({ "devices": n })))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct DeviceRemoveReq {
|
||||
label: String,
|
||||
person: Option<String>,
|
||||
}
|
||||
|
||||
/// Removes one device (A1): it hands over and leaves every vault, then its key stops working.
|
||||
pub async fn remove_device(State(hub): State<Shared>, headers: HeaderMap, Json(req): Json<DeviceRemoveReq>) -> ApiResult {
|
||||
let caller = authenticate(&hub, &headers)?;
|
||||
let conn = hub.db.lock().unwrap();
|
||||
let (account_id, person) = match &req.person {
|
||||
Some(p) if !p.eq_ignore_ascii_case(&caller.person) => {
|
||||
if !caller.owner {
|
||||
return Err(denied("only the team owner can remove someone else's device"));
|
||||
}
|
||||
let (id, name, _, _) = account(&conn, p)?.ok_or_else(|| bad(format!("nobody named {p}")))?;
|
||||
(id, name)
|
||||
}
|
||||
_ => (caller.account_id, caller.person.clone()),
|
||||
};
|
||||
let device: String = conn
|
||||
.query_row(
|
||||
"SELECT id FROM devices WHERE account_id = ?1 AND label = ?2 COLLATE NOCASE AND removed = 0",
|
||||
params![account_id, req.label.trim()],
|
||||
|r| r.get(0),
|
||||
)
|
||||
.optional()?
|
||||
.ok_or_else(|| bad(format!("{person} has no device called \"{}\"", req.label.trim())))?;
|
||||
conn.execute("UPDATE devices SET removed = 1 WHERE id = ?1", [&device])?;
|
||||
let mut stmt = conn.prepare("SELECT vault_id FROM memberships WHERE account_id = ?1")?;
|
||||
let vaults: Vec<i64> = stmt.query_map([account_id], |r| r.get(0))?.collect::<Result<_, _>>()?;
|
||||
for v in &vaults {
|
||||
db::depart(&conn, account_id, *v, Some(&device), false)?;
|
||||
}
|
||||
db::retire_if_finished(&conn, &device)?;
|
||||
db::log(
|
||||
&conn,
|
||||
&caller.who(),
|
||||
"device removed",
|
||||
&format!("{person}'s \"{}\" (hands over and leaves {} vault{})", req.label.trim(), vaults.len(), if vaults.len() == 1 { "" } else { "s" }),
|
||||
)?;
|
||||
Ok(Json(json!({})))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct PersonReq {
|
||||
person: String,
|
||||
}
|
||||
|
||||
/// Remove from team (A8): every membership and device ends, the account is disabled (restorable).
|
||||
pub async fn team_remove(State(hub): State<Shared>, headers: HeaderMap, Json(req): Json<PersonReq>) -> ApiResult {
|
||||
let caller = authenticate(&hub, &headers)?;
|
||||
if !caller.owner {
|
||||
return Err(denied("only the team owner can remove someone from the team"));
|
||||
}
|
||||
let mut conn = hub.db.lock().unwrap();
|
||||
let tx = conn.transaction()?;
|
||||
let (account_id, person, _, disabled) = account(&tx, &req.person)?.ok_or_else(|| bad(format!("nobody named {}", req.person)))?;
|
||||
if account_id == caller.account_id {
|
||||
return Err(bad("the team owner can't remove themselves"));
|
||||
}
|
||||
if disabled {
|
||||
return Err(bad(format!("{person} was already removed from the team")));
|
||||
}
|
||||
let vaults: Vec<(i64, String)> = {
|
||||
let mut stmt = tx.prepare("SELECT v.id, v.name FROM memberships m JOIN vaults v ON v.id = m.vault_id WHERE m.account_id = ?1")?;
|
||||
stmt.query_map([account_id], |r| Ok((r.get(0)?, r.get(1)?)))?.collect::<Result<_, _>>()?
|
||||
};
|
||||
for (id, _) in &vaults {
|
||||
db::depart(&tx, account_id, *id, None, false)?;
|
||||
}
|
||||
tx.execute("DELETE FROM memberships WHERE account_id = ?1", [account_id])?;
|
||||
tx.execute("UPDATE devices SET removed = 1 WHERE account_id = ?1", [account_id])?;
|
||||
tx.execute("UPDATE accounts SET disabled = 1 WHERE id = ?1", [account_id])?;
|
||||
tx.execute("DELETE FROM invites WHERE person = ?1 AND used IS NULL", [&person])?;
|
||||
let devices: Vec<String> = {
|
||||
let mut stmt = tx.prepare("SELECT id FROM devices WHERE account_id = ?1")?;
|
||||
stmt.query_map([account_id], |r| r.get(0))?.collect::<Result<_, _>>()?
|
||||
};
|
||||
for d in &devices {
|
||||
db::retire_if_finished(&tx, d)?;
|
||||
}
|
||||
let names: Vec<&str> = vaults.iter().map(|(_, n)| n.as_str()).collect();
|
||||
let from = if names.is_empty() { "no vaults".to_string() } else { names.join(", ") };
|
||||
db::log(&tx, &caller.who(), "removed from team", &format!("{person}: {from}; account disabled, devices will hand over and leave"))?;
|
||||
tx.commit()?;
|
||||
Ok(Json(json!({})))
|
||||
}
|
||||
|
||||
/// Re-enables a removed account with no vaults; returns a one-time link to sign in a new device.
|
||||
pub async fn team_restore(State(hub): State<Shared>, headers: HeaderMap, Json(req): Json<PersonReq>) -> ApiResult {
|
||||
let caller = authenticate(&hub, &headers)?;
|
||||
if !caller.owner {
|
||||
return Err(denied("only the team owner can restore someone"));
|
||||
}
|
||||
let conn = hub.db.lock().unwrap();
|
||||
let (account_id, person, _, disabled) = account(&conn, &req.person)?.ok_or_else(|| bad(format!("nobody named {}", req.person)))?;
|
||||
if !disabled {
|
||||
return Err(bad(format!("{person} wasn't removed from the team")));
|
||||
}
|
||||
conn.execute("UPDATE accounts SET disabled = 0 WHERE id = ?1", [account_id])?;
|
||||
conn.execute("DELETE FROM invites WHERE person = ?1 AND used IS NULL", [&person])?;
|
||||
let token = db::token(32);
|
||||
conn.execute(
|
||||
"INSERT INTO invites (token_hash, person, owner, grants, created_by, expires, account_id) VALUES (?1, ?2, 0, '[]', ?3, ?4, ?5)",
|
||||
params![db::hash(&token), person, caller.who(), db::now() + 7 * 86400, account_id],
|
||||
)?;
|
||||
db::log(&conn, &caller.who(), "restored to team", &format!("{person} (no vaults yet)"))?;
|
||||
Ok(Json(json!({ "link": format!("{}/join/{token}", hub.url) })))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct SettingsReq {
|
||||
vault: String,
|
||||
delete_from_devices: bool,
|
||||
}
|
||||
|
||||
/// "Delete from their devices" (A7), on by default.
|
||||
pub async fn vault_settings(State(hub): State<Shared>, headers: HeaderMap, Json(req): Json<SettingsReq>) -> ApiResult {
|
||||
let caller = authenticate(&hub, &headers)?;
|
||||
let conn = hub.db.lock().unwrap();
|
||||
let (id, name) = db::vault_id(&conn, &req.vault)?.ok_or_else(|| bad(format!("no vault named {}", req.vault)))?;
|
||||
if !can_manage(&conn, &caller, id)? {
|
||||
return Err(denied(format!("you need Manage on {name}")));
|
||||
}
|
||||
conn.execute("UPDATE vaults SET delete_from_devices = ?1 WHERE id = ?2", params![req.delete_from_devices, id])?;
|
||||
let what = if req.delete_from_devices { "on" } else { "off" };
|
||||
db::log(&conn, &caller.who(), "vault setting", &format!("{name}: delete from devices on removal {what}"))?;
|
||||
Ok(Json(json!({})))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct DoneReq {
|
||||
id: i64,
|
||||
head: Option<String>,
|
||||
}
|
||||
|
||||
/// A leaving device reports in: it has handed over (or had nothing to), and will now delete its copy.
|
||||
pub async fn departure_done(State(hub): State<Shared>, headers: HeaderMap, Json(req): Json<DoneReq>) -> ApiResult {
|
||||
let caller = authenticate_any(&hub, &headers)?;
|
||||
let conn = hub.db.lock().unwrap();
|
||||
let found: Option<(i64, String, bool)> = conn
|
||||
.query_row(
|
||||
"SELECT d.vault_id, v.name, d.without_saving FROM departures d JOIN vaults v ON v.id = d.vault_id
|
||||
WHERE d.id = ?1 AND d.device_id = ?2 AND d.state = 'waiting'",
|
||||
params![req.id, caller.device_id],
|
||||
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
|
||||
)
|
||||
.optional()?;
|
||||
let Some((vault_id, vault, without_saving)) = found else {
|
||||
return Err(bad("there's no open departure like that for this device"));
|
||||
};
|
||||
let repo = Repository::open_bare(hub.repo_path(vault_id)).map_err(anyhow::Error::from)?;
|
||||
let handover = format!("refs/handover/{}", req.id);
|
||||
let state = match (&req.head, without_saving) {
|
||||
(_, true) | (None, false) => if without_saving { "skipped" } else { "done" },
|
||||
(Some(head), false) => {
|
||||
let got = repo.find_reference(&handover).ok().and_then(|r| r.target());
|
||||
if got.map(|o| o.to_string()).as_deref() != Some(head.as_str()) {
|
||||
return Err(bad("the hub hasn't received that handover"));
|
||||
}
|
||||
let head = Oid::from_str(head).map_err(anyhow::Error::from)?;
|
||||
if already_shared(&repo, head)? {
|
||||
repo.find_reference(&handover).and_then(|mut r| r.delete()).map_err(anyhow::Error::from)?;
|
||||
"done"
|
||||
} else {
|
||||
"received"
|
||||
}
|
||||
}
|
||||
};
|
||||
conn.execute("UPDATE departures SET state = ?1, updated = ?2 WHERE id = ?3", params![state, db::now(), req.id])?;
|
||||
let detail = match state {
|
||||
"received" => format!("{vault}: unshared work handed over, waiting for review (handover {})", req.id),
|
||||
"skipped" => format!("{vault}: copy deleted without saving"),
|
||||
_ => format!("{vault}: nothing unshared; copy removed"),
|
||||
};
|
||||
db::log(&conn, &caller.who(), "left vault", &detail)?;
|
||||
db::retire_if_finished(&conn, &caller.device_id)?;
|
||||
Ok(Json(json!({ "state": state })))
|
||||
}
|
||||
|
||||
/// The vault's main line: whatever HEAD points to, or the only branch there is.
|
||||
fn main_ref(repo: &Repository) -> Result<Option<String>> {
|
||||
if let Ok(head) = repo.find_reference("HEAD")
|
||||
&& let Some(target) = head.symbolic_target().ok().flatten()
|
||||
&& repo.find_reference(target).is_ok()
|
||||
{
|
||||
return Ok(Some(target.to_string()));
|
||||
}
|
||||
for r in repo.references_glob("refs/heads/*")? {
|
||||
if let Ok(name) = r?.name() {
|
||||
return Ok(Some(name.to_string()));
|
||||
}
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
fn already_shared(repo: &Repository, head: Oid) -> Result<bool> {
|
||||
let Some(main) = main_ref(repo)? else { return Ok(false) };
|
||||
let tip = repo.find_reference(&main)?.peel_to_commit()?.id();
|
||||
Ok(tip == head || repo.graph_descendant_of(tip, head)?)
|
||||
}
|
||||
|
||||
/// Combines a handover into the vault's main line; same-lines clashes keep both, labeled with `label`.
|
||||
fn keep_handover(repo_path: &Path, id: i64, label: &str) -> Result<usize> {
|
||||
let repo = Repository::open_bare(repo_path)?;
|
||||
let mut handover_ref = repo.find_reference(&format!("refs/handover/{id}"))?;
|
||||
let handover = handover_ref.peel_to_commit()?;
|
||||
let Some(main) = main_ref(&repo)? else {
|
||||
repo.reference("refs/heads/main", handover.id(), false, "lune: kept handover")?;
|
||||
handover_ref.delete()?;
|
||||
return Ok(0);
|
||||
};
|
||||
let tip = repo.find_reference(&main)?.peel_to_commit()?;
|
||||
let mut kept = vec![];
|
||||
if repo.graph_descendant_of(handover.id(), tip.id())? {
|
||||
repo.reference_matching(&main, handover.id(), true, tip.id(), "lune: kept handover")?;
|
||||
} else if !repo.graph_descendant_of(tip.id(), handover.id())? {
|
||||
let mut index = repo.merge_commits(&tip, &handover, None)?;
|
||||
lune_core::vault::keep_both(&mut index, label, &mut kept)?;
|
||||
let tree = repo.find_tree(index.write_tree_to(&repo)?)?;
|
||||
let sig = Signature::now(label, "handover@lune.device")?;
|
||||
let msg = format!("Kept the handover from {label}");
|
||||
let id = repo.commit(None, &sig, &sig, &msg, &tree, &[&tip, &handover])?;
|
||||
repo.reference_matching(&main, id, true, tip.id(), "lune: kept handover")?;
|
||||
}
|
||||
handover_ref.delete()?;
|
||||
Ok(kept.len())
|
||||
}
|
||||
|
||||
/// Departures in vaults the caller manages (all of them for the owner), newest first.
|
||||
pub async fn handovers(State(hub): State<Shared>, headers: HeaderMap) -> ApiResult {
|
||||
let caller = authenticate(&hub, &headers)?;
|
||||
let conn = hub.db.lock().unwrap();
|
||||
let mut stmt = conn.prepare(
|
||||
"SELECT d.id, d.vault_id, v.name, a.name, dev.label, d.state, d.updated
|
||||
FROM departures d JOIN vaults v ON v.id = d.vault_id JOIN accounts a ON a.id = d.account_id
|
||||
JOIN devices dev ON dev.id = d.device_id ORDER BY d.id DESC LIMIT 100",
|
||||
)?;
|
||||
let rows: Vec<(i64, i64, String, String, String, String, i64)> = stmt
|
||||
.query_map([], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?, r.get(5)?, r.get(6)?)))?
|
||||
.collect::<Result<_, _>>()?;
|
||||
let mut out = vec![];
|
||||
for (id, vault_id, vault, person, device, state, at) in rows {
|
||||
if can_manage(&conn, &caller, vault_id)? {
|
||||
out.push(json!({ "id": id, "vault": vault, "person": person, "device": device, "state": state, "at": at }));
|
||||
}
|
||||
}
|
||||
Ok(Json(Value::Array(out)))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct IdReq {
|
||||
id: i64,
|
||||
}
|
||||
|
||||
/// (vault id, vault name, device label, state) of a departure the caller may decide about.
|
||||
fn departure_for(conn: &Connection, caller: &db::Caller, id: i64) -> Result<(i64, String, String, String), crate::api::ApiError> {
|
||||
let found: Option<(i64, String, String, String)> = conn
|
||||
.query_row(
|
||||
"SELECT d.vault_id, v.name, dev.label, d.state FROM departures d JOIN vaults v ON v.id = d.vault_id
|
||||
JOIN devices dev ON dev.id = d.device_id WHERE d.id = ?1",
|
||||
[id],
|
||||
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)),
|
||||
)
|
||||
.optional()?;
|
||||
let found = found.ok_or_else(|| bad(format!("no handover {id}")))?;
|
||||
if !can_manage(conn, caller, found.0)? {
|
||||
return Err(denied(format!("you need Manage on {} to decide about its handovers", found.1)));
|
||||
}
|
||||
Ok(found)
|
||||
}
|
||||
|
||||
pub async fn handover_show(State(hub): State<Shared>, headers: HeaderMap, Json(req): Json<IdReq>) -> ApiResult {
|
||||
let caller = authenticate(&hub, &headers)?;
|
||||
let conn = hub.db.lock().unwrap();
|
||||
let (vault_id, _, _, state) = departure_for(&conn, &caller, req.id)?;
|
||||
if state != "received" {
|
||||
return Err(bad(format!("handover {} has nothing to review ({state})", req.id)));
|
||||
}
|
||||
let lines = (|| -> Result<Vec<String>> {
|
||||
let repo = Repository::open_bare(hub.repo_path(vault_id))?;
|
||||
let handover = repo.find_reference(&format!("refs/handover/{}", req.id))?.peel_to_commit()?;
|
||||
let base = match main_ref(&repo)? {
|
||||
Some(m) => {
|
||||
let tip = repo.find_reference(&m)?.peel_to_commit()?;
|
||||
repo.merge_base(tip.id(), handover.id()).ok().map(|b| repo.find_commit(b)).transpose()?.map(|c| c.tree()).transpose()?
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let diff = repo.diff_tree_to_tree(base.as_ref(), Some(&handover.tree()?), None)?;
|
||||
Ok(diff
|
||||
.deltas()
|
||||
.map(|d| {
|
||||
let what = match d.status() {
|
||||
lune_core::git2::Delta::Added => "added",
|
||||
lune_core::git2::Delta::Deleted => "removed",
|
||||
_ => "changed",
|
||||
};
|
||||
let path = d.new_file().path().or(d.old_file().path()).map(|p| p.display().to_string()).unwrap_or_default();
|
||||
format!("{what:<8} {path}")
|
||||
})
|
||||
.collect())
|
||||
})()
|
||||
.context("can't read the handover")?;
|
||||
Ok(Json(json!(lines)))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct DecideReq {
|
||||
id: i64,
|
||||
decision: String,
|
||||
}
|
||||
|
||||
/// keep / discard a received handover, or skip (delete without saving) a device that hasn't reported in.
|
||||
pub async fn handover_decide(State(hub): State<Shared>, headers: HeaderMap, Json(req): Json<DecideReq>) -> ApiResult {
|
||||
let caller = authenticate(&hub, &headers)?;
|
||||
let conn = hub.db.lock().unwrap();
|
||||
let (vault_id, vault, device, state) = departure_for(&conn, &caller, req.id)?;
|
||||
let (new_state, message) = match (req.decision.as_str(), state.as_str()) {
|
||||
("keep", "received") => {
|
||||
let clashes = keep_handover(&hub.repo_path(vault_id), req.id, &device)?;
|
||||
let extra = if clashes > 0 { format!(" ({clashes} note(s) changed in two places: both versions kept)") } else { String::new() };
|
||||
("kept", format!("Kept {device}'s handover in {vault}{extra}. It reaches every device on its next sync."))
|
||||
}
|
||||
("discard", "received") => {
|
||||
let repo = Repository::open_bare(hub.repo_path(vault_id)).map_err(anyhow::Error::from)?;
|
||||
repo.find_reference(&format!("refs/handover/{}", req.id)).and_then(|mut r| r.delete()).map_err(anyhow::Error::from)?;
|
||||
("discarded", format!("Discarded {device}'s handover for {vault}."))
|
||||
}
|
||||
("skip", "waiting") => {
|
||||
conn.execute("UPDATE departures SET without_saving = 1 WHERE id = ?1", [req.id])?;
|
||||
return {
|
||||
db::log(&conn, &caller.who(), "handover skipped", &format!("{device} in {vault}: delete without saving"))?;
|
||||
Ok(Json(json!({ "message": format!("{device} will delete its copy of {vault} without sending anything, the next time it's online.") })))
|
||||
};
|
||||
}
|
||||
("keep" | "discard", _) => return Err(bad(format!("handover {} has nothing to review ({state})", req.id))),
|
||||
("skip", _) => return Err(bad(format!("{device} has already reported in ({state})"))),
|
||||
_ => return Err(bad("decide keep, discard or skip")),
|
||||
};
|
||||
conn.execute("UPDATE departures SET state = ?1, updated = ?2 WHERE id = ?3", params![new_state, db::now(), req.id])?;
|
||||
db::log(&conn, &caller.who(), &format!("handover {new_state}"), &format!("{device} in {vault}"))?;
|
||||
Ok(Json(json!({ "message": message })))
|
||||
}
|
||||
@@ -4,6 +4,7 @@ mod api;
|
||||
mod db;
|
||||
mod git;
|
||||
mod hook;
|
||||
mod leave;
|
||||
|
||||
use anyhow::Result;
|
||||
use axum::Router;
|
||||
@@ -74,6 +75,15 @@ async fn serve() -> Result<()> {
|
||||
.route("/api/members", post(api::members))
|
||||
.route("/api/log", get(api::log))
|
||||
.route("/api/not-secrets", post(api::not_secret))
|
||||
.route("/api/remove", post(leave::remove))
|
||||
.route("/api/device/remove", post(leave::remove_device))
|
||||
.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/departures/done", post(leave::departure_done))
|
||||
.route("/api/handovers", get(leave::handovers))
|
||||
.route("/api/handovers/show", post(leave::handover_show))
|
||||
.route("/api/handovers/decide", post(leave::handover_decide))
|
||||
.route("/git/{repo}/{*rest}", any(git::serve))
|
||||
.route("/health", get(|| async { "ok" }))
|
||||
.layer(DefaultBodyLimit::disable())
|
||||
|
||||
148
hub/tests/hub.rs
148
hub/tests/hub.rs
@@ -7,6 +7,9 @@ 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 {
|
||||
@@ -47,6 +50,7 @@ fn as_device(url: &str, w: &hub::Welcome) -> HubLink {
|
||||
|
||||
#[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"));
|
||||
|
||||
@@ -106,3 +110,147 @@ fn hub_lifecycle() {
|
||||
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<String> {
|
||||
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<String> = 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:?}");
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user