Skip to main content

gent_daemon/messages/
wire.rs

1//! Versioned encrypted records. Each codec maps into the same verified model.
2//! Signed checkpoints, request fingerprints and user content are never renamed.
3use super::{Event, Record};
4use gent_crypto::Checkpoint;
5use serde::{Deserialize, Deserializer, Serialize, Serializer, de, ser};
6use serde_json::Value;
7mod compact;
8mod value;
9
10pub const ZSTD_VERSION: u8 = 6;
11pub const HELPERS_VERSION: u8 = 7;
12pub const ADMIN_VERSION: u8 = 8;
13pub const DASHBOARD_VERSION: u8 = 9;
14pub const NODE_RENAME_VERSION: u8 = 10;
15pub const MESSAGE_DATES_VERSION: u8 = 11;
16pub const PUBLICATION_VERSION: u8 = 12;
17pub const CHAT_RENAME_VERSION: u8 = 13;
18// Capability 13 advertises a separate QUIC ALPN. Ordered record versions
19// remain unchanged in both directions, including after either peer rolls back.
20pub const CURRENT: u8 = PUBLICATION_VERSION;
21pub const CURRENT_CAPABILITY: u8 = CHAT_RENAME_VERSION;
22pub const NEGOTIATED: &[u8] = &[
23    2,
24    3,
25    4,
26    5,
27    ZSTD_VERSION,
28    HELPERS_VERSION,
29    ADMIN_VERSION,
30    DASHBOARD_VERSION,
31    NODE_RENAME_VERSION,
32    MESSAGE_DATES_VERSION,
33    PUBLICATION_VERSION,
34    CHAT_RENAME_VERSION,
35];
36
37/// Older peers cannot decode new configuration edits on their ordered streams.
38pub(crate) fn configuration_version(edit: &gent_protocol::ConfigurationEdit) -> u8 {
39    match edit {
40        gent_protocol::ConfigurationEdit::SetPermissionRule { .. } => ADMIN_VERSION,
41        gent_protocol::ConfigurationEdit::RenameMember { .. } => NODE_RENAME_VERSION,
42        _ => 1,
43    }
44}
45
46fn check_activity_version(event: &Event, version: u8) -> Result<(), &'static str> {
47    if let Event::ConversationActivity {
48        timestamp,
49        message_dates,
50        ..
51    } = event
52        && version < MESSAGE_DATES_VERSION
53        && (message_dates.is_some() || timestamp.is_none())
54    {
55        return Err("message dates require protocol 11");
56    }
57    Ok(())
58}
59
60fn check_dashboard_version(event: &Event, version: u8) -> Result<(), &'static str> {
61    if let Event::Dashboard { board, html, .. } = event {
62        if html.is_some() && version < PUBLICATION_VERSION {
63            return Err("published HTML requires protocol 12");
64        }
65        if version < DASHBOARD_VERSION {
66            return Err("dashboard requires protocol 9");
67        }
68        if let Some(board) = board {
69            super::dashboard::check_encoding(board)?;
70        }
71    }
72    Ok(())
73}
74
75fn check_configuration_version(event: &Event, version: u8) -> Result<(), String> {
76    if let Event::ConfigurationRequest { edit, .. } = event {
77        let required = configuration_version(edit);
78        if version < required {
79            return Err(format!(
80                "the configuration writer must negotiate Gent protocol {required} before this administration request"
81            ));
82        }
83    }
84    Ok(())
85}
86
87#[derive(Serialize, Deserialize)]
88#[serde(deny_unknown_fields)]
89struct Envelope {
90    version: u8,
91    authority: Checkpoint,
92    #[serde(default, skip_serializing_if = "Option::is_none")]
93    directory: Option<Value>,
94    #[serde(deserialize_with = "value::deserialize")]
95    event: Value,
96}
97
98fn rename(value: &mut Value, from: &str, to: &str) -> Result<(), String> {
99    let map = value.as_object_mut().ok_or("expected wire object")?;
100    if map.contains_key(to) {
101        return Err("conflicting wire fields".into());
102    }
103    let old = map
104        .remove(from)
105        .ok_or_else(|| format!("missing wire field {from}"))?;
106    map.insert(to.into(), old);
107    Ok(())
108}
109
110fn registration(value: &mut Value, encode: bool) -> Result<(), String> {
111    for (old, new) in [("id", "chat_id"), ("node", "node_id")] {
112        let (from, to) = if encode { (old, new) } else { (new, old) };
113        rename(value, from, to)?;
114    }
115    Ok(())
116}
117
118fn v2(event: &mut Value, encode: bool) -> Result<(), String> {
119    match event["kind"].as_str().ok_or("missing event kind")? {
120        "registration" | "conversation_activity" => {
121            let (from, to) = if encode {
122                ("agent", "chat")
123            } else {
124                ("chat", "agent")
125            };
126            rename(event, from, to)?;
127            registration(&mut event[to], encode)?;
128        }
129        "message" => {
130            let (from, to) = if encode {
131                ("sender", "sender_chat")
132            } else {
133                ("sender_chat", "sender")
134            };
135            rename(event, from, to)?;
136            registration(&mut event[to], encode)?;
137            for (old, new) in [
138                ("sender", "sender_chat_id"),
139                ("recipient", "recipient_chat_id"),
140            ] {
141                let (from, to) = if encode { (old, new) } else { (new, old) };
142                rename(&mut event["message"], from, to)?;
143            }
144        }
145        "directory" => {
146            if let Some(chats) = event
147                .get_mut("envelope")
148                .and_then(|e| e.get_mut("chats"))
149                .and_then(Value::as_array_mut)
150            {
151                for chat in chats {
152                    registration(chat, encode)?;
153                }
154            }
155            if let Some(chats) = event
156                .get_mut("envelope")
157                .and_then(|e| e.get_mut("result"))
158                .and_then(|r| r.get_mut("chats"))
159                .and_then(Value::as_array_mut)
160            {
161                for chat in chats {
162                    registration(chat, encode)?;
163                }
164            }
165        }
166        _ => {}
167    }
168    Ok(())
169}
170
171impl Serialize for Record {
172    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
173        let mut event = serde_json::to_value(&self.event).map_err(ser::Error::custom)?;
174        check_activity_version(&self.event, self.version).map_err(ser::Error::custom)?;
175        check_dashboard_version(&self.event, self.version).map_err(ser::Error::custom)?;
176        check_configuration_version(&self.event, self.version).map_err(ser::Error::custom)?;
177        if self.version < ADMIN_VERSION && matches!(self.event, Event::UnregisterChat { .. }) {
178            return Err(ser::Error::custom(
179                "the target node must negotiate Gent protocol 8 before this administration request",
180            ));
181        }
182        if self.version < 5 && matches!(self.event, Event::Direct { .. }) {
183            return Err(ser::Error::custom(
184                "direct transport requires node record version 5",
185            ));
186        }
187        if self.version < HELPERS_VERSION && matches!(self.event, Event::Direct { .. }) {
188            let address = event["address"]
189                .as_object_mut()
190                .ok_or_else(|| ser::Error::custom("invalid direct address"))?;
191            address.remove("offer");
192            address.remove("registrations");
193        }
194        if self.version < 4 && (self.directory.is_some() || event["envelope"]["step"] == "push") {
195            return Err(ser::Error::custom(
196                "directory push requires node record version 4",
197            ));
198        }
199        if self.version < 3 && matches!(self.event, Event::Directory { .. }) {
200            return Err(ser::Error::custom(
201                "directory reconciliation requires node record version 3",
202            ));
203        }
204        match self.version {
205            1 => {}
206            2..=CURRENT => v2(&mut event, true).map_err(ser::Error::custom)?,
207            _ => return Err(ser::Error::custom("unsupported node record version")),
208        }
209        Envelope {
210            version: self.version,
211            authority: self.authority.clone(),
212            directory: self
213                .directory
214                .as_ref()
215                .map(|snapshot| compact::encode(snapshot, self.version))
216                .transpose()
217                .map_err(ser::Error::custom)?,
218            event,
219        }
220        .serialize(serializer)
221    }
222}
223
224impl<'de> Deserialize<'de> for Record {
225    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
226        let mut envelope = Envelope::deserialize(deserializer)?;
227        if envelope.version < ADMIN_VERSION && envelope.event["kind"] == "unregister_chat" {
228            return Err(de::Error::custom(
229                "remote administration requires Gent protocol 8",
230            ));
231        }
232        if envelope.version < 5 && envelope.event["kind"] == "direct" {
233            return Err(de::Error::custom(
234                "direct transport requires node record version 5",
235            ));
236        }
237        if envelope.version < HELPERS_VERSION
238            && envelope.event["kind"] == "direct"
239            && ["offer", "registrations"]
240                .iter()
241                .any(|key| envelope.event["address"].get(key).is_some())
242        {
243            return Err(de::Error::custom(
244                "helper advertisements require node record version 7",
245            ));
246        }
247        if envelope.version < 4
248            && (envelope.directory.is_some() || envelope.event["envelope"]["step"] == "push")
249        {
250            return Err(de::Error::custom(
251                "directory push requires node record version 4",
252            ));
253        }
254        if envelope.version < 3 && envelope.event["kind"] == "directory" {
255            return Err(de::Error::custom(
256                "directory reconciliation requires node record version 3",
257            ));
258        }
259        match envelope.version {
260            1 => {}
261            2..=CURRENT => v2(&mut envelope.event, false).map_err(de::Error::custom)?,
262            _ => return Err(de::Error::custom("unsupported node record version")),
263        }
264        let event: Event = serde_json::from_value(envelope.event).map_err(de::Error::custom)?;
265        check_activity_version(&event, envelope.version).map_err(de::Error::custom)?;
266        check_dashboard_version(&event, envelope.version).map_err(de::Error::custom)?;
267        check_configuration_version(&event, envelope.version).map_err(de::Error::custom)?;
268        Ok(Self {
269            version: envelope.version,
270            authority: envelope.authority,
271            directory: envelope
272                .directory
273                .map(|value| compact::decode(value, envelope.version))
274                .transpose()
275                .map_err(de::Error::custom)?,
276            event,
277        })
278    }
279}
280
281#[cfg(test)]
282mod tests {
283    use super::*;
284    use serde_json::json;
285
286    #[test]
287    fn message_dates_require_a_compatible_peer_and_legacy_activity_still_round_trips() {
288        let mut value = json!({"version":MESSAGE_DATES_VERSION,"authority":{"revision":1,"state_hash":vec![0;32]},
289            "event":{"kind":"conversation_activity","chat":{"chat_id":"c","node_id":"n","nonce":null,"legacy":null,
290            "generation":1,"name":"reader","provider":"test","revoked":false},"timestamp":null,
291            "message_dates":{"has_gent_messages":true,"last_gent_message_at":123}}});
292        let mut record: Record = serde_json::from_value(value.clone()).unwrap();
293        assert_eq!(serde_json::to_value(&record).unwrap(), value);
294        value["version"] = json!(NODE_RENAME_VERSION);
295        record.version = NODE_RENAME_VERSION;
296        assert!(serde_json::to_value(&record).is_err());
297        assert!(serde_json::from_value::<Record>(value.clone()).is_err());
298        value["event"]
299            .as_object_mut()
300            .unwrap()
301            .remove("message_dates");
302        value["event"]["timestamp"] = 123.into();
303        let legacy: Record = serde_json::from_value(value.clone()).unwrap();
304        assert_eq!(serde_json::to_value(legacy).unwrap(), value);
305    }
306
307    #[test]
308    fn targeted_rename_requires_a_compatible_writer_on_the_ordered_stream() {
309        let mut value = json!({"version":NODE_RENAME_VERSION,
310            "authority":{"revision":1,"state_hash":vec![0;32]},
311            "event":{"kind":"configuration_request","request_id":uuid::Uuid::new_v4(),
312                "edit":{"op":"rename_member","node_id":uuid::Uuid::new_v4(),"name":"Studio"}}});
313        let mut record: Record = serde_json::from_value(value.clone()).unwrap();
314        assert_eq!(serde_json::to_value(&record).unwrap(), value);
315        record.version = NODE_RENAME_VERSION - 1;
316        value["version"] = json!(record.version);
317        assert!(serde_json::to_value(&record).is_err());
318        assert!(serde_json::from_value::<Record>(value).is_err());
319    }
320
321    #[test]
322    fn helper_fields_are_negotiated_without_changing_legacy_direct_addresses() {
323        let address = json!({"endpoint":iroh::EndpointAddr::new(iroh::SecretKey::generate().public()),"expires_at":1234});
324        let mut latest = json!({"version":7,"authority":{"revision":1,"state_hash":vec![0;32]},
325            "event":{"kind":"direct","address":address}});
326        let service = uuid::Uuid::new_v4().to_string();
327        latest["event"]["address"]["offer"] = json!({"helper_node":service,"urls":["https://127.0.0.1:9443/"],
328            "cert_der":"AQ==","generation":vec![1;32],"qad_port":9443});
329        latest["event"]["address"]["registrations"] = json!([{"helper_node":service,"url":"https://127.0.0.1:9443/",
330            "generation":vec![1;32],"rtt_ms":2}]);
331        let mut record: Record = serde_json::from_value(latest.clone()).unwrap();
332        assert_eq!(serde_json::to_value(&record).unwrap(), latest);
333        for version in 1..=6 {
334            let mut extended = latest.clone();
335            extended["version"] = json!(version);
336            assert!(serde_json::from_value::<Record>(extended).is_err());
337            record.version = version;
338            if version < 5 {
339                assert!(serde_json::to_value(&record).is_err());
340            } else {
341                let legacy = serde_json::to_value(&record).unwrap();
342                assert_eq!(legacy["event"]["address"], address);
343                let decoded: Record = serde_json::from_value(legacy.clone()).unwrap();
344                assert_eq!(serde_json::to_value(decoded).unwrap(), legacy);
345            }
346        }
347    }
348
349    #[test]
350    fn snapshots_and_pushes_require_v4_and_round_trip_chat_fields() {
351        let value = json!({"version":4,"authority":{"revision":1,"state_hash":vec![0;32]},
352            "directory":{"sequence":1,"root":{"hash":vec![0;32],"count":0},"frontier":[{"prefix":"","summary":{"hash":vec![0;32],"count":0}}]},
353            "event":{"kind":"directory","envelope":{"step":"push","chats":[{
354                "chat_id":"chat","node_id":"node","nonce":null,"legacy":null,"generation":1,
355                "name":"coordinator","provider":"test","revoked":false}]}}});
356        let mut record: Record = serde_json::from_value(value.clone()).unwrap();
357        assert_eq!(serde_json::to_value(&record).unwrap(), value);
358        for version in 1..4 {
359            record.version = version;
360            assert!(serde_json::to_vec(&record).is_err());
361            let mut old = value.clone();
362            old["version"] = json!(version);
363            assert!(serde_json::from_value::<Record>(old).is_err());
364        }
365    }
366
367    #[test]
368    fn directory_records_require_v3_and_preserve_probe_and_chat_shapes() {
369        let probe = json!({"version":3,"authority":{"revision":1,"state_hash":vec![0;32]},"event":{
370            "kind":"directory","envelope":{"step":"probe","round":"00000000-0000-4000-8000-000000000001",
371            "prefix":"","root":null,"summary":{"hash":vec![0;32],"count":0}}}});
372        let leaves = json!({"version":3,"authority":{"revision":1,"state_hash":vec![0;32]},"event":{
373            "kind":"directory","envelope":{"step":"reply","round":"00000000-0000-4000-8000-000000000001",
374            "prefix":"","root":{"hash":vec![0;32],"count":1},"result":{"kind":"leaves","chats":[{
375                "chat_id":"chat","node_id":"node","nonce":null,"legacy":null,"generation":1,
376                "name":"coordinator","provider":"test","revoked":false}]}}}});
377        for value in [probe, leaves] {
378            let mut record: Record = serde_json::from_value(value.clone()).unwrap();
379            assert_eq!(serde_json::to_value(&record).unwrap(), value);
380            for version in [1, 2] {
381                record.version = version;
382                assert!(serde_json::to_value(&record).is_err());
383                let mut old = value.clone();
384                old["version"] = json!(version);
385                assert!(serde_json::from_value::<Record>(old).is_err());
386            }
387        }
388    }
389
390    #[test]
391    fn codecs_are_explicit_and_reject_unknown_or_mixed_shapes() {
392        let legacy = json!({"version":1,"authority":{"revision":1,"state_hash":vec![0;32]},"event":{
393            "kind":"registration","agent":{"id":"chat","node":"node","nonce":null,
394            "legacy":null,"generation":1,"name":"an agent named agent","provider":"agent provider","revoked":false}}});
395        let mut record: Record = serde_json::from_value(legacy.clone()).unwrap();
396        assert_eq!(serde_json::to_value(&record).unwrap(), legacy);
397        record.version = CURRENT;
398        let current = serde_json::to_value(&record).unwrap();
399        assert_eq!(current["event"]["chat"]["chat_id"], "chat");
400        assert_eq!(current["event"]["chat"]["node_id"], "node");
401        assert!(current["event"].get("agent").is_none());
402        let mut decoded: Record = serde_json::from_value(current.clone()).unwrap();
403        decoded.version = 1;
404        assert_eq!(serde_json::to_value(decoded).unwrap(), legacy);
405        for version in [0, CURRENT + 1, 255] {
406            let mut unsupported = current.clone();
407            unsupported["version"] = json!(version);
408            assert!(serde_json::from_value::<Record>(unsupported).is_err());
409        }
410        let mut mixed = current;
411        mixed["event"]["agent"] = legacy["event"]["agent"].clone();
412        assert!(serde_json::from_value::<Record>(mixed).is_err());
413        let mut mislabeled = legacy;
414        mislabeled["version"] = json!(2);
415        assert!(serde_json::from_value::<Record>(mislabeled).is_err());
416        for version in 1..=CURRENT {
417            let input = format!(
418                r#"{{"version":{version},"authority":{{"revision":1,"state_hash":{}}},"event":{{"kind":"presence","reply":true,"reply":false,"challenge":"00000000-0000-4000-8000-000000000001"}}}}"#,
419                json!(vec![0; 32])
420            );
421            assert!(serde_json::from_str::<Record>(&input).is_err());
422        }
423    }
424}