Reason Network: your team's coding agents, talking to each other. The engine behind `reason network`.
Rust agent-to-agentai-agentsclaude-codecodexcoding-agentscursorgrokirohmcpmcp-servermulti-agentpeer-to-peerreason
Sign-in proofs: the re-review's three low findings
Lars Talian68466fe1e3e7
diff --git a/src/net.rs b/src/net.rsindex 2ef92fc..dcd7e55 100644--- a/src/net.rs+++ b/src/net.rs@@ -198,7 +198,7 @@ async fn read_frame<T: DeserializeOwned>(recv: &mut RecvStream) -> Result<T> {/// Joins a team: asks each machine in turn (the ticket's, or the one an invite code points at) to let us in.pub async fn join(endpoint: &Endpoint, peers: &[EndpointAddr], req: &JoinRequest) -> Result<TeamState> {let mut last = anyhow!("the invite lists no machines");- let mut refused: Option<String> = None;+ let mut refused = Refusals::default();for addr in peers {let attempt = || async {let conn = endpoint.connect(addr.clone(), JOIN_ALPN).await?;@@ -222,19 +222,31 @@ pub async fn join(endpoint: &Endpoint, peers: &[EndpointAddr], req: &JoinRequest};match reply {Ok(Ok(JoinReply::Ok { state })) => return Ok(*state),- // A refusal is final: another machine would say the same. Except, asking for one of the person's own- // machines, from a machine that isn't (or an older one, which can't tell): the next may be.- Ok(Ok(JoinReply::Err { error })) if req.owner_only => {- if refused.as_ref().is_none_or(|r| !r.contains(crate::team::SAME_ACCOUNT)) {- refused = Some(error);- }- }- Ok(Ok(JoinReply::Err { error })) => bail!(error),+ Ok(Ok(JoinReply::Err { error })) => refused.add(req, error)?,Ok(Err(e)) => last = e,Err(_) => last = anyhow!("couldn't reach the machine that made the invite (is it online?)"),}}- Err(refused.map_or(last, |r| anyhow!(r)))+ Err(refused.0.map_or(last, |r| anyhow!(r)))+}++/// What the machines asked so far refused a join with. A refusal is final: another machine would say the same. Except+/// for a joiner with a sign-in proof: a machine may not be one of the person's own (`SAME_ACCOUNT`), or may be an older+/// one that knows nothing of proofs (and says the name is taken), while one further down the link can still let it in.+#[derive(Default)]+struct Refusals(Option<String>);++impl Refusals {+ fn add(&mut self, req: &JoinRequest, error: String) -> Result<()> {+ if req.proof.is_none() {+ bail!(error);+ }+ // Told once that it's the same account, the joiner keeps that (not an older machine's "taken").+ if self.0.as_ref().is_none_or(|r| !r.contains(crate::team::SAME_ACCOUNT)) {+ self.0 = Some(error);+ }+ Ok(())+ }}/// Nothing is known yet about where that machine is.@@ -718,6 +730,31 @@ fn tidy_presence(mut p: Presence) -> Presence {mod tests {use super::*;+ #[test]+ fn a_joiner_with_a_proof_asks_on_past_a_refusal() {+ let req = |proof: Option<&str>, owner_only| JoinRequest {+ team: String::new(),+ secret: String::new(),+ person: "alex".into(),+ machine: "mini".into(),+ proof: proof.map(String::from),+ owner_only,+ };+ let taken = "'alex' is already in this team; join with another name (--as)";+ let same = "only one of alex's own computers lets this one in as alex (same_account_needs_owner)";+ // Without a proof, the first refusal is the answer.+ assert!(Refusals::default().add(&req(None, false), taken.into()).is_err());+ // With one, in either pass (the second asks without owner_only), an older machine's "taken" isn't final: a+ // machine of this build further down the link may let it in.+ for owner_only in [true, false] {+ let mut r = Refusals::default();+ r.add(&req(Some("jws"), owner_only), taken.into()).unwrap();+ r.add(&req(Some("jws"), owner_only), same.into()).unwrap();+ r.add(&req(Some("jws"), owner_only), taken.into()).unwrap();+ assert_eq!(r.0.as_deref(), Some(same), "the same account, once known, is what it says in the end");+ }+ }+#[test]fn a_stale_connection_is_replaced_but_a_simultaneous_dial_is_dropped() {let (a, b) = (SecretKey::generate().public(), SecretKey::generate().public());diff --git a/src/proof.rs b/src/proof.rsindex c0d54ff..40151f7 100644--- a/src/proof.rs+++ b/src/proof.rs@@ -17,6 +17,10 @@ const MAX_SKEW_SECS: i64 = 86_400;/// Reason's proof-signing public keys: key id, then the Ed25519 key in base64url. A placeholder until the production/// key exists; in debug builds `REASON_NETWORK_TRUST_KEYS` (a JWKS) adds keys, for tests.+///+/// Never remove a key, even a retired one: who holds a name in a team rests on proofs' signatures (expired proofs+/// included), so a build without a key that signed some would drop machines that every other build keeps. Add the+/// new key next to it instead.const KEYS: &[(&str, &str)] = &[];/// What a proof says.diff --git a/src/team.rs b/src/team.rsindex d1fcc71..150a92d 100644--- a/src/team.rs+++ b/src/team.rs@@ -217,14 +217,18 @@ impl TeamState {.collect()}- /// Records `endpoint`'s sign-in proof, if it is Reason's (expired or not) and newer than the one it has; true if it- /// was taken.+ /// Records `endpoint`'s sign-in proof, if it is Reason's (expired or not) and newer than the one it has (issued later;+ /// the same second, the greater JWS, so every machine keeps the same one); true if it was taken.pub fn attest(&mut self, endpoint: &EndpointId, jws: &str) -> bool {+ let jws = jws.trim();let Ok(p) = proof::verify_ignoring_expiry(jws, endpoint) else { return false };- if self.signed_proof(endpoint).is_some_and(|cur| cur.iat >= p.iat) {+ let key = endpoint.to_string();+ if let Some(cur) = self.signed_proof(endpoint)+ && (cur.iat, self.attestations[&key].as_str()) >= (p.iat, jws)+ {return false;}- self.attestations.insert(endpoint.to_string(), jws.trim().to_string());+ self.attestations.insert(key, jws.to_string());true}@@ -1153,4 +1157,19 @@ mod tests {assert!(s.has_proof(&a.public()) && !s.has_proof(&b.public()));assert!(s.verified_people().contains_key("alex"), "alex is verified, on both machines");}++ #[test]+ fn proofs_issued_the_same_second_converge() {+ let a = key();+ let s = TeamState::found("vibes", "alex", "mbp", &a);+ let (mut p, mut q) = (s.clone(), s.clone());+ // Two proofs Reason issued in the same second (same iat, other claims differ).+ assert!(p.attest(&a.public(), &proof_for("u_alex", "alex", &a, 3600)));+ assert!(q.attest(&a.public(), &proof_for("u_alex", "alex", &a, 7200)));+ assert_ne!(p.attestations, q.attestations);+ p.merge(&q).unwrap();+ q.merge(&p).unwrap();+ assert_eq!(p.attestations, q.attestations, "both keep the same one");+ assert!(!p.merge(&q).unwrap() && !q.merge(&p).unwrap(), "and then nothing changes");+ }}diff --git a/tests/e2e/mixed_versions.py b/tests/e2e/mixed_versions.pyindex 0d2f7de..b2f2f24 100644--- a/tests/e2e/mixed_versions.py+++ b/tests/e2e/mixed_versions.py@@ -16,7 +16,7 @@ D = tempfile.mkdtemp(prefix="reason-network-mixed-")FAKE_BIN = os.path.join(D, "bin")UNEXPECTED = os.path.join(D, "unexpected.log")# alex and nina run this build, olga the older one.-WHO = {"alex": (NEW, "laptop"), "olga": (OLD, "oldbox"), "nina": (NEW, "desk"), "nina2": (NEW, "pad"), "mal": (NEW, "evil")}+WHO = {"alex": (NEW, "laptop"), "olga": (OLD, "oldbox"), "nina": (NEW, "desk"), "nina2": (NEW, "pad"), "nina3": (NEW, "tab"), "mal": (NEW, "evil")}results = []@@ -63,7 +63,7 @@ for name in ("open", "xdg-open", "osascript", "notify-send"):try:print(f"this build: {cli('alex', '--version')} · older: {cli('olga', '--version')}")- ep = {w: cli(w, "endpoint") for w in ("alex", "nina", "nina2", "mal")}+ ep = {w: cli(w, "endpoint") for w in ("alex", "nina", "nina2", "nina3", "mal")}out = cli("alex", "init", "mixed", "--proof", proof("u_alex", "alex", ep["alex"]), "--no-setup")check("this build starts a team, signed in", "You are alex on laptop." in out, out)link = link_of(cli("alex", "link"))@@ -96,6 +96,16 @@ try:check("…let in by nina's own machine, so the older machine takes it too", re.search(r"nina\s+pad\s+(direct|relay)", out) is not None, out)cli("nina2", "leave")cli("nina2", "stop")+ # With nina's machine off, the older machine first on its link says the name is taken; alex's machine, further+ # down, lets the new computer in on its proof (which the older machine doesn't take, as documented).+ cli("nina", "stop")+ until("olga", ["team"], lambda o: not re.search(r"nina\s+desk\s+(direct|relay)", o))+ out = cli("nina3", "join", link_of(cli("olga", "link")), "--proof", proof("u_nina", "nina", ep["nina3"]), "--no-setup")+ check("past the older machine's refusal, a machine of this build lets nina's computer in", "Joined team mixed as nina on tab." in out, out)+ out = until("alex", ["team"], lambda o: re.search(r"nina \(verified\)\s+tab\s+(direct|relay)", o))+ check("…which this build's machines take", re.search(r"nina \(verified\)\s+tab\s+(direct|relay)", out) is not None, out)+ cli("nina3", "leave")+ cli("nina3", "stop")out = subprocess.run([NEW, "join", old_link, "--proof", proof("u_mal", "alex", ep["mal"]), "--no-setup", "--json"],env=env("mal"), capture_output=True, text=True, timeout=90).stdout.strip()check("a taken name through the older machine is name_taken", out == '{"error":"name_taken"}', out)