Skip to content

Reason Network: your team's coding agents, talking to each other. The engine behind `reason network`.

A removed machine never gets the link that replaces the one it knew

Lars Talian8e12f1279171
diff --git a/src/daemon/teamops.rs b/src/daemon/teamops.rs
index 7663483..ca5ae87 100644
--- a/src/daemon/teamops.rs
+++ b/src/daemon/teamops.rs
@@ -119,8 +119,13 @@ impl Daemon {
let after: HashSet<EndpointId> = team.active().map(|m| m.endpoint).collect();
let state = team.clone();
let relay_changed = state.meta.body.relay != relay;
- let _ = self.save_team(&g);
- (state, before.difference(&after).copied().collect::<Vec<_>>(), !after.contains(&me), relay_changed)
+ let gone = !after.contains(&me);
+ // Removed: what came with the news (a team link that replaced the one this machine knew, from a teammate
+ // on an older build) is never written here, not even to the database's log.
+ if !gone {
+ let _ = self.save_team(&g);
+ }
+ (state, before.difference(&after).copied().collect::<Vec<_>>(), gone, relay_changed)
};
if let Some(net) = self.net() {
net.broadcast(&Wire::State { state: Box::new(state) });
@@ -135,6 +140,7 @@ impl Daemon {
g.team = None;
let _ = self.save_team(&g);
let _ = g.store.delete_prefix("presence:");
+ let _ = g.store.scrub();
drop(g);
self.restart_soon();
} else if relay_changed {
diff --git a/src/net.rs b/src/net.rs
index 3eb36bc..a8a5ab5 100644
--- a/src/net.rs
+++ b/src/net.rs
@@ -285,6 +285,16 @@ impl Refusals {
}
}
+/// What `w` is for `peer`: team state with the team link and invites only for a machine that is an active member in that
+/// state. A machine it says was removed (still connected for a moment, so it hears so) learns who's in the team, not
+/// the link that replaced the one it knew.
+fn for_peer(w: &Wire, peer: &EndpointId) -> Wire {
+ match w {
+ Wire::State { state } if !state.is_active(peer) => Wire::State { state: Box::new(state.without_secrets()) },
+ w => w.clone(),
+ }
+}
+
/// Nothing is known yet about where that machine is.
fn unpublished(e: &anyhow::Error) -> bool {
matches!(
@@ -462,8 +472,8 @@ impl Net {
}
pub fn broadcast(&self, w: &Wire) {
- for l in self.links.lock().unwrap().values() {
- let _ = l.tx.send(w.clone());
+ for (peer, l) in self.links.lock().unwrap().iter() {
+ let _ = l.tx.send(for_peer(w, peer));
}
}
@@ -653,7 +663,7 @@ impl Net {
});
let _ = tx.send(Wire::Hello { team, proto: PROTO });
if let Some(state) = daemon.team_state() {
- let _ = tx.send(Wire::State { state: Box::new(state) });
+ let _ = tx.send(for_peer(&Wire::State { state: Box::new(state) }, &peer));
}
let _ = tx.send(Wire::Presence { presence: daemon.presence().await });
for msg in daemon.outbox_for(&peer) {
@@ -769,6 +779,30 @@ fn tidy_presence(mut p: Presence) -> Presence {
mod tests {
use super::*;
+ #[test]
+ fn a_removed_machine_is_sent_no_link_or_invite() {
+ let (a, b, c) = (SecretKey::generate(), SecretKey::generate(), SecretKey::generate());
+ let mut s = TeamState::found("vibes", "alex", "mbp", &a);
+ s.put_member(&a, b.public(), "alice", "xps", true);
+ s.invite(&a, &"00".repeat(16), 24, None);
+ // Removing alice replaces the link; the state saying so goes out while her machine is still connected.
+ s.put_member(&a, b.public(), "alice", "xps", false);
+ s.new_link(&a);
+ let w = Wire::State { state: Box::new(s.clone()) };
+ let Wire::State { state: to_b } = for_peer(&w, &b.public()) else { panic!() };
+ assert!(to_b.link.is_none() && to_b.invites.is_empty());
+ assert!(!to_b.is_active(&b.public()), "but it does say she was removed");
+ let text = serde_json::to_string(&for_peer(&w, &b.public())).unwrap();
+ assert!(!text.contains(s.link_secret().unwrap()));
+ // Nor a stranger; a member gets it all, and anything else goes as it is.
+ let Wire::State { state: to_c } = for_peer(&w, &c.public()) else { panic!() };
+ assert!(to_c.link.is_none());
+ let Wire::State { state: to_a } = for_peer(&w, &a.public()) else { panic!() };
+ assert_eq!(*to_a, s);
+ let ack = Wire::Ack { id: "x".into(), state: "stored".into(), note: String::new() };
+ assert!(matches!(for_peer(&ack, &b.public()), Wire::Ack { .. }));
+ }
+
#[test]
fn a_joiner_with_a_proof_asks_on_past_a_refusal() {
let req = |proof: Option<&str>, owner_only| JoinRequest {
diff --git a/src/store.rs b/src/store.rs
index 93abb08..bf25d22 100644
--- a/src/store.rs
+++ b/src/store.rs
@@ -95,6 +95,19 @@ impl Store {
pub fn open(path: &Path, inbox: PathBuf) -> Result<Self> {
let db = Connection::open(path)?;
db.execute_batch(SCHEMA)?;
+ // Deleted rows are overwritten, not just let go (see `scrub`).
+ db.execute_batch("PRAGMA secure_delete = ON;")?;
+ // Only this user reads it, like machine.key: it holds the team link. (SQLite gives the log files the mode the
+ // database has, but older installs made them with the default.)
+ #[cfg(unix)]
+ for suffix in ["", "-wal", "-shm"] {
+ let mut p = path.as_os_str().to_owned();
+ p.push(suffix);
+ let p = PathBuf::from(p);
+ if p.exists() {
+ crate::util::chmod(&p, 0o600)?;
+ }
+ }
// Added in 0.10.7.
if !db.prepare("SELECT 1 FROM pragma_table_info('messages') WHERE name = 'approval'")?.exists([])? {
db.execute("ALTER TABLE messages ADD COLUMN approval TEXT", [])?;
@@ -333,6 +346,13 @@ impl Store {
Ok(rows.collect::<rusqlite::Result<_>>()?)
}
+ /// Writes everything in the log into the database and empties the log, so what was deleted (with `secure_delete`,
+ /// overwritten) isn't still in it.
+ pub fn scrub(&self) -> Result<()> {
+ self.db.query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |_| Ok(()))?;
+ Ok(())
+ }
+
pub fn delete_prefix(&self, prefix: &str) -> Result<()> {
self.db.execute("DELETE FROM kv WHERE key >= ?1 AND key < ?1 || x'ff'", [prefix])?;
Ok(())
@@ -464,6 +484,33 @@ mod tests {
use crate::util;
use std::collections::HashMap;
+ #[test]
+ #[cfg(unix)]
+ fn the_database_is_this_users_and_keeps_nothing_it_deleted() {
+ use std::os::unix::fs::PermissionsExt;
+ let dir = std::env::temp_dir().join(format!("reason-network-store-{}", ulid::Ulid::new()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let db = dir.join("network.db");
+ // A database made before, with the default mode.
+ drop(Store::open(&db, temp_inbox()).unwrap());
+ util::chmod(&db, 0o644).unwrap();
+ let store = Store::open(&db, temp_inbox()).unwrap();
+ let secret = "5ec7e75ec7e75ec7e75ec7e75ec7e75e";
+ store.set("team", &format!(r#"{{"link":{{"body":{{"secret":"{secret}"}}}}}}"#)).unwrap();
+ for f in ["network.db", "network.db-wal", "network.db-shm"] {
+ let mode = std::fs::metadata(dir.join(f)).unwrap().permissions().mode() & 0o777;
+ assert_eq!(mode, 0o600, "{f}");
+ }
+ store.delete_prefix("team").unwrap();
+ store.scrub().unwrap();
+ for f in ["network.db", "network.db-wal"] {
+ let bytes = std::fs::read(dir.join(f)).unwrap_or_default();
+ assert!(!bytes.windows(secret.len()).any(|w| w == secret.as_bytes()), "{f} still holds it");
+ }
+ drop(store);
+ std::fs::remove_dir_all(&dir).unwrap();
+ }
+
#[test]
fn a_session_gone_a_day_is_forgotten_with_the_mail_it_never_read() {
// (Not one that is live, nor the person's own mailbox, nor mail held for the person.)
diff --git a/tests/e2e/two_machines.py b/tests/e2e/two_machines.py
index 626113f..cff5029 100644
--- a/tests/e2e/two_machines.py
+++ b/tests/e2e/two_machines.py
@@ -126,6 +126,14 @@ def link_relays(link):
fields.append(("n0 " if short else "") + raw[at + 1:at + 1 + raw[at]].decode())
at += 1 + raw[at]
return fields[1:]
+
+
+def link_secret(link):
+ """The team link's secret (the 16 bytes after the team id), as hex."""
+ t = re.split(r"#rn1-|#tincan1", link)[1]
+ return base64.urlsafe_b64decode(t + "=" * (-len(t) % 4))[16:32].hex()
+
+
os.makedirs(os.path.join(D, "work"), exist_ok=True)
# --- team formation, signed in with Reason ---
@@ -243,6 +251,41 @@ out = subprocess.run([BIN, "link"], env=bob, capture_output=True, text=True, tim
check("any member can show the same team link", link.group(1).split("#")[1][:40] in out.replace("\n", ""), out)
subprocess.run([BIN, "stop"], env=bob, capture_output=True)
+# --- removal while online: the removed machine never gets the link that replaces the one it knew ---
+eve = dict(env("alice"), REASON_NETWORK_HOME=os.path.join(D, "eve"), REASON_NETWORK_MACHINE="tab")
+eve_link = re.search(r"(https://\S+#rn1-\S+)", cli("alex", "link")).group(1)
+_, out = run(eve, "join", eve_link, "--as", "eve", "--no-setup")
+check("eve joins", "Joined team vibes as eve on tab." in out, out)
+for _ in range(30):
+ if re.search(r"eve\s+tab\s+(direct|relay)", cli("alex", "team")):
+ break
+ time.sleep(1)
+out = cli("alex", "remove", "eve")
+check("remove eve while her machine is online", "Removed eve on tab" in out, out)
+for _ in range(30):
+ if "not in a team" in run(eve, "team")[1]:
+ break
+ time.sleep(1)
+check("eve's machine hears it was removed", "not in a team" in run(eve, "team")[1])
+new_link = re.search(r"(https://\S+#rn1-\S+)", cli("alex", "link")).group(1)
+new_secret = link_secret(new_link)
+check("the link changed", new_secret != link_secret(eve_link))
+held = b"".join(open(os.path.join(D, "eve", f), "rb").read() for f in ("network.db", "network.db-wal", "network.db-shm")
+ if os.path.exists(os.path.join(D, "eve", f)))
+check("the removed machine's database and its log hold no current link secret", held and new_secret.encode() not in held,
+ f"{len(held)} bytes")
+seen = set(re.findall(rb'"secret":"([0-9a-f]{32})"', held))
+check("…nor any link secret it could rebuild a link from", all(sec.decode() != new_secret for sec in seen), seen)
+_, out = run(eve, "join", eve_link, "--as", "eve2", "--no-setup")
+check("…so it can't rejoin with the old link", "Joined" not in out and "replaced" in out, out)
+if os.name != "nt":
+ modes = {f: oct(os.stat(os.path.join(D, "eve", f)).st_mode & 0o777) for f in ("network.db", "network.db-wal", "network.db-shm")
+ if os.path.exists(os.path.join(D, "eve", f))}
+ check("the database files are the user's alone", modes and all(m == "0o600" for m in modes.values()), modes)
+run(eve, "stop")
+out = cli("alice", "team")
+check("the others are still connected", re.search(r"alex \(verified\)\s+laptop\s+(direct|relay)", out) is not None, out)
+
# --- sessions on both machines ---
claude = Mcp("alex", "claude-code", strip_claude=False, cwd=ROOT)
codex = Mcp("alice", "codex-mcp-client", strip_claude=True, cwd=os.path.join(D, "work"))