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