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: RS256 from Reason's cloud-access issuer
Lars Talian336e28c26273
diff --git a/Cargo.lock b/Cargo.lockindex 559e815..5468069 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -2844,6 +2844,7 @@ dependencies = ["objc2","objc2-app-kit","objc2-foundation",+ "ring","rmcp","rusqlite","schemars",diff --git a/Cargo.toml b/Cargo.tomlindex de84d24..4a4f659 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -22,6 +22,7 @@ futures-lite = "2"getrandom = "0.3"iroh = "1.3"iroh-mdns-address-lookup = "0.6"+ring = "0.17"rmcp = { version = "3.5", features = ["server", "macros", "transport-io"] }rusqlite = { version = "0.37", features = ["bundled"] }schemars = "1"diff --git a/DESIGN.md b/DESIGN.mdindex 14d8be9..c26fd3f 100644--- a/DESIGN.md+++ b/DESIGN.md@@ -127,13 +127,15 @@ the code's key knows the code, so could make up a team), so a sign-in never joinnames 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`, 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.+**Sign-in proofs.** Signed in with Reason, a machine carries a proof: a compact JWS from Reason's cloud-access+issuer (`iss` `https://reasonmachines.com/network`), RS256 only, saying 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 RSA public keys (2048 bits or more), compiled in and never removed, and never calls Reason; debug+builds also trust the keys in `REASON_NETWORK_TRUST_KEYS` (an RSA JWKS), for tests, and release builds don't. A proof+longer than 4 KB (one signed with a 4096-bit key is at most about 1.6 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'texpired. `has_proof` is per machine. Expiry decides only that mark, never membership: who may hold a name goes bydiff --git a/README.md b/README.mdindex a31c972..748b552 100644--- a/README.md+++ b/README.md@@ -37,8 +37,8 @@ curl -fsSL https://reasonmachines.com/install.sh | bash -s -- network join '<linThat's it. Ask any agent "who's on the team?", tell it to ask someone's agent something, or to send them a file.-**Without an account**: install just this engine. It asks your name and a team name, and gives you a team link (on-your clipboard). Teammates open it, paste one command, type their name, and they're in. Or they tell their agent+**Without an account**: install just this engine (answer n when it asks to use your Reason account). It asks your+name and a team name, and gives you a team link (on your clipboard). Teammates open it, paste one command, type their name, and they're in. Or they tell their agent"join my Reason Network team: <link>". Names aren't verified this way.```shdiff --git a/src/proof.rs b/src/proof.rsindex 40151f7..1b88fb9 100644--- a/src/proof.rs+++ b/src/proof.rs@@ -1,27 +1,44 @@//! Reason sign-in proofs: a statement signed by Reason that a machine's key (its endpoint id) belongs to a Reason-//! account, and the name that account goes by. A compact JWS (Ed25519, `EdDSA`), checked here against Reason's public-//! keys, which are compiled in: verifying one never calls Reason. Every machine checks every proof it is shown itself.+//! account, and the name that account goes by. A compact JWS (RS256: RSASSA-PKCS1-v1_5 with SHA-256, from Reason's+//! cloud-access issuer), checked here against Reason's public keys, which are compiled in: verifying one never calls+//! Reason. Every machine checks every proof it is shown itself.use anyhow::{Result, anyhow, bail};use data_encoding::BASE64URL_NOPAD;-use iroh::{EndpointId, PublicKey, Signature};+use iroh::EndpointId;+use ring::signature::{RSA_PKCS1_2048_8192_SHA256, RsaPublicKeyComponents};use serde::{Deserialize, Serialize};-const ISSUER: &str = "https://reasonmachines.com";+const ISSUER: &str = "https://reasonmachines.com/network";const AUDIENCE: &str = "reason-network";const TYPE: &str = "reason-network-proof";-/// Longer than any proof Reason signs: refused before decoding.+/// Refused before decoding. A proof Reason signs with a 4096-bit key is at most about 1.6 KB: the signature is 512+/// bytes (683 in base64url), the header with a 64-character key id about 130, and the claims (a 40-character name, an+/// email of at most 254, the 64-digit endpoint) at most about 790. Even an 8192-bit key, the most `ring` takes, stays+/// under 2.3 KB.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;+/// The smallest RSA key trusted, in bits.+const MIN_BITS: usize = 2048;-/// 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.+/// Reason's proof-signing public keys: key id, then the RSA modulus `n` and exponent `e` in base64url (as in a JWK). 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)] = &[];+///+/// The cloud-access issuer's KMS key (`https://oidc.reasonmachines.com`, which signs proofs as `iss`+/// `https://reasonmachines.com/network`), from https://oidc.reasonmachines.com/.well-known/jwks.json on 2026-10-20.+/// Only that one: proofs come only from KMS (the issuer refuses rather than falling back to its env key,+/// `reason-oidc-prod-2026-10-07`, which isn't trusted here). `the_production_keys_are_pinned` pins it to a hash of its+/// modulus.+const KEYS: &[(&str, &str, &str)] = &[(+ "reason-oidc-kms-2026-10",+ "s5x90QSBmHGl4adzvrjLvQ1ZRiwkDZGJ3pZs7CzPCxjKOBjoPoV6INAi4b8c3F4fMHH1T2BCXH9jX4wQjOCCzZBmB-E9Ch395WiqbLhyY2pH9V-ksbL9DGibS8xCoTT7EySB3FECzd_mHq-kQBCGxKnmBU0uETiPJLV276MzoBFsA8-s0PhsKqiQnUD3AKxHdDX-sWyI145QZasjZIT30Z8ixdRfrcUrLBMtWDhIqsOSP58i3_-3U-2gz_yG-7usgpyTcxCEU1IQGQtKBcJEVwd5QrbGgGE0w_uLxm2anfpT_eCZqOS_TWGYivVZ7TuqnxZgtON6kQgMNctSwprMDQ",+ "AQAB",+)];/// What a proof says.#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]@@ -65,37 +82,40 @@ struct Jwks {#[derive(Deserialize)]struct Jwk {kty: String,- crv: String,kid: String,- x: String,+ n: String,+ e: String,}-fn key(x: &str) -> Option<PublicKey> {- let bytes = BASE64URL_NOPAD.decode(x.trim_end_matches('=').as_bytes()).ok()?;- PublicKey::from_bytes(&bytes.try_into().ok()?).ok()+type Key = RsaPublicKeyComponents<Vec<u8>>;++/// An RSA public key from its base64url modulus and exponent, if it is one of at least `MIN_BITS`.+fn key(n: &str, e: &str) -> Option<Key> {+ let decode = |v: &str| BASE64URL_NOPAD.decode(v.trim_end_matches('=').as_bytes()).ok();+ let strip = |v: Vec<u8>| v.into_iter().skip_while(|b| *b == 0).collect::<Vec<u8>>();+ let (n, e) = (strip(decode(n)?), strip(decode(e)?));+ let bits = n.first().map_or(0, |b| n.len() * 8 - b.leading_zeros() as usize);+ (bits >= MIN_BITS && !e.is_empty()).then_some(RsaPublicKeyComponents { n, e })}/// 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();+fn trusted() -> &'static [(String, Key)] {+ static KEYS_: std::sync::OnceLock<Vec<(String, Key)>> = 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();+ let mut out: Vec<(String, Key)> =+ KEYS.iter().filter_map(|(kid, n, e)| Some((kid.to_string(), key(n, e)?))).collect();#[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(- jwks.keys- .into_iter()- .filter(|k| k.kty == "OKP" && k.crv == "Ed25519")- .filter_map(|k| Some((k.kid, key(&k.x)?))),+ jwks.keys.into_iter().filter(|k| k.kty == "RSA").filter_map(|k| Some((k.kid, key(&k.n, &k.e)?))),);}#[cfg(test)]- out.push((tests::KID.into(), tests::signer().public()));+ out.push((tests::KID.into(), tests::public(tests::signer())));out})}@@ -112,13 +132,7 @@ 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> {+fn verify_with(jws: &str, endpoint: &EndpointId, now: i64, keys: &[(String, Key)], 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");@@ -129,14 +143,14 @@ fn verify_with(};let decode = |p: &str| BASE64URL_NOPAD.decode(p.as_bytes()).map_err(|_| bad());let header: Header = serde_json::from_slice(&decode(h)?).map_err(|_| bad())?;- if header.alg != "EdDSA" || header.typ != TYPE {+ // RS256 only: never `none`, nor HS256 with the public key taken for a shared secret.+ if header.alg != "RS256" || header.typ != TYPE {bail!("not a Reason Network sign-in proof");}let Some((_, key)) = keys.iter().find(|(kid, _)| *kid == header.kid) else {bail!("this sign-in proof is signed with a key this version doesn't know (update Reason Network)");};- let sig: [u8; Signature::LENGTH] = decode(s)?.try_into().map_err(|_| bad())?;- if key.verify(format!("{h}.{c}").as_bytes(), &Signature::from_bytes(&sig)).is_err() {+ if key.verify(&RSA_PKCS1_2048_8192_SHA256, format!("{h}.{c}").as_bytes(), &decode(s)?).is_err() {bail!("this sign-in proof's signature doesn't verify");}let claims: Claims = serde_json::from_slice(&decode(c)?).map_err(|_| bad())?;@@ -168,18 +182,47 @@ pub(crate) mod tests {use iroh::SecretKey;use serde_json::json;+ use ring::signature::RsaKeyPair;+ use std::sync::OnceLock;+pub const KID: &str = "test-1";- /// The key test builds trust (see `trusted`), standing in for Reason's.- pub fn signer() -> SecretKey {- SecretKey::from_bytes(&[7; 32])+ fn pkcs8(cell: &'static OnceLock<RsaKeyPair>, der: &[u8]) -> &'static RsaKeyPair {+ cell.get_or_init(|| RsaKeyPair::from_pkcs8(der).expect("a test key"))+ }++ /// The key test builds trust (see `trusted`), standing in for Reason's: a 2048-bit RSA key made for these tests.+ pub fn signer() -> &'static RsaKeyPair {+ static K: OnceLock<RsaKeyPair> = OnceLock::new();+ pkcs8(&K, include_bytes!("testdata/proof-signer.pk8"))+ }++ /// A key nobody trusts.+ pub fn forger() -> &'static RsaKeyPair {+ static K: OnceLock<RsaKeyPair> = OnceLock::new();+ pkcs8(&K, include_bytes!("testdata/proof-forger.pk8"))}- pub fn sign_with(key: &SecretKey, header: serde_json::Value, claims: serde_json::Value) -> String {+ pub fn public(k: &RsaKeyPair) -> Key {+ RsaPublicKeyComponents::from(k.public())+ }++ pub fn header() -> serde_json::Value {+ json!({"alg": "RS256", "kid": KID, "typ": TYPE})+ }++ /// The RS256 signature over `input`, in base64url.+ pub fn signature(key: &RsaKeyPair, input: &str) -> String {+ let mut sig = vec![0; key.public().modulus_len()];+ key.sign(&ring::signature::RSA_PKCS1_SHA256, &ring::rand::SystemRandom::new(), input.as_bytes(), &mut sig)+ .unwrap();+ BASE64URL_NOPAD.encode(&sig)+ }++ pub fn sign_with(key: &RsaKeyPair, header: serde_json::Value, claims: serde_json::Value) -> String {let enc = |v: serde_json::Value| BASE64URL_NOPAD.encode(&serde_json::to_vec(&v).unwrap());let input = format!("{}.{}", enc(header), enc(claims));- let sig = key.sign(input.as_bytes());- format!("{input}.{}", BASE64URL_NOPAD.encode(&sig.to_bytes()))+ format!("{input}.{}", signature(key, &input))}pub fn claims(sub: &str, name: &str, endpoint: &EndpointId) -> serde_json::Value {@@ -190,7 +233,7 @@ pub(crate) mod tests {/// A good proof that `endpoint` belongs to account `sub`, called `name`.pub fn proof(sub: &str, name: &str, endpoint: &EndpointId) -> String {- sign_with(&signer(), json!({"alg": "EdDSA", "kid": KID, "typ": TYPE}), claims(sub, name, endpoint))+ sign_with(signer(), header(), claims(sub, name, endpoint))}#[test]@@ -204,15 +247,15 @@ pub(crate) mod tests {#[test]fn rejects_bad_proofs() {let me = SecretKey::generate().public();- let header = json!({"alg": "EdDSA", "kid": KID, "typ": TYPE});+ let header = header();let err = |jws: &str| verify(jws, &me).unwrap_err().to_string();let with = |change: &dyn Fn(&mut serde_json::Value)| {let mut c = claims("user_1", "alex", &me);change(&mut c);- sign_with(&signer(), header.clone(), c)+ sign_with(signer(), header.clone(), c)};- let forged = sign_with(&SecretKey::generate(), header.clone(), claims("user_1", "alex", &me));+ let forged = sign_with(forger(), header.clone(), claims("user_1", "alex", &me));assert!(err(&forged).contains("signature doesn't verify"));// A good signature over other claims.let good = proof("user_1", "alex", &me);@@ -226,15 +269,17 @@ pub(crate) mod tests {assert!(err(&mixed).contains("signature doesn't verify"));assert!(err(&with(&|c| c["aud"] = json!("reason"))).contains("isn't from Reason Network"));assert!(err(&with(&|c| c["iss"] = json!("https://evil.example"))).contains("isn't from Reason Network"));+ // Reason's own issuer, but not the network's.+ assert!(err(&with(&|c| c["iss"] = json!("https://reasonmachines.com"))).contains("isn't from Reason Network"));assert!(err(&with(&|c| c["exp"] = json!(crate::util::now_ms() / 1000 - 1))).contains("expired"));assert!(err(&proof("user_1", "alex", &SecretKey::generate().public())).contains("for another machine"));for name in ["", "Alex", "alex smith", &"a".repeat(41)] {assert!(err(&with(&|c| c["name"] = json!(name))).contains("valid name"), "{name:?}");}let unknown =- sign_with(&signer(), json!({"alg": "EdDSA", "kid": "other", "typ": TYPE}), claims("user_1", "alex", &me));+ sign_with(signer(), json!({"alg": "RS256", "kid": "other", "typ": TYPE}), claims("user_1", "alex", &me));assert!(err(&unknown).contains("doesn't know"));- let alg = sign_with(&signer(), json!({"alg": "none", "kid": KID, "typ": TYPE}), claims("user_1", "alex", &me));+ let alg = sign_with(signer(), json!({"alg": "none", "kid": KID, "typ": TYPE}), claims("user_1", "alex", &me));assert!(err(&alg).contains("not a Reason Network sign-in proof"));for damaged in ["", "a.b", "a.b.c.d", &good[..good.len() - 4]] {assert!(verify(damaged, &me).is_err(), "{damaged:?}");@@ -247,7 +292,7 @@ pub(crate) mod tests {let jws = proof("user_1", "alex", &me);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())];+ let keys = [(KID.to_string(), public(signer()))];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");@@ -256,11 +301,65 @@ pub(crate) mod tests {#[test]fn reads_a_jwks_key() {- let x = BASE64URL_NOPAD.encode(signer().public().as_bytes());- let jwks: Jwks =- serde_json::from_value(json!({"keys": [{"kty": "OKP", "crv": "Ed25519", "kid": KID, "x": x}]})).unwrap();- assert_eq!(key(&jwks.keys[0].x), Some(signer().public()));- assert_eq!(key("not base64!"), None);+ let p = public(signer());+ let (n, e) = (BASE64URL_NOPAD.encode(&p.n), BASE64URL_NOPAD.encode(&p.e));+ let jwks: Jwks = serde_json::from_value(+ json!({"keys": [{"kty": "RSA", "kid": KID, "n": n, "e": e, "alg": "RS256", "use": "sig"}]}),+ )+ .unwrap();+ let k = key(&jwks.keys[0].n, &jwks.keys[0].e).unwrap();+ assert_eq!((k.n, k.e), (p.n.clone(), p.e.clone()));+ // A leading zero byte (as some encoders write it) is the same key.+ let padded = BASE64URL_NOPAD.encode(&[&[0u8][..], &p.n].concat());+ assert_eq!(key(&padded, &e).unwrap().n, p.n);+ assert!(key("not base64!", &e).is_none());+ // Under 2048 bits isn't trusted.+ assert!(key(&BASE64URL_NOPAD.encode(&p.n[..128]), &e).is_none());+ }++ #[test]+ fn the_production_keys_are_pinned() {+ // SHA-256 of the modulus, as Reason's JWKS gave it on 2026-10-20: an accidental edit to `KEYS` fails here.+ let pins = [("reason-oidc-kms-2026-10", "c8a5d1e79ecc6c6056a7a11eac0b870a664f4b4ecb27392e7db4544c23e039c4")];+ assert_eq!(KEYS.len(), pins.len());+ for ((kid, n, e), (pinned_kid, pinned)) in KEYS.iter().zip(pins) {+ assert_eq!(*kid, pinned_kid);+ let k = key(n, e).expect("an RSA key of at least 2048 bits");+ let hash = data_encoding::HEXLOWER.encode(ring::digest::digest(&ring::digest::SHA256, &k.n).as_ref());+ assert_eq!(hash, pinned, "{kid}");+ assert_eq!(k.e, [1, 0, 1], "{kid}");+ }+ // It's trusted (next to the test key); the issuer's env key isn't.+ assert!(trusted().iter().any(|(k, _)| k == "reason-oidc-kms-2026-10"));+ assert!(!trusted().iter().any(|(k, _)| k == "reason-oidc-prod-2026-10-07"));+ }++ #[test]+ fn only_rs256_counts() {+ let me = SecretKey::generate().public();+ let c = claims("user_1", "alex", &me);+ let enc = |v: &serde_json::Value| BASE64URL_NOPAD.encode(&serde_json::to_vec(v).unwrap());+ // HS256 keyed with Reason's public key (anyone has it), in the forms it gets published.+ let p = public(signer());+ let jwk =+ json!({"kty": "RSA", "kid": KID, "n": BASE64URL_NOPAD.encode(&p.n), "e": BASE64URL_NOPAD.encode(&p.e)});+ for secret in [p.n.clone(), serde_json::to_vec(&jwk).unwrap()] {+ let input = format!("{}.{}", enc(&json!({"alg": "HS256", "kid": KID, "typ": TYPE})), enc(&c));+ let tag = ring::hmac::sign(&ring::hmac::Key::new(ring::hmac::HMAC_SHA256, &secret), input.as_bytes());+ let jws = format!("{input}.{}", BASE64URL_NOPAD.encode(tag.as_ref()));+ assert!(verify(&jws, &me).unwrap_err().to_string().contains("not a Reason Network sign-in proof"));+ }+ // Unsigned.+ for sig in ["", "AAAA"] {+ let jws = format!("{}.{}.{sig}", enc(&json!({"alg": "none", "kid": KID, "typ": TYPE})), enc(&c));+ assert!(verify(&jws, &me).unwrap_err().to_string().contains("not a Reason Network sign-in proof"));+ }+ // Another RSA scheme's name, over a good RS256 signature.+ let good = proof("user_1", "alex", &me);+ let mut parts = good.split('.');+ let (_, body, sig) = (parts.next(), parts.next().unwrap(), parts.next().unwrap());+ let ps = format!("{}.{body}.{sig}", enc(&json!({"alg": "PS256", "kid": KID, "typ": TYPE})));+ assert!(verify(&ps, &me).is_err());}#[test]@@ -268,16 +367,12 @@ pub(crate) mod tests {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);+ let jws = sign_with(signer(), header(), 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),- );+ let forged = sign_with(forger(), header(), claims("user_1", "alex", &me));assert!(verify_ignoring_expiry(&forged, &me).is_err());}@@ -287,25 +382,22 @@ pub(crate) mod tests {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);+ let jws = sign_with(signer(), header(), 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"- );+ assert!(verify(&sign_with(signer(), header(), 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"}"#);+ let header = BASE64URL_NOPAD.encode(br#"{"alg":"RS256","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)),+ format!("{}.A.{}", "A".repeat(4 << 20), "A".repeat(342)),+ format!("{header}.{}.{}", "A".repeat(4 << 20), "A".repeat(342)),] {let t = std::time::Instant::now();assert!(verify(&big, &me).unwrap_err().to_string().contains("too long"));@@ -318,20 +410,20 @@ pub(crate) mod tests {let me = SecretKey::generate().public();let c = claims("user_1", "alex", &me);for header in [- json!({"alg": "EdDSA", "kid": KID, "typ": TYPE, "crit": ["exp"], "exp": 1}),- json!({"alg": "EdDSA", "kid": KID, "typ": TYPE, "jku": "https://evil.example/keys.json"}),- json!({"alg": "EdDSA", "kid": KID}),+ json!({"alg": "RS256", "kid": KID, "typ": TYPE, "crit": ["exp"], "exp": 1}),+ json!({"alg": "RS256", "kid": KID, "typ": TYPE, "jku": "https://evil.example/keys.json"}),+ json!({"alg": "RS256", "kid": KID}),] {- let jws = sign_with(&signer(), header.clone(), c.clone());+ let jws = sign_with(signer(), header.clone(), c.clone());assert!(verify(&jws, &me).unwrap_err().to_string().contains("damaged"), "{header}");assert!(verify_ignoring_expiry(&jws, &me).is_err(), "{header}");}// A key twice is refused too.let h =- BASE64URL_NOPAD.encode(format!(r#"{{"alg":"EdDSA","kid":"zzz","kid":"{KID}","typ":"{TYPE}"}}"#).as_bytes());+ BASE64URL_NOPAD.encode(format!(r#"{{"alg":"RS256","kid":"zzz","kid":"{KID}","typ":"{TYPE}"}}"#).as_bytes());let body = BASE64URL_NOPAD.encode(&serde_json::to_vec(&c).unwrap());let input = format!("{h}.{body}");- let jws = format!("{input}.{}", BASE64URL_NOPAD.encode(&signer().sign(input.as_bytes()).to_bytes()));+ let jws = format!("{input}.{}", signature(signer(), &input));assert!(verify(&jws, &me).is_err());}}diff --git a/src/team.rs b/src/team.rsindex 949fb4a..0bbe409 100644--- a/src/team.rs+++ b/src/team.rs@@ -1029,8 +1029,8 @@ mod tests {// A proof for another machine, or a forged one, is refused.assert!(!s.attest(&b.public(), &proof("u_alice", "alice", &a)));let forged = crate::proof::tests::sign_with(- &key(),- serde_json::json!({"alg": "EdDSA", "kid": crate::proof::tests::KID, "typ": "reason-network-proof"}),+ crate::proof::tests::forger(),+ crate::proof::tests::header(),crate::proof::tests::claims("u_alice", "alice", &b.public()),);assert!(!s.attest(&b.public(), &forged));@@ -1105,11 +1105,7 @@ mod tests {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,- )+ crate::proof::tests::sign_with(crate::proof::tests::signer(), crate::proof::tests::header(), c)}#[test]diff --git a/src/testdata/proof-forger.pk8 b/src/testdata/proof-forger.pk8new file mode 100644index 0000000..3b770a2Binary files /dev/null and b/src/testdata/proof-forger.pk8 differdiff --git a/src/testdata/proof-signer.pk8 b/src/testdata/proof-signer.pk8new file mode 100644index 0000000..6156dbeBinary files /dev/null and b/src/testdata/proof-signer.pk8 differdiff --git a/tests/e2e/proofs.py b/tests/e2e/proofs.pyindex 4eaaebc..ad8dba8 100644--- a/tests/e2e/proofs.py+++ b/tests/e2e/proofs.py@@ -1,83 +1,72 @@"""Reason sign-in proofs for the e2e tests: a stand-in for Reason's signing key, trusted through-REASON_NETWORK_TRUST_KEYS. Ed25519 from RFC 8032's reference code, so the tests need nothing installed."""-import base64, hashlib, json, os, time--p = 2**255 - 19-d = -121665 * pow(121666, p - 2, p) % p-q = 2**252 + 27742317777372353535851937790883648493---def _add(P, Q):- A, B = (P[1] - P[0]) * (Q[1] - Q[0]) % p, (P[1] + P[0]) * (Q[1] + Q[0]) % p- C, D = 2 * P[3] * Q[3] * d % p, 2 * P[2] * Q[2] % p- E, F, G, H = B - A, D - C, D + C, B + A- return (E * F, G * H, F * G, E * H)---def _mul(s, P):- Q = (0, 1, 1, 0)- while s > 0:- if s & 1:- Q = _add(Q, P)- P, s = _add(P, P), s >> 1- return Q---def _compress(P):- zinv = pow(P[2], p - 2, p)- x, y = P[0] * zinv % p, P[1] * zinv % p- return int.to_bytes(y | ((x & 1) << 255), 32, "little")---def _base():- y = 4 * pow(5, p - 2, p) % p- x2 = (y * y - 1) * pow(d * y * y + 1, p - 2, p)- x = pow(x2, (p + 3) // 8, p)- if (x * x - x2) % p:- x = x * pow(2, (p - 1) // 4, p) % p- if x & 1:- x = p - x- return (x, y, 1, x * y % p)---G = _base()---def _expand(seed):- h = hashlib.sha512(seed).digest()- a = int.from_bytes(h[:32], "little")- a &= (1 << 254) - 8- a |= 1 << 254- return a, h[32:]---def public(seed):- return _compress(_mul(_expand(seed)[0], G))---def sign(seed, msg):- a, prefix = _expand(seed)- A = _compress(_mul(a, G))- r = int.from_bytes(hashlib.sha512(prefix + msg).digest(), "little") % q- R = _compress(_mul(r, G))- h = int.from_bytes(hashlib.sha512(R + A + msg).digest(), "little") % q- return R + int.to_bytes((r + h * a) % q, 32, "little")+REASON_NETWORK_TRUST_KEYS (debug builds). RS256 (RSASSA-PKCS1-v1_5 with SHA-256) in plain Python, so the tests need+nothing installed: keys are made fresh for each run."""+import base64, hashlib, json, secrets, time++# DER of the DigestInfo for SHA-256, which PKCS#1 v1.5 puts before the hash (RFC 8017, 9.2).+SHA256_INFO = bytes.fromhex("3031300d060960864801650304020105000420")+++def _prime(bits):+ while True:+ n = secrets.randbits(bits) | (1 << (bits - 1)) | (1 << (bits - 2)) | 1+ if all(n % p for p in (3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37)) and _probably_prime(n):+ return n+++def _probably_prime(n, rounds=40):+ d, r = n - 1, 0+ while d % 2 == 0:+ d, r = d // 2, r + 1+ for _ in range(rounds):+ x = pow(secrets.randbelow(n - 3) + 2, d, n)+ if x in (1, n - 1):+ continue+ for _ in range(r - 1):+ x = pow(x, 2, n)+ if x == n - 1:+ break+ else:+ return False+ return True+++def keygen(bits=2048):+ """An RSA key: (n, e, d)."""+ e = 65537+ while True:+ p, q = _prime(bits // 2), _prime(bits // 2)+ phi = (p - 1) * (q - 1)+ if p != q and phi % e and (p * q).bit_length() == bits:+ return p * q, e, pow(e, -1, phi)+++def sign(key, msg):+ n, _, d = key+ k = (n.bit_length() + 7) // 8+ t = SHA256_INFO + hashlib.sha256(msg).digest()+ em = b"\x00\x01" + b"\xff" * (k - len(t) - 3) + b"\x00" + t+ return pow(int.from_bytes(em, "big"), d, n).to_bytes(k, "big")def b64(b):return base64.urlsafe_b64encode(b).rstrip(b"=").decode()-REASON = os.urandom(32) # stands in for Reason's signing key+def _int(i):+ return b64(i.to_bytes((i.bit_length() + 7) // 8, "big"))+++REASON = keygen() # stands in for Reason's signing keyKID = "e2e-1"-TRUST = json.dumps({"keys": [{"kty": "OKP", "crv": "Ed25519", "kid": KID, "x": b64(public(REASON))}]})+TRUST = json.dumps({"keys": [{"kty": "RSA", "kid": KID, "alg": "RS256", "use": "sig", "n": _int(REASON[0]), "e": _int(REASON[1])}]})def proof(sub, name, endpoint, key=None, **claims):- """A proof that `endpoint` belongs to account `sub`, called `name`; signed with `key` it's a forgery."""+ """A proof that `endpoint` belongs to account `sub`, called `name`; signed with another `key` it's a forgery."""now = int(time.time())- body = {"iss": "https://reasonmachines.com", "aud": "reason-network", "sub": sub, "name": name,+ body = {"iss": "https://reasonmachines.com/network", "aud": "reason-network", "sub": sub, "name": name,"email": f"{name}@example.com", "endpoint": endpoint, "iat": now, "exp": now + 90 * 86400, **claims}- head = {"alg": "EdDSA", "kid": KID, "typ": "reason-network-proof"}+ head = {"alg": "RS256", "kid": KID, "typ": "reason-network-proof"}signing = f"{b64(json.dumps(head).encode())}.{b64(json.dumps(body).encode())}"return f"{signing}.{b64(sign(key or REASON, signing.encode()))}"diff --git a/tests/e2e/two_machines.py b/tests/e2e/two_machines.pyindex 65544db..626113f 100644--- a/tests/e2e/two_machines.py+++ b/tests/e2e/two_machines.py@@ -7,7 +7,7 @@ test messages into that real session (they say "ignore this")."""import base64, json, os, re, subprocess, sys, tempfile, timesys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))-from proofs import TRUST, proof+from proofs import TRUST, keygen, proofROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))BIN = os.path.join(ROOT, "target", "debug", "reason-network")@@ -174,7 +174,7 @@ out, both = run(mal, "join", link.group(1), "--proof", proof("u_mallory", "alex"check("a name verified by another account is taken: name_taken", as_json(out) == {"error": "name_taken"}, both)out, both = run(mal, "join", link.group(1), "--as", "alice", "--no-setup", "--json")check("…and without a proof too", as_json(out) == {"error": "name_taken"}, both)-_, out = run(mal, "join", link.group(1), "--proof", proof("u_mallory", "mallory", mal_ep, key=os.urandom(32)), "--no-setup")+_, out = run(mal, "join", link.group(1), "--proof", proof("u_mallory", "mallory", mal_ep, key=keygen()), "--no-setup")check("a forged proof is refused", "signature doesn't verify" in out and "Joined" not in out, out)_, out = run(mal, "join", link.group(1), "--proof", proof("u_alex", "alex", ep["alex"]), "--no-setup")check("someone else's proof is refused", "for another machine" in out and "Joined" not in out, out)