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 security review's changes
Lars Talian05343f7907ef
diff --git a/DESIGN.md b/DESIGN.mdindex d152fa3..ce89674 100644--- a/DESIGN.md+++ b/DESIGN.md@@ -116,20 +116,29 @@ The link secret is a reusable invite in the team state (any member can show theredeem it), replaced with `reason-network link --new` and whenever someone is removed; removed machines are never sent it.The page shows one command (`curl … install.sh | sh -s -- <ticket>`); the joiner only types a name. Four-wordone-time codes (`reason-network invite --code`, ~41 bits) derive a temporary iroh key the inviting machine listens on, for-reading out loud or adding your own machines. A code doesn't name the team, so the joiner checks the team it is handed-holds the code's invite, signed by a member and used by the joiner. Links are `rn1-…` (older builds wrote `tincan1…`,-with the same payload; both are read). After `init` and `join` the CLI prints the invite line,-`Join the Reason Network: <team link>`, and agents get it from `list_team`.+reading out loud or adding your own machines. A code can't show the joiner which team answers it (whoever listens on+the code's key knows the code, so could make up a team), so a sign-in never joins with one: only with a link, which+names the team. Links are `rn1-…` (older builds wrote `tincan1…`, with the same payload; both are read). After `init`+and `join` the CLI prints the invite line, `Join the Reason Network: <team link>`, and agents get it from `list_team`.**Sign-in proofs.** Signed in with Reason, a machine carries a proof: a compact JWS (Ed25519) from Reason saying-this endpoint id belongs to account `sub`, named `name`, until `exp` (`init`/`join --proof`, `reason-network proof`-to refresh). The engine checks it against Reason's public keys, compiled in, and never calls Reason. Proofs travel in-the team state's `attestations` (endpoint → JWS), outside the signed entries, so builds without them pass the rest-on unchanged; each machine checks every proof itself and drops the ones that don't verify. A person whose machine-has a valid proof for their name shows as verified. With a proof, the name is the proof's; a verified name can't be-taken by anyone but another computer of the same account (which any member may let in through the team link).-`--json` on `init`, `join`, `link` and `team` is for the Reason CLI, which signs people in; a taken name is-`{"error":"name_taken"}`.+this endpoint id belongs to account `sub`, named `name`, issued `iat`, until `exp` (`init`/`join --proof`,+`reason-network proof` to refresh). The engine checks it against Reason's public keys, compiled in, and never calls+Reason; debug builds also trust the keys in `REASON_NETWORK_TRUST_KEYS`, for tests, and release builds don't. A proof+longer than 4 KB, or issued more than a day ahead, is refused. Proofs travel in the team state's `attestations`+(endpoint → JWS), outside the signed entries, so builds without them pass the rest on unchanged; each machine checks+every proof itself, drops the ones that don't verify, and keeps them only for members.++`verified` is per person: a person shows as verified while a machine of theirs has a proof for their name that hasn't+expired. `has_proof` is per machine. Expiry decides only that mark, never membership: who may hold a name goes by+Reason's signature alone, so it doesn't change as time passes or differ between machines' clocks. With a proof, the+name is the proof's. A name held with a proof can't be taken by anyone else (`{"error":"name_taken"}` with `--json`,+for the Reason CLI, which signs people in). Another computer of the same account may take it: the joiner first asks the+link's machines for one of that person's own, whose word every build takes (a machine that isn't says+`same_account_needs_owner` and the joiner asks the next); if none of them is online, a machine of this build lets it+in on its proof; if none can, the join fails with `{"error":"same_account_needs_owner"}`, never `name_taken`. Builds+before proofs (0.10.x) never see a computer let in on its proof, only one let in by the person's own machine. If every+machine asked is that old, nothing tells the joiner it's the same account, and the join comes back as `name_taken`.**Presence and directory.** Daemons keep a connection to every online member (full mesh; fine to ~50machines). On connect they exchange roster heads (anti-entropy) and full presence. On any local change adiff --git a/src/daemon/teamops.rs b/src/daemon/teamops.rsindex fe93747..8f284d6 100644--- a/src/daemon/teamops.rs+++ b/src/daemon/teamops.rs@@ -145,8 +145,8 @@ impl Daemon {/// Someone presented an invite (on the join protocol).pub fn redeem(self: &Arc<Self>, joiner: EndpointId, req: &JoinRequest) -> Result<TeamState> {- // Signed in to Reason: the name is the one Reason gave.- let proof = req.proof.as_deref().map(|p| proof::verify(p, &joiner)).transpose()?;+ // Signed in to Reason: the name is the one Reason gave. (Expiry doesn't decide who joins: peers don't check it.)+ let proof = req.proof.as_deref().map(|p| proof::verify_ignoring_expiry(p, &joiner)).transpose()?;let person = proof.as_ref().map_or_else(|| util::slug(&req.person), |p| p.name.clone());let machine = util::slug(&req.machine);if person.is_empty() || machine.is_empty() {@@ -158,7 +158,7 @@ impl Daemon {if !req.team.is_empty() && req.team != team.id {bail!("this invite is for a different team");}- team.redeem(&self.key, &req.secret, &person, joiner, proof.as_ref())?;+ team.redeem(&self.key, &req.secret, &person, joiner, proof.as_ref(), req.owner_only)?;if let Some(p) = &req.proof {team.attest(&joiner, p);}@@ -227,6 +227,7 @@ impl Daemon {) -> Result<TeamInfo> {// A proof that doesn't verify here won't anywhere: say so before leaving anything.let checked = proof.as_deref().map(|p| proof::verify(p, &self.key.public())).transpose()?;+ sign_in_needs_a_link(invite_text, proof.as_deref())?;let person = checked.map_or_else(|| person.to_string(), |p| p.name);let mut solo = false;if let Some(t) = self.team_state() {@@ -274,16 +275,27 @@ impl Daemon {let endpoint = net::bind(self.key.clone(), relay.as_deref(), self.cfg.lan()).await?;let req = JoinRequest {team: team.clone(),- secret: secret.clone(),+ secret,person: person.clone(),machine: self.machine.clone(),proof: proof.clone(),+ owner_only: proof.is_some(),+ };+ // Another computer of an account that holds a name is best let in by one of that person's own machines, which+ // every build takes: ask for that first. Else any machine of this build lets it in on its proof.+ let res = match net::join(&endpoint, &peers, &req).await {+ Err(e) if e.to_string().contains(team::SAME_ACCOUNT) => {+ let any = JoinRequest { owner_only: false, ..req };+ net::join(&endpoint, &peers, &any).await.map_err(|again| if taken(&again) { e } else { again })+ }+ r => r,};- let res = net::join(&endpoint, &peers, &req).await;endpoint.close().await;let mut state = TeamState::verified(&res?)?;let me = self.key.public();- if !handed_the_invited_team(&state, &team, &secret, &me) {+ // A ticket names the team; a code can't (whoever answers on the code's key knows the code, so could make up a+ // team), which is why a sign-in joins only with a link.+ if (!team.is_empty() && state.id != team) || !state.is_active(&me) {bail!("the team did not add this machine");}// An inviting machine from before sign-in proofs passes ours over: it goes out with this machine's state.@@ -453,11 +465,13 @@ impl Daemon {rtt_ms: None,last_seen: None,verified: false,+ has_proof: false,};let (Some(team), net) = (self.team_state(), self.net()) else { return vec![here] };let verified = team.verified_people();let remotes = net.as_ref().map(|n| n.remotes()).unwrap_or_default();- let mut out = vec![MachineInfo { verified: verified.contains_key(&here.person), ..here }];+ let mut out =+ vec![MachineInfo { verified: verified.contains_key(&here.person), has_proof: team.has_proof(&me), ..here }];for m in team.active().filter(|m| m.endpoint != me) {let link = net.as_ref().and_then(|n| n.link_info(&m.endpoint));out.push(MachineInfo {@@ -470,6 +484,7 @@ impl Daemon {rtt_ms: link.map(|l| l.rtt_ms),last_seen: remotes.get(&m.endpoint).map(|r| r.last_seen).filter(|t| *t > 0),verified: verified.contains_key(&m.person),+ has_proof: team.has_proof(&m.endpoint),});}out[1..].sort_by(|a, b| (&a.person, &a.machine).cmp(&(&b.person, &b.machine)));@@ -594,46 +609,29 @@ impl Daemon {}}-/// Whether the team a joiner was handed is the one it was invited to: the one a team link names, holding the invite it-/// presented (for a code, the only thing that names the team), signed by a member, and letting this machine in.-fn handed_the_invited_team(state: &TeamState, team: &str, secret: &str, me: &EndpointId) -> bool {- let invited =- state.invites.get(&team::hash(secret)).is_some_and(|i| i.body.reusable || i.body.used_by == Some(*me));- (team.is_empty() || state.id == team) && invited && state.is_active(me)+/// The name is someone else's in the team (as every build says it).+pub fn taken(e: &anyhow::Error) -> bool {+ e.to_string().contains("is already in this team")+}++/// A sign-in proof goes with a team link, never a four-word code: a code can't show the joiner which team answers it.+fn sign_in_needs_a_link(invite_text: &str, proof: Option<&str>) -> Result<()> {+ if proof.is_some() && invite::normalize(invite_text).is_some() {+ bail!("signing in joins a team with its link, not a four-word code: ask for the team link");+ }+ Ok(())}#[cfg(test)]mod tests {use super::*;- use iroh::SecretKey;#[test]- fn a_code_joiner_checks_the_team_it_is_handed() {- let (a, me) = (SecretKey::generate(), SecretKey::generate());+ fn a_sign_in_never_joins_with_a_code() {let code = invite::generate();- let secret = invite::secret(&code);- let mut s = TeamState::found("vibes", "alex", "mbp", &a);- s.invite(&a, &secret, 24, None);- s.redeem(&a, &secret, "sam", me.public(), None).unwrap();- s.put_member(&a, me.public(), "sam", "nuc", true);- let handed = TeamState::verified(&s).unwrap();- assert!(handed_the_invited_team(&handed, "", &secret, &me.public()));- assert!(handed_the_invited_team(&handed, &s.id, &secret, &me.public()));- assert!(!handed_the_invited_team(&handed, "00112233445566778899aabbccddeeff", &secret, &me.public()));- // Some other team, with this machine in it but not the invite (whoever answered on the code's key made it up).- let mut other = TeamState::found("not yours", "mallory", "evil", &a);- other.put_member(&a, me.public(), "sam", "nuc", true);- let other = TeamState::verified(&other).unwrap();- assert!(other.is_active(&me.public()));- assert!(!handed_the_invited_team(&other, "", &secret, &me.public()), "the code's invite isn't in it");- // The invite, but used by another machine.- let mut used = TeamState::found("vibes", "alex", "mbp", &a);- used.invite(&a, &secret, 24, None);- used.redeem(&a, &secret, "eve", SecretKey::generate().public(), None).unwrap();- used.put_member(&a, me.public(), "sam", "nuc", true);- assert!(!handed_the_invited_team(&TeamState::verified(&used).unwrap(), "", &secret, &me.public()));- // A team link's invite is reusable.- let link = s.link_secret().unwrap().to_string();- assert!(handed_the_invited_team(&handed, &s.id, &link, &me.public()));+ assert!(sign_in_needs_a_link(&code, Some("jws")).unwrap_err().to_string().contains("not a four-word code"));+ assert!(sign_in_needs_a_link(&code.replace('-', " "), Some("jws")).is_err());+ assert!(sign_in_needs_a_link(&code, None).is_ok(), "codes still work without signing in");+ assert!(sign_in_needs_a_link("https://reasonmachines.com/network/join/#rn1-AAAA", Some("jws")).is_ok());}}diff --git a/src/main.rs b/src/main.rsindex 9f25ba4..673aec3 100644--- a/src/main.rs+++ b/src/main.rs@@ -316,7 +316,17 @@ async fn main() -> Result<()> {// Don't wait on anything left behind (a stuck stdin read): the agent is waiting on us.std::process::exit(0)}- Some(cmd) => cli(cmd).await,+ Some(cmd) => {+ // With --json, every failure is JSON too.+ let json = matches!(+ cmd,+ Cmd::Init { json: true, .. }+ | Cmd::Join { json: true, .. }+ | Cmd::Link { json: true, .. }+ | Cmd::Team { json: true }+ );+ cli(cmd).await.or_else(|e| json_error(json, e))+ }// `reason network` alone: get set up if needed, else show who's around.None => {let in_team = Link::new(None).call::<TeamInfo>(Request::Team).await.is_ok();@@ -460,7 +470,7 @@ async fn cli(cmd: Cmd) -> Result<()> {bail!("name the team: `{CLI} init <team>` (or run it in a terminal to be asked)")};let req = Request::CreateTeam { name: team, person: default_person(person), relay, proof };- let t: TeamInfo = link.call(req).await.or_else(|e| json_error(json, e))?;+ let t: TeamInfo = link.call(req).await?;wait_exit(daemon_pid()).await;if json {let agents = if no_setup { None } else { Some(setup::quietly().await?) };@@ -478,7 +488,7 @@ async fn cli(cmd: Cmd) -> Result<()> {Cmd::Join { invite, person, no_setup, proof, json } => {let Some(invite) = invite else { bail!("give the invite code: `{CLI} join <code>`") };let req = Request::Join { ticket: invite, person: default_person(person), proof };- let t: TeamInfo = link.call(req).await.or_else(|e| json_error(json, e))?;+ let t: TeamInfo = link.call(req).await?;wait_exit(daemon_pid()).await;let agents = if no_setup || !json { None } else { Some(setup::quietly().await?) };if !json {@@ -623,13 +633,24 @@ async fn cli(cmd: Cmd) -> Result<()> {async fn team_json(link: &std::sync::Arc<Link>, set_up_for: Option<Vec<&str>>) -> Result<serde_json::Value> {let t: TeamInfo = link.call(Request::Team).await?;let l: LinkInfo = link.call(Request::Link { new: false }).await?;+ team_value(&t, &l, set_up_for)+}++fn team_value(t: &TeamInfo, l: &LinkInfo, set_up_for: Option<Vec<&str>>) -> Result<serde_json::Value> {+ // A daemon from before team ids were in its reply (it was running when this binary was updated).+ if t.id.is_empty() {+ bail!(+ "the Reason Network daemon running is older than this command: restart the Reason Network daemon (`{CLI} stop`)"+ );+ }let endpoint = t.machines.iter().find(|m| m.is_me).map(|m| m.endpoint.clone()).unwrap_or_default();let members: Vec<_> = t.machines.iter().map(|m| {serde_json::json!({"person": m.person, "machine": m.machine, "endpoint": m.endpoint,- "verified": m.verified, "is_me": m.is_me, "online": m.is_me || m.online})+ "verified": m.verified, "has_proof": m.has_proof, "is_me": m.is_me,+ "online": m.is_me || m.online})}).collect();let mut out = serde_json::json!({@@ -642,18 +663,30 @@ async fn team_json(link: &std::sync::Arc<Link>, set_up_for: Option<Vec<&str>>) -Ok(out)}-/// With `--json`, a failure is a JSON object on stdout too: `{"error":"name_taken"}` when the name is someone else's-/// in the team (the Reason CLI then asks for another), else the message.+/// With `--json`, a failure is a JSON object on stdout too (see `json_failure`).fn json_error<T>(json: bool, e: anyhow::Error) -> Result<T> {if !json {return Err(e);}- let msg = format!("{e:#}");- let error = if msg.contains("is already in this team") { "name_taken" } else { msg.as_str() };- println!("{}", serde_json::json!({ "error": error }));+ println!("{}", json_failure(&e));std::process::exit(1)}+/// `{"error":"same_account_needs_owner"}` when one of the person's own computers should let this one in,+/// `{"error":"name_taken"}` when the name is someone else's in the team (the Reason CLI then asks for another), else the+/// message.+fn json_failure(e: &anyhow::Error) -> serde_json::Value {+ let msg = format!("{e:#}");+ let error = if msg.contains(team::SAME_ACCOUNT) {+ team::SAME_ACCOUNT+ } else if msg.contains("is already in this team") {+ "name_taken"+ } else {+ msg.as_str()+ };+ serde_json::json!({ "error": error })+}+/// The running daemon's pid, from its lock file.fn daemon_pid() -> Option<u32> {client::running_daemon()@@ -681,3 +714,63 @@ pub async fn stop_daemon() -> bool {wait_exit(pid).await;true}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn json_failures_name_the_cases_the_reason_cli_handles() {+ let e = |m: &str| json_failure(&anyhow::anyhow!(m.to_string()));+ assert_eq!(+ e("'alex' is already in this team; join with another name (--as)"),+ serde_json::json!({"error": "name_taken"})+ );+ let same = "only one of alex's own computers lets this one in as alex (same_account_needs_owner)";+ assert_eq!(e(same), serde_json::json!({"error": "same_account_needs_owner"}));+ assert_eq!(+ e("this sign-in proof expired; sign in again"),+ serde_json::json!({"error": "this sign-in proof expired; sign in again"})+ );+ }++ #[test]+ fn team_json_needs_a_daemon_that_gives_the_team_id() {+ let me = MachineInfo {+ person: "alex".into(),+ machine: "mbp".into(),+ endpoint: "ab".repeat(32),+ is_me: true,+ online: true,+ link: None,+ rtt_ms: None,+ last_seen: None,+ verified: true,+ has_proof: true,+ };+ let mut t = TeamInfo {+ id: String::new(),+ name: "vibes".into(),+ team_name: "vibes".into(),+ relay: None,+ relay_connected: None,+ person: "alex".into(),+ machine: "mbp".into(),+ machines: vec![me],+ };+ let l = LinkInfo { team: "vibes".into(), url: join_url("rn1-AAAA"), ticket: "rn1-AAAA".into() };+ assert!(team_value(&t, &l, None).unwrap_err().to_string().contains("restart the Reason Network daemon"));+ t.id = "00112233445566778899aabbccddeeff".into();+ let v = team_value(&t, &l, Some(vec!["Claude Code"])).unwrap();+ assert_eq!(+ (v["team_id"].as_str(), v["team_name"].as_str()),+ (Some("00112233445566778899aabbccddeeff"), Some("vibes"))+ );+ assert_eq!(v["invite_line"], "Join the Reason Network: https://reasonmachines.com/network/join/#rn1-AAAA");+ assert_eq!(+ (v["members"][0]["verified"].as_bool(), v["members"][0]["has_proof"].as_bool()),+ (Some(true), Some(true))+ );+ assert_eq!(v["set_up_for"], serde_json::json!(["Claude Code"]));+ }+}diff --git a/src/net.rs b/src/net.rsindex 0bf5969..2ef92fc 100644--- a/src/net.rs+++ b/src/net.rs@@ -55,7 +55,7 @@ pub struct Presence {pub known: Vec<String>,}-#[derive(Debug, Serialize, Deserialize)]+#[derive(Debug, Clone, Serialize, Deserialize)]pub struct JoinRequest {pub team: String,pub secret: String,@@ -64,6 +64,10 @@ pub struct JoinRequest {/// The joiner's Reason sign-in proof. Builds before proofs ignore it.#[serde(default, skip_serializing_if = "Option::is_none")]pub proof: Option<String>,+ /// Let another computer of the account holding the name in only from one of that person's machines (see+ /// `TeamState::redeem`).+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]+ pub owner_only: bool,}#[derive(Debug, Serialize, Deserialize)]@@ -194,6 +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;for addr in peers {let attempt = || async {let conn = endpoint.connect(addr.clone(), JOIN_ALPN).await?;@@ -217,13 +222,19 @@ 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.+ // 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(Err(e)) => last = e,Err(_) => last = anyhow!("couldn't reach the machine that made the invite (is it online?)"),}}- Err(last)+ Err(refused.map_or(last, |r| anyhow!(r)))}/// Nothing is known yet about where that machine is.diff --git a/src/proof.rs b/src/proof.rsindex 478b92a..31ceba7 100644--- a/src/proof.rs+++ b/src/proof.rs@@ -10,9 +10,13 @@ use serde::{Deserialize, Serialize};const ISSUER: &str = "https://reasonmachines.com";const AUDIENCE: &str = "reason-network";const TYPE: &str = "reason-network-proof";+/// Longer than any proof Reason signs: refused before decoding.+const MAX_LEN: usize = 4096;+/// A proof issued further ahead than this is refused (a broken clock, or worse).+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; `REASON_NETWORK_TRUST_KEYS` (a JWKS) adds keys, for tests.+/// key exists; in debug builds `REASON_NETWORK_TRUST_KEYS` (a JWKS) adds keys, for tests.const KEYS: &[(&str, &str)] = &[];/// What a proof says.@@ -45,11 +49,13 @@ struct Claims {proof: Proof,}+#[cfg(any(test, debug_assertions))]#[derive(Deserialize)]struct Jwks {keys: Vec<Jwk>,}+#[cfg(any(test, debug_assertions))]#[derive(Deserialize)]struct Jwk {kty: String,@@ -63,14 +69,16 @@ fn key(x: &str) -> Option<PublicKey> {PublicKey::from_bytes(&bytes.try_into().ok()?).ok()}-/// The keys a proof may be signed with: the compiled-in ones, those in `REASON_NETWORK_TRUST_KEYS`, and in tests a-/// test key.+/// The keys a proof may be signed with: the compiled-in ones and, in debug builds, those in+/// `REASON_NETWORK_TRUST_KEYS` (release builds trust only the compiled-in keys), and in tests a test key.fn trusted() -> &'static [(String, PublicKey)] {static KEYS_: std::sync::OnceLock<Vec<(String, PublicKey)>> = std::sync::OnceLock::new();KEYS_.get_or_init(|| {+ #[allow(unused_mut)]let mut out: Vec<(String, PublicKey)> =KEYS.iter().filter_map(|(kid, x)| Some((kid.to_string(), key(x)?))).collect();- if let Some(jwks) = crate::paths::env_var_os("TRUST_KEYS")+ #[cfg(any(test, debug_assertions))]+ if let Some(jwks) = std::env::var_os("REASON_NETWORK_TRUST_KEYS")&& let Ok(jwks) = serde_json::from_str::<Jwks>(&jwks.to_string_lossy()){out.extend(@@ -89,11 +97,26 @@ fn trusted() -> &'static [(String, PublicKey)] {/// Checks `jws` for the machine `endpoint`: Reason's signature, issuer, audience, expiry, and that it names this/// machine.pub fn verify(jws: &str, endpoint: &EndpointId) -> Result<Proof> {- verify_with(jws, endpoint, crate::util::now_ms() / 1000, trusted())+ verify_with(jws, endpoint, crate::util::now_ms() / 1000, trusted(), true)}-fn verify_with(jws: &str, endpoint: &EndpointId, now: i64, keys: &[(String, PublicKey)]) -> Result<Proof> {+/// The same, except that a proof that expired still counts: for who may hold a name in the team, which mustn't change+/// as time passes (or differ between machines whose clocks do). Only "verified" goes by `verify`.+pub fn verify_ignoring_expiry(jws: &str, endpoint: &EndpointId) -> Result<Proof> {+ verify_with(jws, endpoint, crate::util::now_ms() / 1000, trusted(), false)+}++fn verify_with(+ jws: &str,+ endpoint: &EndpointId,+ now: i64,+ keys: &[(String, PublicKey)],+ expiry: bool,+) -> Result<Proof> {let bad = || anyhow!("this sign-in proof is damaged");+ if jws.len() > MAX_LEN {+ bail!("this sign-in proof is too long");+ }let mut parts = jws.trim().split('.');let (Some(h), Some(c), Some(s), None) = (parts.next(), parts.next(), parts.next(), parts.next()) else {return Err(bad());@@ -115,9 +138,12 @@ fn verify_with(jws: &str, endpoint: &EndpointId, now: i64, keys: &[(String, Publbail!("this sign-in proof isn't from Reason Network");}let p = claims.proof;- if p.exp <= now {+ if expiry && p.exp <= now {bail!("this sign-in proof expired; sign in again");}+ if p.iat > now.saturating_add(MAX_SKEW_SECS) {+ bail!("this sign-in proof is dated in the future (is this computer's clock right?)");+ }if p.endpoint != endpoint.to_string() {bail!("this sign-in proof is for another machine");}@@ -213,10 +239,13 @@ pub(crate) mod tests {fn only_trusted_keys_count() {let me = SecretKey::generate().public();let jws = proof("user_1", "alex", &me);- assert!(verify_with(&jws, &me, 0, &[]).is_err(), "no keys, nothing verifies");+ let now = crate::util::now_ms() / 1000;+ assert!(verify_with(&jws, &me, now, &[], true).is_err(), "no keys, nothing verifies");let keys = [(KID.to_string(), signer().public())];- assert!(verify_with(&jws, &me, 0, &keys).is_ok());- assert!(verify_with(&jws, &me, i64::MAX, &keys).is_err(), "expired by then");+ assert!(verify_with(&jws, &me, now, &keys, true).is_ok());+ let later = now + 91 * 86_400;+ assert!(verify_with(&jws, &me, later, &keys, true).is_err(), "expired by then");+ assert!(verify_with(&jws, &me, later, &keys, false).is_ok(), "but still Reason's word, for who holds a name");}#[test]@@ -227,4 +256,54 @@ pub(crate) mod tests {assert_eq!(key(&jwks.keys[0].x), Some(signer().public()));assert_eq!(key("not base64!"), None);}++ #[test]+ fn an_expired_proof_still_says_whose_machine_it_is() {+ let me = SecretKey::generate().public();+ let mut c = claims("user_1", "alex", &me);+ c["exp"] = json!(crate::util::now_ms() / 1000 - 1);+ let jws = sign_with(&signer(), json!({"alg": "EdDSA", "kid": KID, "typ": TYPE}), c);+ assert!(verify(&jws, &me).is_err());+ assert_eq!(verify_ignoring_expiry(&jws, &me).unwrap().sub, "user_1");+ // Everything else still counts.+ assert!(verify_ignoring_expiry(&jws, &SecretKey::generate().public()).is_err());+ let forged = sign_with(+ &SecretKey::generate(),+ json!({"alg": "EdDSA", "kid": KID, "typ": TYPE}),+ claims("user_1", "alex", &me),+ );+ assert!(verify_ignoring_expiry(&forged, &me).is_err());+ }++ #[test]+ fn refuses_proofs_from_the_future() {+ let me = SecretKey::generate().public();+ for iat in [json!(i64::MAX), json!(crate::util::now_ms() / 1000 + 2 * 86_400)] {+ let mut c = claims("user_1", "alex", &me);+ c["iat"] = iat;+ let jws = sign_with(&signer(), json!({"alg": "EdDSA", "kid": KID, "typ": TYPE}), c);+ assert!(verify(&jws, &me).unwrap_err().to_string().contains("in the future"));+ assert!(verify_ignoring_expiry(&jws, &me).is_err());+ }+ let mut c = claims("user_1", "alex", &me);+ c["iat"] = json!(crate::util::now_ms() / 1000 + 3600);+ assert!(+ verify(&sign_with(&signer(), json!({"alg": "EdDSA", "kid": KID, "typ": TYPE}), c), &me).is_ok(),+ "a clock a bit ahead"+ );+ }++ #[test]+ fn refuses_a_huge_proof_before_decoding_it() {+ let me = SecretKey::generate().public();+ let header = BASE64URL_NOPAD.encode(br#"{"alg":"EdDSA","kid":"test-1","typ":"reason-network-proof"}"#);+ for big in [+ format!("{}.A.{}", "A".repeat(4 << 20), "A".repeat(86)),+ format!("{header}.{}.{}", "A".repeat(4 << 20), "A".repeat(86)),+ ] {+ let t = std::time::Instant::now();+ assert!(verify(&big, &me).unwrap_err().to_string().contains("too long"));+ assert!(t.elapsed() < std::time::Duration::from_millis(50), "{:?}", t.elapsed());+ }+ }}diff --git a/src/proto.rs b/src/proto.rsindex c95e3ff..5873c1b 100644--- a/src/proto.rs+++ b/src/proto.rs@@ -323,9 +323,13 @@ pub struct MachineInfo {pub link: Option<String>,pub rtt_ms: Option<u64>,pub last_seen: Option<i64>,- /// The person's name is verified: a machine of theirs carries a Reason sign-in proof for it.+ /// The person is verified (it's per person, the same on each of their machines): a machine of theirs carries a+ /// Reason sign-in proof for their name, good now.#[serde(default)]pub verified: bool,+ /// This machine carries such a proof itself.+ #[serde(default)]+ pub has_proof: bool,}#[derive(Debug, Clone, Serialize, Deserialize)]diff --git a/src/team.rs b/src/team.rsindex d3c267f..d1fcc71 100644--- a/src/team.rs+++ b/src/team.rs@@ -102,6 +102,10 @@ pub struct TeamState {pub attestations: BTreeMap<String, String>,}+/// A join refused because one of the person's own computers should let this one in (another computer of the same+/// Reason account): the joiner asks the ticket's other machines.+pub const SAME_ACCOUNT: &str = "same_account_needs_owner";+/// Entries stamped further ahead than this are refused (a broken clock, or worse).const MAX_SKEW_MS: i64 = 86_400_000;@@ -171,13 +175,22 @@ impl TeamState {}/// Whether `endpoint` may be an active machine of `person`, on `signer`'s word: one of the person's machines vouches- /// for it, nobody else has the name, or Reason says it belongs to the account the name is verified for.+ /// for it, nobody else has the name, or Reason says it belongs to the account that holds the name.fn may_take(&self, person: &str, endpoint: &EndpointId, signer: &EndpointId) -> bool {self.active().any(|m| m.endpoint == *signer && m.person == person)|| !self.active().any(|m| m.person == person && m.endpoint != *endpoint)- || self- .proof(endpoint)- .is_some_and(|p| p.name == person && self.verified_people().get(person) == Some(&p.sub))+ || self.signed_proof(endpoint).is_some_and(|p| self.same_account(person, &p, endpoint))+ }++ /// Whether `p` (the proof of `endpoint`) is for `person`, and from the Reason account another of `person`'s machines+ /// holds the name with. Expiry doesn't count here: who holds a name mustn't change as time passes.+ pub fn same_account(&self, person: &str, p: &Proof, endpoint: &EndpointId) -> bool {+ p.name == person+ && self.active().any(|m| {+ m.person == person+ && m.endpoint != *endpoint+ && self.signed_proof(&m.endpoint).is_some_and(|q| q.name == person && q.sub == p.sub)+ })}/// The machine's sign-in proof, if it has one that verifies now.@@ -185,7 +198,18 @@ impl TeamState {proof::verify(self.attestations.get(&endpoint.to_string())?, endpoint).ok()}- /// Verified people: each name an active machine's proof is for, with the Reason account it belongs to.+ /// The machine's sign-in proof, expired or not.+ fn signed_proof(&self, endpoint: &EndpointId) -> Option<Proof> {+ proof::verify_ignoring_expiry(self.attestations.get(&endpoint.to_string())?, endpoint).ok()+ }++ /// Whether the machine carries a proof, good now, for the name it goes by.+ pub fn has_proof(&self, endpoint: &EndpointId) -> bool {+ self.member(endpoint).is_some_and(|m| self.proof(endpoint).is_some_and(|p| p.name == m.person))+ }++ /// Verified people: each name an active machine has a proof for, good now, with the Reason account it belongs to.+ /// It's per person: all of a verified person's machines show as theirs.pub fn verified_people(&self) -> HashMap<String, String> {self.active().filter_map(|m| self.proof(&m.endpoint).filter(|p| p.name == m.person))@@ -193,10 +217,11 @@ impl TeamState {.collect()}- /// Records `endpoint`'s sign-in proof, if it verifies and is 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; true if it+ /// was taken.pub fn attest(&mut self, endpoint: &EndpointId, jws: &str) -> bool {- let Ok(p) = proof::verify(jws, endpoint) else { return false };- if self.proof(endpoint).is_some_and(|cur| cur.iat >= p.iat) {+ 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) {return false;}self.attestations.insert(endpoint.to_string(), jws.trim().to_string());@@ -284,7 +309,8 @@ impl TeamState {}/// Checks that `secret` admits `person` (with the joiner's verified sign-in proof, if any), and marks the invite- /// used by `joiner`.+ /// used by `joiner`. `owner_only`: another computer of the account holding the name is let in only by one of that+ /// person's machines (which every build takes), not on its proof (which builds before proofs don't).pub fn redeem(&mut self,key: &SecretKey,@@ -292,6 +318,7 @@ impl TeamState {person: &str,joiner: EndpointId,proof: Option<&Proof>,+ owner_only: bool,) -> Result<()> {let h = hash(secret);let signed = self.invites.get(&h).ok_or_else(|| anyhow!("unknown invite"))?;@@ -319,8 +346,12 @@ impl TeamState {bail!("only one of {p}'s machines can let this one in; try again while one is online")}Some(_) => {}- // Another computer of the account the name is verified for may join under it.- None if proof.is_some_and(|p| p.name == person && self.verified_people().get(person) == Some(&p.sub)) => {}+ // Another computer of the account that holds the name may join under it.+ None if proof.is_some_and(|p| self.same_account(person, p, &joiner)) => {+ if owner_only && self.member(&key.public()).is_none_or(|m| m.person != person) {+ bail!("only one of {person}'s own computers lets this one in as {person} ({SAME_ACCOUNT})")+ }+ }None if self.active().any(|m| m.person == person && m.endpoint != joiner) => {bail!("'{person}' is already in this team; join with another name (--as)")}@@ -339,13 +370,15 @@ impl TeamState {bail!("state from a different team");}let mut changed = false;- // Proofs check themselves; they come before members, whose names they can vouch for (`may_take`).+ // Proofs check themselves; they come before members, whose names they can vouch for (`may_take`). Only+ // members' are kept (see the end).+ let proofs_before = self.attestations.clone();for (k, jws) in &other.attestations {if let Ok(id) = k.parse::<EndpointId>()+ && (self.members.contains_key(k) || other.members.contains_key(k))&& self.attestations.get(k) != Some(jws)- && self.attest(&id, jws){- changed = true;+ self.attest(&id, jws);}}// Then admissions: they decide who may sign everything else. One admission can vouch for the signer of@@ -431,7 +464,8 @@ impl TeamState {changed = true;}}- Ok(changed)+ self.attestations.retain(|k, _| self.members.contains_key(k));+ Ok(changed || self.attestations != proofs_before)}/// Validates a state received from a stranger (the join reply): every entry must trace back to the founder.@@ -678,17 +712,17 @@ mod tests {sa.invite(&a, &secret, 24, None);// b joins through a: a redeems and adds b; b verifies what it receives.- sa.redeem(&a, &secret, "alice", b.public(), None).unwrap();+ sa.redeem(&a, &secret, "alice", b.public(), None, false).unwrap();sa.put_member(&a, b.public(), "alice", "xps", true);let mut sb = TeamState::verified(&sa).unwrap();assert_eq!(sb, sa);assert!(sb.is_active(&b.public()));- assert!(sa.redeem(&a, &secret, "eve", c.public(), None).is_err(), "invites are single use");+ assert!(sa.redeem(&a, &secret, "eve", c.public(), None, false).is_err(), "invites are single use");// b invites c; a learns about c by merging b's copy.let s2 = random_secret();sb.invite(&b, &s2, 1, None);- sb.redeem(&b, &s2, "sam", c.public(), None).unwrap();+ sb.redeem(&b, &s2, "sam", c.public(), None, false).unwrap();sb.put_member(&b, c.public(), "sam", "nuc", true);assert!(sa.merge(&sb).unwrap());assert!(sa.is_active(&c.public()));@@ -738,7 +772,7 @@ mod tests {s.put_member(&f, f.public(), "alex", "mbp", false); // founder leaveslet secret = random_secret();s.invite(&b, &secret, 24, None);- s.redeem(&b, &secret, "sam", d.public(), None).unwrap();+ s.redeem(&b, &secret, "sam", d.public(), None, false).unwrap();s.put_member(&b, d.public(), "sam", "nuc", true);let sd = TeamState::verified(&s).unwrap();assert!(sd.is_active(&d.public()) && sd.is_active(&b.public()) && !sd.is_active(&f.public()));@@ -763,7 +797,7 @@ mod tests {// A newcomer sees the same, including c (admitted by b, who is gone now).let secret = random_secret();x.invite(&f, &secret, 24, None);- x.redeem(&f, &secret, "dee", d.public(), None).unwrap();+ x.redeem(&f, &secret, "dee", d.public(), None, false).unwrap();x.put_member(&f, d.public(), "dee", "pi", true);let z = TeamState::verified(&x).unwrap();assert!(z.is_active(&c.public()) && !z.is_active(&b.public()));@@ -789,14 +823,20 @@ mod tests {let mut s = TeamState::found("vibes", "alex", "mbp", &a);let first = random_secret();s.invite(&a, &first, 24, None);- s.redeem(&a, &first, "alice", b.public(), None).unwrap();+ s.redeem(&a, &first, "alice", b.public(), None, false).unwrap();s.put_member(&a, b.public(), "alice", "xps", true);- assert!(s.redeem(&a, &first, "alice", b.public(), None).is_ok(), "a retry by the same machine is fine");+ assert!(s.redeem(&a, &first, "alice", b.public(), None, false).is_ok(), "a retry by the same machine is fine");let from_b = random_secret();s.invite(&b, &from_b, 720, None);s.put_member(&a, b.public(), "alice", "xps", false);- assert!(s.redeem(&a, &first, "alice", b.public(), None).is_err(), "removed: the old invite doesn't readmit");- assert!(s.redeem(&a, &from_b, "sam", c.public(), None).is_err(), "invites by a removed machine are dead");+ assert!(+ s.redeem(&a, &first, "alice", b.public(), None, false).is_err(),+ "removed: the old invite doesn't readmit"+ );+ assert!(+ s.redeem(&a, &from_b, "sam", c.public(), None, false).is_err(),+ "invites by a removed machine are dead"+ );}#[test]@@ -818,11 +858,11 @@ mod tests {let mut s = TeamState::found("vibes", "alex", "mbp", &a);let open = random_secret();s.invite(&a, &open, 24, None);- assert!(s.redeem(&a, &open, "alex", b.public(), None).is_err());+ assert!(s.redeem(&a, &open, "alex", b.public(), None, false).is_err());let mine = random_secret();s.invite(&a, &mine, 24, Some("alex".into()));- assert!(s.redeem(&a, &mine, "alice", b.public(), None).is_err());- s.redeem(&a, &mine, "alex", b.public(), None).unwrap();+ assert!(s.redeem(&a, &mine, "alice", b.public(), None, false).is_err());+ s.redeem(&a, &mine, "alex", b.public(), None, false).unwrap();}#[test]@@ -830,7 +870,7 @@ mod tests {let (a, b, fake, mine) = (key(), key(), key(), key());let mut s = TeamState::found("vibes", "alex", "mbp", &a);let link = s.link_secret().unwrap().to_string();- s.redeem(&a, &link, "alice", b.public(), None).unwrap();+ s.redeem(&a, &link, "alice", b.public(), None, false).unwrap();s.put_member(&a, b.public(), "alice", "xps", true);// alice's machine signs a new machine in as alex, on its copy, and sends it over.let mut evil = s.clone();@@ -906,20 +946,20 @@ mod tests {let (a, b, c, d) = (key(), key(), key(), key());let mut s = TeamState::found("vibes", "alex", "mbp", &a);let link = s.link_secret().unwrap().to_string();- s.redeem(&a, &link, "alice", b.public(), None).unwrap();+ s.redeem(&a, &link, "alice", b.public(), None, false).unwrap();s.put_member(&a, b.public(), "alice", "xps", true);- s.redeem(&a, &link, "sam", c.public(), None).unwrap();+ s.redeem(&a, &link, "sam", c.public(), None, false).unwrap();s.put_member(&a, c.public(), "sam", "nuc", true);- assert!(s.redeem(&a, &link, "alice", d.public(), None).is_err(), "names stay unique");+ assert!(s.redeem(&a, &link, "alice", d.public(), None, false).is_err(), "names stay unique");// A joiner learns the link, and can show it too.let joined = TeamState::verified(&s).unwrap();assert_eq!(joined.link_secret(), Some(link.as_str()));assert_eq!(s.without_secrets().link, None);assert!(s.without_secrets().invites.is_empty());s.new_link(&b);- assert!(s.redeem(&a, &link, "dee", d.public(), None).is_err(), "the old link stops working");+ assert!(s.redeem(&a, &link, "dee", d.public(), None, false).is_err(), "the old link stops working");let fresh = s.link_secret().unwrap().to_string();- s.redeem(&a, &fresh, "dee", d.public(), None).unwrap();+ s.redeem(&a, &fresh, "dee", d.public(), None, false).unwrap();}#[test]@@ -1010,13 +1050,13 @@ mod tests {let link = s.link_secret().unwrap().to_string();let p = |sub: &str, name: &str, k: &SecretKey| crate::proof::verify(&proof(sub, name, k), &k.public()).unwrap();// Another account, or no proof, can't take it.- let err = s.redeem(&a, &link, "alex", b.public(), Some(&p("u_mallory", "alex", &b))).unwrap_err();+ let err = s.redeem(&a, &link, "alex", b.public(), Some(&p("u_mallory", "alex", &b)), false).unwrap_err();assert!(err.to_string().contains("already in this team"), "{err}");- assert!(s.redeem(&a, &link, "alex", b.public(), None).is_err());+ assert!(s.redeem(&a, &link, "alex", b.public(), None, false).is_err());// Another computer of the same account can, through the team link, let in by anyone.- s.redeem(&a, &link, "alice", c.public(), None).unwrap();+ s.redeem(&a, &link, "alice", c.public(), None, false).unwrap();s.put_member(&a, c.public(), "alice", "xps", true);- s.redeem(&c, &link, "alex", d.public(), Some(&p("u_alex", "alex", &d))).unwrap();+ s.redeem(&c, &link, "alex", d.public(), Some(&p("u_alex", "alex", &d)), false).unwrap();s.attest(&d.public(), &proof("u_alex", "alex", &d));s.put_member(&c, d.public(), "alex", "mini", true);let peer = TeamState::verified(&s).unwrap();@@ -1027,7 +1067,90 @@ mod tests {assert!(!TeamState::verified(&forged).unwrap().is_active(&d.public()));// A name nobody verified stays with whoever has it, proof or not.let e = key();- let err = s.redeem(&a, &link, "alice", e.public(), Some(&p("u_alice", "alice", &e))).unwrap_err();+ let err = s.redeem(&a, &link, "alice", e.public(), Some(&p("u_alice", "alice", &e)), false).unwrap_err();assert!(err.to_string().contains("already in this team"), "{err}");}++ /// A proof as Reason signs it, expiring `ttl` seconds from now (in the past when negative).+ fn proof_for(sub: &str, name: &str, k: &SecretKey, ttl: i64) -> String {+ let mut c = crate::proof::tests::claims(sub, name, &k.public());+ c["exp"] = serde_json::json!(util::now_ms() / 1000 + ttl);+ crate::proof::tests::sign_with(+ &crate::proof::tests::signer(),+ serde_json::json!({"alg": "EdDSA", "kid": crate::proof::tests::KID, "typ": "reason-network-proof"}),+ c,+ )+ }++ #[test]+ fn who_holds_a_name_doesnt_change_when_proofs_expire() {+ let (a, c, d) = (key(), key(), key());+ let mut s = TeamState::found("vibes", "alex", "mbp", &a);+ // Both of alex's proofs have run out: that only takes the "verified" mark away.+ assert!(s.attest(&a.public(), &proof_for("u_alex", "alex", &a, -10)));+ let link = s.link_secret().unwrap().to_string();+ s.redeem(&a, &link, "alice", c.public(), None, false).unwrap();+ s.put_member(&a, c.public(), "alice", "xps", true);+ let jws = proof_for("u_alex", "alex", &d, -10);+ let pd = crate::proof::verify_ignoring_expiry(&jws, &d.public()).unwrap();+ s.redeem(&c, &link, "alex", d.public(), Some(&pd), false).unwrap();+ assert!(s.attest(&d.public(), &jws));+ s.put_member(&c, d.public(), "alex", "mini", true);+ let newcomer = TeamState::verified(&s).unwrap();+ assert!(newcomer.is_active(&d.public()), "a newcomer keeps alex's second computer, as everyone else does");+ assert!(newcomer.verified_people().is_empty() && !newcomer.has_proof(&a.public()));+ // Someone else's expired proof still doesn't take the name.+ let m = key();+ let pm = crate::proof::verify_ignoring_expiry(&proof_for("u_mallory", "alex", &m, -10), &m.public()).unwrap();+ assert!(s.redeem(&c, &link, "alex", m.public(), Some(&pm), false).is_err());+ }++ #[test]+ fn another_computer_of_the_account_asks_for_one_of_its_own_machines() {+ let (a, c, d) = (key(), key(), key());+ let mut s = TeamState::found("vibes", "alex", "mbp", &a);+ s.attest(&a.public(), &proof("u_alex", "alex", &a));+ let link = s.link_secret().unwrap().to_string();+ s.redeem(&a, &link, "alice", c.public(), None, false).unwrap();+ s.put_member(&a, c.public(), "alice", "xps", true);+ let pd = crate::proof::verify(&proof("u_alex", "alex", &d), &d.public()).unwrap();+ // alice's machine isn't alex's: it says so, distinctly (not "taken"), for the joiner to ask the next machine.+ let err = s.redeem(&c, &link, "alex", d.public(), Some(&pd), true).unwrap_err().to_string();+ assert!(err.contains(SAME_ACCOUNT) && !err.contains("already in this team"), "{err}");+ // alex's machine lets it in, which takes no proof for peers to accept: builds before proofs take it too.+ s.redeem(&a, &link, "alex", d.public(), Some(&pd), true).unwrap();+ s.put_member(&a, d.public(), "alex", "mini", true);+ assert!(TeamState::verified(&s).unwrap().is_active(&d.public()));+ // Another account's proof is plain taken, whoever is asked.+ let m = key();+ let pm = crate::proof::verify(&proof("u_mallory", "alex", &m), &m.public()).unwrap();+ let err = s.redeem(&c, &link, "alex", m.public(), Some(&pm), true).unwrap_err().to_string();+ assert!(err.contains("already in this team") && !err.contains(SAME_ACCOUNT), "{err}");+ }++ #[test]+ fn proofs_are_kept_only_for_members() {+ let (a, stranger) = (key(), key());+ let mut s = TeamState::found("vibes", "alex", "mbp", &a);+ let mut other = s.clone();+ other.attestations.insert(stranger.public().to_string(), proof("u_x", "x", &stranger));+ assert!(!s.merge(&other).unwrap(), "nothing to take");+ assert!(s.attestations.is_empty());+ // Nor kept for a member entry that didn't verify.+ let mut forged = s.clone();+ forged.put_member(&stranger, stranger.public(), "x", "evil", true);+ forged.attestations.insert(stranger.public().to_string(), proof("u_x", "x", &stranger));+ assert!(!s.merge(&forged).unwrap());+ assert!(s.attestations.is_empty());+ }++ #[test]+ fn has_proof_is_per_machine_verified_per_person() {+ let (a, b) = (key(), key());+ let mut s = TeamState::found("vibes", "alex", "mbp", &a);+ s.attest(&a.public(), &proof("u_alex", "alex", &a));+ s.put_member(&a, b.public(), "alex", "mini", true);+ assert!(s.has_proof(&a.public()) && !s.has_proof(&b.public()));+ assert!(s.verified_people().contains_key("alex"), "alex is verified, on both machines");+ }}diff --git a/tests/e2e/mixed_versions.py b/tests/e2e/mixed_versions.pyindex fc3e30b..0d2f7de 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"), "mal": (NEW, "evil")}+WHO = {"alex": (NEW, "laptop"), "olga": (OLD, "oldbox"), "nina": (NEW, "desk"), "nina2": (NEW, "pad"), "mal": (NEW, "evil")}results = []@@ -39,6 +39,16 @@ def cli(who, *args):return (r.stdout + r.stderr).strip()+def until(who, args, ok, secs=45):+ """Runs the command until its output passes `ok` (machines find each other in their own time); the last output."""+ deadline = time.time() + secs+ while True:+ out = cli(who, *args)+ if ok(out) or time.time() > deadline:+ return out+ time.sleep(1)++def link_of(out):m = re.search(r"https://\S+/join/#\S+", out)return m.group(0) if m else ""@@ -53,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", "mal")}+ ep = {w: cli(w, "endpoint") for w in ("alex", "nina", "nina2", "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"))@@ -61,11 +71,10 @@ try:check("the older build can't read an rn1 link", "Joined" not in out, out)out = cli("olga", "join", link.replace("#rn1-", "#tincan1"), "--as", "olga", "--no-setup")check("…but joins with the same link as tincan1", "Joined team mixed as olga on oldbox." in out, out)- time.sleep(5)- out = cli("alex", "team")+ out = until("alex", ["team"], lambda o: re.search(r"olga\s+oldbox\s+(direct|relay)", o))check("the older machine is connected, and alex still verified after its state came back",re.search(r"olga\s+oldbox\s+(direct|relay)", out) is not None and "alex (verified)" in out, out)- out = cli("olga", "team")+ out = until("olga", ["team"], lambda o: re.search(r"alex\s+laptop\s+(direct|relay)", o))check("the older machine sees alex, connected", re.search(r"alex\s+laptop\s+(direct|relay)", out) is not None, out)# A machine of this build joins through the older one, which knows nothing of proofs.@@ -73,12 +82,20 @@ try:out = cli("nina", "join", old_link, "--proof", proof("u_nina", "nina", ep["nina"]), "--no-setup")check("this build joins, signed in, through the older machine", "Joined team mixed as nina on desk." in out, out)check("…and its proof goes along anyway", "nina (verified)" in out, out)- time.sleep(6)- out = cli("alex", "team")+ out = until("alex", ["team"], lambda o: re.search(r"nina \(verified\)\s+desk\s+(direct|relay)", o))check("alex's machine sees nina verified", re.search(r"nina \(verified\)\s+desk\s+(direct|relay)", out) is not None, out)- out = cli("olga", "team")- check("the older machine has all three, every signed entry checking out",- all(re.search(rf"{p}\s+{m}\s+(direct|relay|this machine)", out) for p, m in [("alex", "laptop"), ("olga", "oldbox"), ("nina", "desk")]), out)+ three = lambda o: all(re.search(rf"{p}\s+{m}\s+(direct|relay|this machine)", o) for p, m in [("alex", "laptop"), ("olga", "oldbox"), ("nina", "desk")])+ out = until("olga", ["team"], three)+ check("the older machine has all three, every signed entry checking out", three(out), out)+ # nina's second computer, through the older machine's link: it asks the link's machines for one of nina's own,+ # whose word the older machine takes too.+ old_link = link_of(cli("olga", "link")) # now listing nina's machine too+ out = cli("nina2", "join", old_link, "--proof", proof("u_nina", "nina", ep["nina2"]), "--no-setup")+ check("another computer of nina's account joins through the older machine's link", "Joined team mixed as nina on pad." in out, out)+ out = until("olga", ["team"], lambda o: re.search(r"nina\s+pad\s+(direct|relay)", o))+ 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")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)@@ -86,8 +103,7 @@ try:# Messages both ways, and the state kept across restarts.cli("olga", "listen", "--as", "t", "--wait", "0")cli("alex", "listen", "--as", "t", "--wait", "0")- time.sleep(3)- out = cli("alex", "send", "olga/t", "--from", "alex/t", "hello old friend")+ out = until("alex", ["send", "olga/t", "--from", "alex/t", "hello old friend"], lambda o: "→ olga/t" in o and "no session" not in o)check("this build sends to the older one", "→ olga/t" in out, out)out = cli("olga", "listen", "--as", "t", "--wait", "10")check("…which gets it", "hello old friend" in out, out)@@ -96,11 +112,8 @@ try:check("and back", "hello back" in out, out)for w in ("alex", "olga"):cli(w, "stop")- time.sleep(1)cli("olga", "team")- cli("alex", "team")- time.sleep(8)- out = cli("alex", "team")+ out = until("alex", ["team"], lambda o: re.search(r"olga\s+oldbox\s+(direct|relay)", o))check("after both restart, people stay verified", "alex (verified)" in out and "nina (verified)" in outand re.search(r"olga\s+oldbox\s+(direct|relay)", out) is not None, out)finally:diff --git a/tests/e2e/two_machines.py b/tests/e2e/two_machines.pyindex 955cb37..30318c8 100644--- a/tests/e2e/two_machines.py+++ b/tests/e2e/two_machines.py@@ -141,7 +141,8 @@ check("joiner sees alex connected, verified", re.search(r"alex \(verified\)\s+laout = cli("alex", "team")check("founder sees alice connected, verified", re.search(r"alice \(verified\)\s+desktop\s+(direct|relay)", out) is not None, out)j = as_json(cli("alex", "team", "--json"))-check("team --json marks people verified", [m["verified"] for m in j.get("members", [])] == [True, True] and j.get("link", "").startswith("https://"), j)+check("team --json marks people verified, and each machine's proof", [(m["verified"], m["has_proof"]) for m in j.get("members", [])] == [(True, True)] * 2+ and j.get("link", "").startswith("https://") and j.get("team_name") == "vibes" and len(j.get("team_id", "")) == 32, j)j = as_json(cli("alex", "link", "--json"))check("link --json gives the invite line", j.get("invite_line", "").startswith("Join the Reason Network: https://reasonmachines.com/network/join/#rn1-"), j)out = cli("alex", "link")@@ -165,6 +166,11 @@ _, out = run(mal, "join", link.group(1), "--proof", proof("u_alex", "alex", ep["check("someone else's proof is refused", "for another machine" in out and "Joined" not in out, out)_, out = run(mal, "init", "x", "--proof", proof("u_mallory", "mallory", mal_ep, aud="reason"), "--no-setup")check("init refuses a proof for something else", "isn't from Reason Network" in out and "Created" not in out, out)+out, both = run(mal, "join", link.group(1), "--proof", "garbage", "--no-setup", "--json")+check("with --json every failure is JSON", as_json(out) == {"error": "this sign-in proof is damaged"}, both)+code = re.search(r"Invite code for a teammate: ([a-z]+(?:-[a-z]+){3})", cli("alex", "invite", "--code"))+_, out = run(mal, "join", code.group(1), "--proof", proof("u_mallory", "mallory", mal_ep), "--no-setup")+check("a sign-in joins only with a link, never a four-word code", "not a four-word code" in out and "Joined" not in out, out)run(mal, "stop")check("alex's team still has just the two", len(as_json(cli("alex", "team", "--json")).get("members", [])) == 2)# alex signed in on a second computer: the same account takes its name there, let in by anyone's machine.@@ -172,7 +178,7 @@ mini = dict(env("alex"), REASON_NETWORK_HOME=os.path.join(D, "alex-mini"), REASOmini_ep = run(mini, "endpoint")[0]alice_link = re.search(r"(https://\S+#rn1-\S+)", cli("alice", "link")).group(1)_, out = run(mini, "join", alice_link, "--proof", proof("u_alex", "alex", mini_ep), "--no-setup")-check("another computer of the same account joins under its verified name", "Joined team vibes as alex on mini." in out, out)+check("another computer of the same account joins under its verified name (alice's link: alex's machine lets it in)", "Joined team vibes as alex on mini." in out, out)check("…and gets the invite line", "Join the Reason Network: https://reasonmachines.com/network/join/#rn1-" in out, out)time.sleep(3)out = cli("alex", "team")