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