Skip to main content

wire/
signing.rs

1//! Ed25519 sign-over-event_id (Nostr NIP-01 style).
2//!
3//! Sign flow:
4//!   1. Compute SHA-256 over canonical bytes of `msg` (strict: drops event_id).
5//!   2. That 32-byte digest IS the `event_id` (hex-encoded for transport).
6//!   3. Sign the raw 32-byte digest. The signature commits to event_id, which
7//!      transitively commits to the canonical body — tamper anything, the
8//!      digest changes, the signature fails.
9//!
10//! Why sign the id and not the body: lets relays/index layers cite events by
11//! id without re-canonicalizing every body. Same property Nostr exploits.
12
13use base64::Engine as _;
14use base64::engine::general_purpose::STANDARD as B64;
15use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey};
16use rand::rngs::OsRng;
17use serde_json::Value;
18use sha2::{Digest, Sha256};
19use std::collections::BTreeMap;
20use std::ops::Range;
21use thiserror::Error;
22
23use crate::canonical::canonical;
24
25// ---------- event schema version ----------
26
27/// Schema version tag stamped on every signed event by 0.5.11+. Pull-side
28/// verification rejects events whose schema_version's *major* component
29/// disagrees with this — see `pull::process_events`.
30///
31/// Legacy events without this field are accepted (we can't retroactively
32/// stamp 0.5.10 traffic), so the field's *absence* is fine; only its
33/// *presence with a wrong major* is a hard reject.
34pub const EVENT_SCHEMA_VERSION: &str = "v3.1";
35
36/// Major component of a `v<major>.<minor>` schema_version. Used to decide
37/// whether a received event is wire-compatible.
38///
39/// Today: every Wire schema is v3.x; major == "v3". A 0.5.12 binary might
40/// start emitting v4.0 events; older 0.5.x binaries see major=v4 and bail
41/// instead of attempting to decode an incompatible shape.
42pub fn schema_major(schema_version: &str) -> &str {
43    schema_version.split('.').next().unwrap_or(schema_version)
44}
45
46// ---------- kind ranges ----------
47
48/// Disjoint kind-id ranges. Mirrors v3 protocol; v0.1 ships a strict subset.
49///
50/// v0.2+ kinds (file_share=1900, file_revoke=1901, registry_revocation=10500)
51/// are deliberately ABSENT — see ANTI_FEATURES.md.
52pub static KIND_RANGES: &[(KindClass, Range<u32>)] = &[
53    (KindClass::Regular, 1000..10000),
54    (KindClass::Replaceable, 10000..20000),
55    (KindClass::Ephemeral, 20000..30000),
56    (KindClass::Addressable, 30000..40000),
57];
58
59/// v0.1 named kinds. Anything not here is unknown to this version.
60pub fn kinds() -> &'static [(u32, &'static str)] {
61    &[
62        (1, "decision"),    // Nostr-compat short text — special-cased to Regular
63        (100, "heartbeat"), // ephemeral liveness ping — special-cased to Ephemeral
64        (1000, "decision"),
65        (1001, "claim"),
66        (1002, "ack"),
67        (1100, "agent_card"),
68        (1101, "trust_add_key"),
69        (1102, "trust_revoke_key"),
70        (1200, "wire_open"),
71        (1201, "wire_close"),
72    ]
73}
74
75/// `kinds()` as a `BTreeMap` for membership tests. Allocated per call —
76/// callers that need it hot should cache.
77pub fn kinds_map() -> BTreeMap<u32, &'static str> {
78    kinds().iter().copied().collect()
79}
80
81#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
82pub enum KindClass {
83    Regular,
84    Replaceable,
85    Ephemeral,
86    Addressable,
87}
88
89impl KindClass {
90    pub fn as_str(self) -> &'static str {
91        match self {
92            KindClass::Regular => "regular",
93            KindClass::Replaceable => "replaceable",
94            KindClass::Ephemeral => "ephemeral",
95            KindClass::Addressable => "addressable",
96        }
97    }
98}
99
100/// Classify a kind id. `None` means unknown — caller decides how to handle.
101pub fn kind_class(kind: u32) -> Option<KindClass> {
102    // Documented out-of-range special cases (Nostr NIP-01 compatibility +
103    // v3 heartbeat carve-out). Keep these explicit, not a hidden lookup.
104    match kind {
105        1 => return Some(KindClass::Regular),
106        100 => return Some(KindClass::Ephemeral),
107        _ => {}
108    }
109    for (cls, range) in KIND_RANGES {
110        if range.contains(&kind) {
111            return Some(*cls);
112        }
113    }
114    None
115}
116
117// ---------- canonical re-export (keeps call sites symmetric with Python) ----------
118
119pub fn canonical_event(value: &Value, strict: bool) -> Vec<u8> {
120    canonical(value, strict)
121}
122
123// Public alias matching Python `signing.canonical(...)` import path.
124pub use crate::canonical::canonical as canonical_value;
125
126// ---------- event_id ----------
127
128pub fn compute_event_id(msg: &Value) -> String {
129    let bytes = canonical(msg, true);
130    let digest = Sha256::digest(&bytes);
131    hex::encode(digest)
132}
133
134// ---------- key id + fingerprint ----------
135
136pub fn fingerprint(public_key: &[u8]) -> String {
137    let digest = Sha256::digest(public_key);
138    hex::encode(&digest[..4])
139}
140
141pub fn make_key_id(handle: &str, public_key: &[u8]) -> String {
142    format!("{handle}:{}", fingerprint(public_key))
143}
144
145// ---------- base64 helpers ----------
146
147pub fn b64encode(bytes: &[u8]) -> String {
148    B64.encode(bytes)
149}
150
151pub fn b64decode(s: &str) -> Result<Vec<u8>, base64::DecodeError> {
152    B64.decode(s)
153}
154
155// ---------- key generation ----------
156
157/// Returns `(private_key_bytes, public_key_bytes)` — both 32 bytes, raw.
158pub fn generate_keypair() -> ([u8; 32], [u8; 32]) {
159    let sk = SigningKey::generate(&mut OsRng);
160    let pk = sk.verifying_key();
161    (sk.to_bytes(), pk.to_bytes())
162}
163
164// ---------- sign / verify ----------
165
166#[derive(Debug, Error)]
167pub enum SignError {
168    #[error("private key must be 32 bytes, got {0}")]
169    BadPrivateLen(usize),
170    #[error("public key must be 32 bytes, got {0}")]
171    BadPublicLen(usize),
172}
173
174#[derive(Debug, Error)]
175pub enum VerifyError {
176    #[error("missing field: {0}")]
177    MissingField(&'static str),
178    #[error("event_id mismatch — body was tampered after signing")]
179    EventIdMismatch,
180    #[error("signer {0:?} not in trust")]
181    UnknownAgent(String),
182    #[error("key {0:?} not found for agent {1:?}")]
183    UnknownKey(String, String),
184    #[error("key {0:?} for agent {1:?} is deactivated")]
185    DeactivatedKey(String, String),
186    #[error("signature decode failed")]
187    BadSignature,
188    #[error("signature did not verify")]
189    SignatureRejected,
190}
191
192/// Sign a message. Returns the canonical wire form: original fields + the
193/// computed `event_id`, `public_key_id`, `signature`.
194pub fn sign_message_v31(
195    msg: &Value,
196    private_key: &[u8],
197    public_key: &[u8],
198    agent: &str,
199) -> Result<Value, SignError> {
200    if private_key.len() != 32 {
201        return Err(SignError::BadPrivateLen(private_key.len()));
202    }
203    if public_key.len() != 32 {
204        return Err(SignError::BadPublicLen(public_key.len()));
205    }
206    let mut sk_bytes = [0u8; 32];
207    sk_bytes.copy_from_slice(private_key);
208    let sk = SigningKey::from_bytes(&sk_bytes);
209
210    let event_id = compute_event_id(msg);
211    let raw = hex::decode(&event_id).expect("compute_event_id always returns valid hex");
212    let sig = sk.sign(&raw);
213
214    let mut out = msg.as_object().cloned().unwrap_or_default();
215    out.insert("event_id".into(), Value::String(event_id));
216    out.insert(
217        "public_key_id".into(),
218        Value::String(make_key_id(agent, public_key)),
219    );
220    out.insert(
221        "signature".into(),
222        Value::String(b64encode(&sig.to_bytes())),
223    );
224    Ok(Value::Object(out))
225}
226
227/// Verify a signed message against a trust dict (see `trust` module).
228///
229/// Returns `Ok(())` iff: event_id matches recomputed, signer's key is in
230/// trust + active, and the Ed25519 signature validates over the event_id.
231pub fn verify_message_v31(msg: &Value, trust: &Value) -> Result<(), VerifyError> {
232    let from = msg
233        .get("from")
234        .and_then(Value::as_str)
235        .ok_or(VerifyError::MissingField("from"))?;
236    // v0.5.7+: DID may include a `-<8-hex>` pubkey suffix
237    // (`did:wire:paul-abc12345`). Trust map is keyed by the bare handle,
238    // so strip both the `did:wire:` prefix AND the optional pubkey suffix.
239    let handle = crate::agent_card::display_handle_from_did(from);
240
241    let public_key_id = msg
242        .get("public_key_id")
243        .and_then(Value::as_str)
244        .ok_or(VerifyError::MissingField("public_key_id"))?;
245
246    let signature_b64 = msg
247        .get("signature")
248        .and_then(Value::as_str)
249        .ok_or(VerifyError::MissingField("signature"))?;
250
251    let event_id = msg
252        .get("event_id")
253        .and_then(Value::as_str)
254        .ok_or(VerifyError::MissingField("event_id"))?;
255
256    let recomputed = compute_event_id(msg);
257    if recomputed != event_id {
258        return Err(VerifyError::EventIdMismatch);
259    }
260
261    let agent = trust
262        .get("agents")
263        .and_then(|a| a.get(handle))
264        .ok_or_else(|| VerifyError::UnknownAgent(handle.to_string()))?;
265
266    let public_keys = agent
267        .get("public_keys")
268        .and_then(Value::as_array)
269        .ok_or_else(|| VerifyError::UnknownKey(public_key_id.to_string(), handle.to_string()))?;
270
271    let key_record = public_keys
272        .iter()
273        .find(|k| k.get("key_id").and_then(Value::as_str) == Some(public_key_id))
274        .ok_or_else(|| VerifyError::UnknownKey(public_key_id.to_string(), handle.to_string()))?;
275
276    let active = key_record
277        .get("active")
278        .and_then(Value::as_bool)
279        .unwrap_or(true);
280    if !active {
281        return Err(VerifyError::DeactivatedKey(
282            public_key_id.to_string(),
283            handle.to_string(),
284        ));
285    }
286
287    let pk_b64 = key_record
288        .get("key")
289        .and_then(Value::as_str)
290        .ok_or(VerifyError::MissingField("key"))?;
291    let pk_bytes = b64decode(pk_b64).map_err(|_| VerifyError::BadSignature)?;
292    if pk_bytes.len() != 32 {
293        return Err(VerifyError::BadSignature);
294    }
295    let mut pk_arr = [0u8; 32];
296    pk_arr.copy_from_slice(&pk_bytes);
297    let vk = VerifyingKey::from_bytes(&pk_arr).map_err(|_| VerifyError::BadSignature)?;
298
299    let sig_bytes = b64decode(signature_b64).map_err(|_| VerifyError::BadSignature)?;
300    if sig_bytes.len() != 64 {
301        return Err(VerifyError::BadSignature);
302    }
303    let mut sig_arr = [0u8; 64];
304    sig_arr.copy_from_slice(&sig_bytes);
305    let sig = Signature::from_bytes(&sig_arr);
306
307    let raw = hex::decode(event_id).map_err(|_| VerifyError::BadSignature)?;
308    vk.verify(&raw, &sig)
309        .map_err(|_| VerifyError::SignatureRejected)
310}
311
312#[allow(dead_code)] // kept for v0.6 — once a caller exists, drop the allow.
313fn strip_did_wire(s: &str) -> &str {
314    s.strip_prefix("did:wire:").unwrap_or(s)
315}
316
317#[cfg(test)]
318mod tests {
319    use super::*;
320    use serde_json::json;
321
322    fn trust_for(handle: &str, pub_key: &[u8]) -> Value {
323        let kid = make_key_id(handle, pub_key);
324        json!({
325            "agents": {
326                handle: {
327                    "public_keys": [
328                        {"key_id": kid, "key": b64encode(pub_key), "active": true}
329                    ]
330                }
331            }
332        })
333    }
334
335    #[test]
336    fn kind_ranges_disjoint() {
337        let mut seen = std::collections::HashSet::new();
338        for (_, rng) in KIND_RANGES {
339            for k in rng.clone() {
340                assert!(seen.insert(k), "kind {k} in multiple ranges");
341            }
342        }
343    }
344
345    #[test]
346    fn kind_class_known_ranges() {
347        assert_eq!(kind_class(20000), Some(KindClass::Ephemeral));
348        assert_eq!(kind_class(29999), Some(KindClass::Ephemeral));
349        assert_eq!(kind_class(1000), Some(KindClass::Regular));
350        assert_eq!(kind_class(9999), Some(KindClass::Regular));
351        assert_eq!(kind_class(10000), Some(KindClass::Replaceable));
352        assert_eq!(kind_class(19999), Some(KindClass::Replaceable));
353        assert_eq!(kind_class(30000), Some(KindClass::Addressable));
354    }
355
356    #[test]
357    fn kind_class_special_cases() {
358        assert_eq!(kind_class(1), Some(KindClass::Regular));
359        assert_eq!(kind_class(100), Some(KindClass::Ephemeral));
360    }
361
362    #[test]
363    fn kind_class_unknown_returns_none() {
364        assert_eq!(kind_class(99999), None);
365        assert_eq!(kind_class(7), None);
366    }
367
368    #[test]
369    fn v01_does_not_ship_v02_kinds() {
370        let names = kinds_map();
371        for deferred in [1900, 1901, 10500] {
372            assert!(
373                !names.contains_key(&deferred),
374                "v0.2+ kind {deferred} leaked into v0.1"
375            );
376        }
377    }
378
379    #[test]
380    fn fingerprint_is_8_hex() {
381        let fp = fingerprint(&[0u8; 32]);
382        assert_eq!(fp.len(), 8);
383        u32::from_str_radix(&fp, 16).expect("hex");
384    }
385
386    #[test]
387    fn make_key_id_format() {
388        let (_, pk) = generate_keypair();
389        let kid = make_key_id("paul", &pk);
390        assert!(kid.starts_with("paul:"));
391        assert_eq!(kid.split(':').nth(1).unwrap().len(), 8);
392    }
393
394    #[test]
395    fn generate_keypair_returns_32_byte_pair() {
396        let (sk, pk) = generate_keypair();
397        assert_eq!(sk.len(), 32);
398        assert_eq!(pk.len(), 32);
399    }
400
401    #[test]
402    fn sign_verify_roundtrip() {
403        let (sk, pk) = generate_keypair();
404        let msg = json!({
405            "timestamp": "2026-05-09T00:00:00Z",
406            "from": "paul",
407            "type": "decision",
408            "kind": 1,
409            "subject": "test",
410            "body": {"content": "hello"},
411        });
412        let signed = sign_message_v31(&msg, &sk, &pk, "paul").unwrap();
413        assert!(signed.get("event_id").is_some());
414        assert!(signed.get("public_key_id").is_some());
415        assert!(signed.get("signature").is_some());
416        verify_message_v31(&signed, &trust_for("paul", &pk)).unwrap();
417    }
418
419    #[test]
420    fn verify_rejects_tampered_body() {
421        let (sk, pk) = generate_keypair();
422        let msg = json!({"from": "paul", "type": "decision", "body": {"content": "original"}});
423        let mut signed = sign_message_v31(&msg, &sk, &pk, "paul").unwrap();
424        signed["body"]["content"] = json!("tampered");
425        let err = verify_message_v31(&signed, &trust_for("paul", &pk)).unwrap_err();
426        assert!(matches!(err, VerifyError::EventIdMismatch));
427    }
428
429    #[test]
430    fn verify_accepts_did_wire_prefix_in_from() {
431        let (sk, pk) = generate_keypair();
432        let msg = json!({"from": "did:wire:paul", "type": "decision", "body": {}});
433        let signed = sign_message_v31(&msg, &sk, &pk, "paul").unwrap();
434        verify_message_v31(&signed, &trust_for("paul", &pk)).unwrap();
435    }
436
437    #[test]
438    fn verify_rejects_unknown_agent() {
439        let (sk, pk) = generate_keypair();
440        let msg = json!({"from": "paul", "type": "decision", "body": {}});
441        let signed = sign_message_v31(&msg, &sk, &pk, "paul").unwrap();
442        let trust = json!({"agents": {"willard": {"public_keys": []}}});
443        let err = verify_message_v31(&signed, &trust).unwrap_err();
444        assert!(matches!(err, VerifyError::UnknownAgent(h) if h == "paul"));
445    }
446
447    #[test]
448    fn verify_rejects_inactive_key() {
449        let (sk, pk) = generate_keypair();
450        let msg = json!({"from": "paul", "type": "decision", "body": {}});
451        let signed = sign_message_v31(&msg, &sk, &pk, "paul").unwrap();
452        let mut trust = trust_for("paul", &pk);
453        trust["agents"]["paul"]["public_keys"][0]["active"] = json!(false);
454        let err = verify_message_v31(&signed, &trust).unwrap_err();
455        assert!(matches!(err, VerifyError::DeactivatedKey(_, _)));
456    }
457
458    #[test]
459    fn compute_event_id_is_64_hex() {
460        let v = json!({"from": "paul", "type": "test"});
461        let eid = compute_event_id(&v);
462        assert_eq!(eid.len(), 64);
463        for c in eid.chars() {
464            assert!(c.is_ascii_hexdigit());
465        }
466    }
467}