Skip to main content

agentmux_srv_core/backend/lan/discovery/
udp_peers.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Desktop-to-desktop discovery that does not depend on mDNS
5//! (`docs/specs/SPEC_LAN_FIREWALL_SETUP_2026_10_01.md` §4.7 item 5,
6//! `docs/specs/SPEC_LAN_UDP_PEER_DISCOVERY_2026_10_02.md`).
7//!
8//! mDNS can fail for reasons nothing on our side can fix: another program holds
9//! UDP 5353 (Area54, 2026-10-01: Chrome, then the DNS Client service), a guest
10//! network filters multicast, an interface never gets a socket. The UDP probe
11//! responder on 47891 only ever served mobile clients, so two desktops had one
12//! route to each other and no second.
13//!
14//! Each instance binds one UDP port ([`DESKTOP_DISCOVERY_PORT`]) while LAN is on
15//! and, from that same socket:
16//!
17//! * sends the existing probe to the limited broadcast address and to each
18//!   interface's directed broadcast every [`PROBE_INTERVAL`];
19//! * answers a probe from a private-range source with the identity payload the
20//!   47891 responder sends (`probe_response_json`), without its `siblings`;
21//! * reads identity payloads that come back and records the sender as a peer.
22//!
23//! Probing and answering share one socket on purpose: a peer's reply goes to the
24//! probe's source port, so it lands on a port the firewall rule names rather than
25//! on an ephemeral one.
26//!
27//! **Trust is the same as mDNS.** A reply is network-claimed and unauthenticated,
28//! exactly like a TXT record; what it gains an attacker is a place in the peer
29//! table, not an identity. Jekt signing and LAN key pinning are untouched. The
30//! limits below (private-range source, field sizes, port floor, a peer cap) are
31//! the same defence in depth the mDNS path has.
32//!
33//! Like the 47891 responder this socket does not set `SO_REUSEADDR`, so only the
34//! first instance on a host holds it. A second instance (a `task dev` build next
35//! to an installed one) quietly does without; hosts with one install are the
36//! case this exists for.
37
38use super::*;
39
40/// UDP port for desktop-to-desktop discovery. Inside the fixed block
41/// (`ports::LAN_PORT_RANGE`, below every OS's ephemeral range) so one
42/// firewall rule can name it. UDP and TCP port numbers are separate, so sharing
43/// a number with a TCP listener in the block is harmless.
44pub(crate) const DESKTOP_DISCOVERY_PORT: u16 = 29700;
45
46/// How often each instance probes.
47pub(super) const PROBE_INTERVAL: std::time::Duration = std::time::Duration::from_secs(30);
48///
49/// How long a UDP-learned peer stays listed after its last reply. This is the
50/// staleness floor every peer gets (`peer_staleness_window_secs` clamps a
51/// smaller `other_ttl_secs` up to it), so it is the real lifetime, not a hint:
52/// ten missed probes. A departed peer therefore lingers five minutes, which is
53/// still far shorter than an mDNS peer's TTL.
54const UDP_PEER_TTL_SECS: u32 = LAN_PEER_STALE_TIMEOUT_FLOOR_SECS as u32;
55
56/// Key prefix of a peer learned over UDP in `LanDiscovery::instances` (mDNS
57/// peers are keyed by their service name).
58const UDP_KEY_PREFIX: &str = "udp:";
59
60/// Peers learned over UDP at once. An unauthenticated broadcast must not be able
61/// to grow the table without bound; a real LAN has a handful of machines.
62const MAX_UDP_PEERS: usize = 64;
63
64const MAX_ID_LEN: usize = 128;
65const MAX_HOSTNAME_LEN: usize = 253;
66const MAX_VERSION_LEN: usize = 64;
67const MAX_CHANNEL_LEN: usize = 64;
68const MAX_AUTH_KEY_LEN: usize = 256;
69/// Below this a port is privileged or a well-known service, never one of ours.
70const MIN_PEER_PORT: u16 = 1024;
71
72/// The identity a peer's reply claims, after validation.
73#[derive(Debug, Clone, PartialEq, Eq)]
74pub(super) struct UdpPeer {
75    pub instance_id: String,
76    pub hostname: String,
77    pub version: String,
78    /// Empty when the peer predates advertising it.
79    pub channel: String,
80    /// The peer's operating system, only if it is a plain lowercase token.
81    /// Empty when the peer predates advertising it.
82    pub os: String,
83    /// How the peer is installed, as for `LanInstance::install`; empty when it predates advertising it.
84    pub install: String,
85    /// The kind of build the peer says it is (`release`, `local`, `dev`); empty for anything else.
86    pub build: String,
87    /// The peer's advertised WAN instance id, a well-formed one only; empty when it predates advertising it.
88    pub install_id: String,
89    pub address: IpAddr,
90    pub port: u16,
91    pub auth_key: String,
92}
93
94/// Validate a datagram as a peer's identity reply from `src`. `None` for noise,
95/// a probe, another protocol version, a source outside the private ranges, or
96/// any field that is missing, empty or implausibly large.
97pub(super) fn parse_peer_reply(bytes: &[u8], src: &std::net::SocketAddr) -> Option<UdpPeer> {
98    let value: serde_json::Value = serde_json::from_slice(bytes).ok()?;
99    if value.get("type").and_then(|t| t.as_str()) != Some(UDP_RESPONSE_TYPE)
100        || !is_probe_version_match(&value)
101    {
102        return None;
103    }
104    if !is_lan_source(src) {
105        return None;
106    }
107    let text = |key: &str, max: usize| -> Option<String> {
108        let s = value.get(key)?.as_str()?;
109        (s.len() <= max).then(|| s.to_string())
110    };
111    let instance_id = text("instance_id", MAX_ID_LEN).filter(|s| !s.is_empty())?;
112    // Without a key the peer cannot be queried at all (`query_peers_concurrently`
113    // skips it), so there is nothing to record.
114    let auth_key = text("auth_key", MAX_AUTH_KEY_LEN).filter(|s| !s.is_empty())?;
115    let hostname = text("hostname", MAX_HOSTNAME_LEN)?;
116    let version = text("version", MAX_VERSION_LEN)?;
117    // Optional: a peer from before it was advertised sends none, and an
118    // oversize one is dropped rather than refusing the whole reply.
119    let channel = text("channel", MAX_CHANNEL_LEN).unwrap_or_default();
120    let os = value
121        .get("os")
122        .and_then(|v| v.as_str())
123        .and_then(crate::backend::host_os::sanitize_os)
124        .unwrap_or_default();
125    let install = value
126        .get("install")
127        .and_then(|v| v.as_str())
128        .and_then(crate::backend::host_os::sanitize_os)
129        .unwrap_or_default();
130    let port = u16::try_from(value.get("port")?.as_u64()?)
131        .ok()
132        .filter(|p| *p >= MIN_PEER_PORT)?;
133    Some(UdpPeer {
134        instance_id,
135        hostname,
136        version,
137        channel,
138        os,
139        install,
140        build: crate::backend::lan::peer_words::build_token(value.get("build").and_then(|v| v.as_str())),
141        install_id: crate::backend::lan::peer_words::install_id_token(value.get("install_id").and_then(|v| v.as_str())),
142        address: src.ip(),
143        port,
144        auth_key,
145    })
146}
147
148/// What [`merge_udp_peer`] did.
149#[derive(Debug, Clone, Copy, PartialEq, Eq)]
150pub(super) enum Merge {
151    /// A new peer: the table changed, so clients should be told.
152    Inserted,
153    /// Already known (by mDNS or an earlier reply); only its liveness moved.
154    Refreshed,
155    /// Not recorded (table full).
156    Dropped,
157}
158
159/// A UDP peer's key: the address its reply came from and the port it serves.
160///
161/// Not the instance id. That is `v<version>` (the launcher's `AGENTMUX_INSTANCE_ID`),
162/// so every machine on the same release shares it, and keying on it merged two
163/// such machines into one entry that flapped between them (Codex P1 on #4241).
164fn udp_key(address: &str, port: u16) -> String {
165    format!("{UDP_KEY_PREFIX}{address}:{port}")
166}
167
168/// The same peer as `peer` already in the table, by the one identity that is
169/// unique on a LAN: the address it answers on and the port it serves.
170fn find_existing<'a>(
171    instances: &'a mut HashMap<String, LanInstance>,
172    peer: &UdpPeer,
173) -> Option<(&'a String, &'a mut LanInstance)> {
174    let address = peer.address.to_string();
175    instances
176        .iter_mut()
177        .find(|(_, i)| i.address == address && i.port == peer.port)
178}
179
180/// Record `peer` in the table without ever duplicating a peer mDNS already
181/// knows: `find_agent` queries every entry, so a double would double every
182/// lookup. An mDNS entry is authoritative and only has its liveness refreshed.
183pub(super) fn merge_udp_peer(
184    instances: &mut HashMap<String, LanInstance>,
185    peer: &UdpPeer,
186    now: u64,
187) -> Merge {
188    if let Some((key, existing)) = find_existing(instances, peer) {
189        existing.last_seen = now;
190        if key.starts_with(UDP_KEY_PREFIX) {
191            // Ours: the reply is the freshest word on who this is. A peer that
192            // restarted on a new release keeps its address and port but reports a
193            // new version and instance id; the key does not depend on either.
194            existing.instance_id = peer.instance_id.clone();
195            existing.hostname = peer.hostname.clone();
196            existing.version = peer.version.clone();
197            // An older build, or an oversize field, sends none: keep the channel
198            // already known rather than fall back to the port label (Codex P2 on
199            // #4241), as the mDNS path does.
200            if !peer.channel.is_empty() {
201                existing.channel = peer.channel.clone();
202            }
203            if !peer.os.is_empty() {
204                existing.os = peer.os.clone();
205            }
206            if !peer.install.is_empty() {
207                existing.install = peer.install.clone();
208            }
209            if !peer.build.is_empty() {
210                existing.build = peer.build.clone();
211            }
212            crate::backend::lan::peer_words::keep_known(&mut existing.install_id, peer.install_id.clone());
213            existing.auth_key = peer.auth_key.clone();
214        } else {
215            if existing.auth_key.is_empty() {
216                existing.auth_key = peer.auth_key.clone();
217            }
218            if existing.channel.is_empty() {
219                existing.channel = peer.channel.clone();
220            }
221            if existing.os.is_empty() {
222                existing.os = peer.os.clone();
223            }
224            if existing.install.is_empty() {
225                existing.install = peer.install.clone();
226            }
227            if existing.build.is_empty() {
228                existing.build = peer.build.clone();
229            }
230            if existing.install_id.is_empty() {
231                existing.install_id = peer.install_id.clone();
232            }
233        }
234        return Merge::Refreshed;
235    }
236    if instances
237        .keys()
238        .filter(|k| k.starts_with(UDP_KEY_PREFIX))
239        .count()
240        >= MAX_UDP_PEERS
241    {
242        return Merge::Dropped;
243    }
244    let address = peer.address.to_string();
245    instances.insert(
246        udp_key(&address, peer.port),
247        LanInstance {
248            instance_id: peer.instance_id.clone(),
249            hostname: peer.hostname.clone(),
250            version: peer.version.clone(),
251            channel: peer.channel.clone(),
252            os: peer.os.clone(),
253            install: peer.install.clone(),
254            build: peer.build.clone(),
255            install_id: peer.install_id.clone(),
256            address,
257            port: peer.port,
258            auth_key: peer.auth_key.clone(),
259            agents: Vec::new(),
260            agent_status: Default::default(),
261            agent_lines: Default::default(),
262            agent_providers: Default::default(),
263            agent_kinds: Default::default(),
264            agent_accounts: Default::default(),
265            agent_resets: Default::default(),
266            agent_seats: Default::default(),
267            first_seen: now,
268            last_seen: now,
269            last_polled_ok: 0,
270            other_ttl_secs: UDP_PEER_TTL_SECS,
271        },
272    );
273    Merge::Inserted
274}
275
276/// Remove UDP-learned entries that an mDNS entry now covers (the same address
277/// and port). Called after an mDNS resolution so the order the two routes find a
278/// peer in does not decide whether it is listed twice. Instance ids are not
279/// compared: they are per release, not per machine (see [`udp_key`]).
280pub(super) fn drop_udp_duplicates(instances: &mut HashMap<String, LanInstance>) {
281    let mdns: Vec<(String, u16)> = instances
282        .iter()
283        .filter(|(k, _)| !k.starts_with(UDP_KEY_PREFIX))
284        .map(|(_, i)| (i.address.clone(), i.port))
285        .collect();
286    instances.retain(|key, i| {
287        !key.starts_with(UDP_KEY_PREFIX)
288            || !mdns
289                .iter()
290                .any(|(addr, port)| *addr == i.address && *port == i.port)
291    });
292}
293
294/// Where to send a probe: the limited broadcast address, plus each non-loopback
295/// IPv4 interface's directed broadcast. The limited broadcast alone leaves by
296/// one interface only on Windows, which is the wrong one on a host with a VPN or
297/// a virtual adapter (narko has four).
298pub(super) fn probe_targets(
299    broadcasts: impl IntoIterator<Item = Ipv4Addr>,
300    port: u16,
301) -> Vec<std::net::SocketAddr> {
302    let mut all: BTreeSet<Ipv4Addr> = broadcasts
303        .into_iter()
304        .filter(|b| !b.is_loopback())
305        .collect();
306    all.insert(Ipv4Addr::BROADCAST);
307    all.into_iter()
308        .map(|b| std::net::SocketAddr::from((b, port)))
309        .collect()
310}
311
312/// The directed broadcast address of every usable local IPv4 interface.
313pub(super) fn local_broadcasts() -> Vec<Ipv4Addr> {
314    if_addrs::get_if_addrs()
315        .unwrap_or_default()
316        .into_iter()
317        .filter(|i| !i.is_loopback())
318        .filter_map(|i| match i.addr {
319            if_addrs::IfAddr::V4(v4) => v4.broadcast,
320            _ => None,
321        })
322        .collect()
323}
324
325/// The probe datagram. The same one a mobile client sends, so every responder in
326/// the field already understands it.
327pub(super) fn probe_datagram() -> Vec<u8> {
328    serde_json::to_vec(&json!({ "type": UDP_PROBE_TYPE, "v": UDP_PROTOCOL_VERSION }))
329        .unwrap_or_default()
330}
331
332impl LanDiscovery {
333    /// Bind the discovery socket and run [`Self::udp_peer_loop_on`] over it. A
334    /// failed bind (most likely another local instance holds the port) is
335    /// logged at debug and ends the task; mDNS is unaffected.
336    pub(super) async fn udp_peer_loop(self: Arc<Self>, cancel: oneshot::Receiver<()>) {
337        let socket = match UdpSocket::bind(("0.0.0.0", DESKTOP_DISCOVERY_PORT)).await {
338            Ok(s) => s,
339            Err(e) => {
340                tracing::debug!(
341                    port = DESKTOP_DISCOVERY_PORT,
342                    "UDP peer discovery not started (bind failed, likely another local instance \
343                     holds this port): {e}"
344                );
345                return;
346            }
347        };
348        if let Err(e) = socket.set_broadcast(true) {
349            tracing::warn!(error = %e, "UDP peer discovery: cannot enable broadcast, not starting");
350            return;
351        }
352        tracing::debug!(
353            port = DESKTOP_DISCOVERY_PORT,
354            "UDP peer discovery listening"
355        );
356        let targets = || probe_targets(local_broadcasts(), DESKTOP_DISCOVERY_PORT);
357        self.udp_peer_loop_on(socket, targets, PROBE_INTERVAL, cancel)
358            .await;
359    }
360
361    /// The loop proper, over a socket and target list the caller supplies so a
362    /// test can drive two instances on loopback without the production port.
363    pub(super) async fn udp_peer_loop_on(
364        self: Arc<Self>,
365        socket: UdpSocket,
366        targets: impl Fn() -> Vec<std::net::SocketAddr>,
367        every: std::time::Duration,
368        mut cancel: oneshot::Receiver<()>,
369    ) {
370        let own_port = socket.local_addr().map(|a| a.port()).unwrap_or(0);
371        let probe = probe_datagram();
372        let mut ticker = tokio::time::interval(every);
373        ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
374        let mut buf = [0u8; 1024];
375        loop {
376            tokio::select! {
377                _ = &mut cancel => {
378                    tracing::debug!("UDP peer discovery stopping");
379                    return;
380                }
381                _ = ticker.tick() => {
382                    for target in targets() {
383                        // An interface that is down, or a host with no route to
384                        // a broadcast address, fails here; the others still go.
385                        if let Err(e) = socket.send_to(&probe, target).await {
386                            tracing::debug!(%target, error = %e, "UDP peer probe send failed");
387                        }
388                    }
389                }
390                result = socket.recv_from(&mut buf) => match result {
391                    Ok((len, src)) => self.handle_datagram(&socket, own_port, &buf[..len], src).await,
392                    Err(e) => {
393                        // A persistent error (Windows reports an ICMP
394                        // port-unreachable from our own earlier send as
395                        // WSAECONNRESET) must not spin this loop.
396                        tracing::debug!("UDP peer discovery recv_from error: {e}");
397                        tokio::time::sleep(std::time::Duration::from_millis(200)).await;
398                    }
399                },
400            }
401        }
402    }
403
404    async fn handle_datagram(
405        &self,
406        socket: &UdpSocket,
407        own_port: u16,
408        bytes: &[u8],
409        src: std::net::SocketAddr,
410    ) {
411        // Our own broadcast comes back to our own socket on most stacks.
412        let own_addrs = crate::backend::lan::listeners::cached_local_addresses();
413        if src.port() == own_port && own_addrs.contains(&src.ip()) {
414            return;
415        }
416        // A probe of another protocol version is refused plainly, and a reply of one is logged: neither is read as version 1.
417        if matches!(super::probe_version::classify(bytes), super::probe_version::Probe::Other(_)) {
418            super::probe_version::declined(socket, bytes, src, &self.version).await;
419            return;
420        }
421        if super::probe_version::newer_reply(bytes, &src) {
422            return;
423        }
424        if is_valid_probe(bytes) {
425            // Same trust boundary as the 47891 responder: the reply carries
426            // `auth_key`, so only a private-range source gets one.
427            if !is_lan_source(&src) {
428                return;
429            }
430            // Identity only, without the 47891 reply's `siblings`: a desktop
431            // reads replies into a 1024-byte buffer, which siblings could
432            // overflow, and finds a host's other channels over mDNS anyway.
433            if let Ok(payload) = serde_json::to_vec(&self.build_identity_response()) {
434                if let Err(e) = socket.send_to(&payload, src).await {
435                    tracing::debug!(%src, error = %e, "UDP peer reply send failed");
436                }
437            }
438            return;
439        }
440        let Some(peer) = parse_peer_reply(bytes, &src) else {
441            return;
442        };
443        // Not `peer.instance_id == self.instance_id`: that id is the release
444        // (`v<version>`), so every other machine on our release would have been
445        // ignored. "Us" is our own address with our own port, checked below.
446        let own_addr_list = [peer.address];
447        if is_self_resolution(peer.port, &own_addr_list, self.port, &own_addrs) {
448            return;
449        }
450        let now = agentmux_common::time::now_secs_u64();
451        let outcome = merge_udp_peer(&mut self.instances.write(), &peer, now);
452        match outcome {
453            Merge::Inserted => {
454                tracing::info!(
455                    peer_id = %peer.instance_id,
456                    address = %peer.address,
457                    port = peer.port,
458                    "LAN peer discovered (UDP broadcast)"
459                );
460                self.broadcast_instances();
461            }
462            Merge::Refreshed => {}
463            Merge::Dropped => {
464                tracing::debug!(%src, "UDP peer table full, reply ignored");
465            }
466        }
467    }
468}
469
470#[cfg(test)]
471mod tests {
472    use super::*;
473
474    fn src(ip: &str) -> std::net::SocketAddr {
475        format!("{ip}:{DESKTOP_DISCOVERY_PORT}").parse().unwrap()
476    }
477
478    fn reply(id: &str, port: u64) -> Vec<u8> {
479        serde_json::to_vec(&json!({
480            "type": UDP_RESPONSE_TYPE, "v": 1, "instance_id": id, "hostname": "area54",
481            "version": "0.59.4", "port": port, "auth_key": "k-secret",
482        }))
483        .unwrap()
484    }
485
486    fn peer(id: &str, addr: &str, port: u16) -> UdpPeer {
487        UdpPeer {
488            instance_id: id.into(),
489            hostname: "h".into(),
490            version: "0.59.4".into(),
491            channel: "stable".into(),
492            os: String::new(),
493            install: String::new(),
494            build: String::new(),
495            install_id: String::new(),
496            address: addr.parse().unwrap(),
497            port,
498            auth_key: "k".into(),
499        }
500    }
501
502    fn mdns_entry(id: &str, addr: &str, port: u16) -> LanInstance {
503        LanInstance {
504            instance_id: id.into(),
505            hostname: "mdns-name".into(),
506            version: "0.59.4".into(),
507            channel: String::new(),
508            os: String::new(),
509            install: String::new(),
510            build: String::new(),
511            address: addr.into(),
512            port,
513            auth_key: "mdns-key".into(),
514            agents: vec!["korp".into()],
515            agent_status: Default::default(),
516            agent_lines: Default::default(),
517            agent_providers: Default::default(),
518            agent_kinds: Default::default(),
519            agent_accounts: Default::default(),
520            agent_resets: Default::default(),
521            agent_seats: Default::default(),
522            first_seen: 1,
523            last_seen: 1,
524            last_polled_ok: 0,
525            install_id: String::new(),
526            other_ttl_secs: 4500,
527        }
528    }
529
530    #[test]
531    fn a_well_formed_reply_from_a_lan_address_is_a_peer() {
532        let p = parse_peer_reply(&reply("abc", 29700), &src("10.0.0.26")).unwrap();
533        assert_eq!(p.instance_id, "abc");
534        assert_eq!(p.address, "10.0.0.26".parse::<IpAddr>().unwrap());
535        assert_eq!(p.port, 29700);
536        assert_eq!(p.auth_key, "k-secret");
537    }
538
539    #[test]
540    fn the_channel_is_read_when_present_and_optional_when_not() {
541        let mut v: serde_json::Value = serde_json::from_slice(&reply("abc", 29700)).unwrap();
542        assert_eq!(
543            parse_peer_reply(&serde_json::to_vec(&v).unwrap(), &src("10.0.0.26"))
544                .unwrap()
545                .channel,
546            ""
547        );
548        v["channel"] = json!("dev-fix-lan");
549        assert_eq!(
550            parse_peer_reply(&serde_json::to_vec(&v).unwrap(), &src("10.0.0.26"))
551                .unwrap()
552                .channel,
553            "dev-fix-lan"
554        );
555        // Oversize: dropped, the reply still counts.
556        v["channel"] = json!("c".repeat(MAX_CHANNEL_LEN + 1));
557        assert_eq!(
558            parse_peer_reply(&serde_json::to_vec(&v).unwrap(), &src("10.0.0.26"))
559                .unwrap()
560                .channel,
561            ""
562        );
563    }
564
565    #[test]
566    fn the_install_id_is_read_when_well_formed_and_optional_when_not() {
567        let mut v: serde_json::Value = serde_json::from_slice(&reply("abc", 29700)).unwrap();
568        let id_of = |v: &serde_json::Value| parse_peer_reply(&serde_json::to_vec(v).unwrap(), &src("10.0.0.26")).unwrap().install_id;
569        assert_eq!(id_of(&v), "", "an older peer sends none");
570        v["install_id"] = json!("mw3am46w5weex4a4fqrc3avnua");
571        assert_eq!(id_of(&v), "mw3am46w5weex4a4fqrc3avnua");
572        v["install_id"] = json!("not an id");
573        assert_eq!(id_of(&v), "", "malformed: dropped, the reply still counts");
574        v["install_id"] = json!(7);
575        assert_eq!(id_of(&v), "");
576    }
577
578    // The platform tag (SPEC_SWARM_REMOTE_AGENTS_PLATFORM_TAG_AND_SELECTION_2026_10_03.md §3).
579    #[test]
580    fn the_os_is_read_when_it_is_a_plain_token_and_dropped_otherwise() {
581        let mut v: serde_json::Value = serde_json::from_slice(&reply("abc", 29700)).unwrap();
582        let os_of = |v: &serde_json::Value| {
583            parse_peer_reply(&serde_json::to_vec(v).unwrap(), &src("10.0.0.26"))
584                .unwrap()
585                .os
586        };
587        assert_eq!(os_of(&v), "");
588        for ok in ["windows", "macos", "linux"] {
589            v["os"] = json!(ok);
590            assert_eq!(os_of(&v), ok);
591        }
592        // Anything else is dropped; the reply still counts.
593        for bad in ["Windows", "<b>x</b>", "../etc", "", "a-very-long-platform-name"] {
594            v["os"] = json!(bad);
595            assert_eq!(os_of(&v), "", "{bad:?}");
596        }
597        v["os"] = json!(42);
598        assert_eq!(os_of(&v), "");
599    }
600
601    #[test]
602    fn a_reply_without_an_os_keeps_the_known_one() {
603        let mut t = HashMap::new();
604        let mut with = peer("abc", "10.0.0.26", 29700);
605        with.os = "macos".into();
606        merge_udp_peer(&mut t, &with, 100);
607        assert_eq!(t["udp:10.0.0.26:29700"].os, "macos");
608        merge_udp_peer(&mut t, &peer("abc", "10.0.0.26", 29700), 200);
609        assert_eq!(t["udp:10.0.0.26:29700"].os, "macos");
610    }
611
612    #[test]
613    fn an_mdns_entry_with_no_os_learns_it_from_a_udp_reply() {
614        let mut t = HashMap::new();
615        t.insert("mdns-full".to_string(), mdns_entry("abc", "10.0.0.26", 29700));
616        let mut udp = peer("abc", "10.0.0.26", 29700);
617        udp.os = "linux".into();
618        merge_udp_peer(&mut t, &udp, 100);
619        assert_eq!(t["mdns-full"].os, "linux");
620    }
621
622    #[test]
623    fn the_address_is_the_datagrams_source_never_a_claimed_one() {
624        let mut v: serde_json::Value = serde_json::from_slice(&reply("abc", 29700)).unwrap();
625        v["address"] = json!("10.9.9.9");
626        let p = parse_peer_reply(&serde_json::to_vec(&v).unwrap(), &src("10.0.0.26")).unwrap();
627        assert_eq!(p.address.to_string(), "10.0.0.26");
628    }
629
630    #[test]
631    fn replies_that_are_not_trustworthy_enough_to_record_are_refused() {
632        let ok = src("10.0.0.26");
633        // Not from the private ranges: a public host must not seed the table.
634        assert!(parse_peer_reply(&reply("abc", 29700), &src("8.8.8.8")).is_none());
635        // A probe, noise, another version.
636        assert!(parse_peer_reply(&probe_datagram(), &ok).is_none());
637        assert!(parse_peer_reply(b"not json", &ok).is_none());
638        let mut v: serde_json::Value = serde_json::from_slice(&reply("abc", 29700)).unwrap();
639        v["v"] = json!(2);
640        assert!(parse_peer_reply(&serde_json::to_vec(&v).unwrap(), &ok).is_none());
641        // Privileged or out-of-range ports.
642        assert!(parse_peer_reply(&reply("abc", 80), &ok).is_none());
643        assert!(parse_peer_reply(&reply("abc", 70000), &ok).is_none());
644        // Missing or empty identity or key, and oversize fields.
645        assert!(parse_peer_reply(&reply("", 29700), &ok).is_none());
646        for field in ["instance_id", "auth_key", "hostname", "version", "port"] {
647            let mut v: serde_json::Value = serde_json::from_slice(&reply("abc", 29700)).unwrap();
648            v.as_object_mut().unwrap().remove(field);
649            assert!(
650                parse_peer_reply(&serde_json::to_vec(&v).unwrap(), &ok).is_none(),
651                "{field}"
652            );
653        }
654        let mut v: serde_json::Value = serde_json::from_slice(&reply("abc", 29700)).unwrap();
655        v["auth_key"] = json!("k".repeat(MAX_AUTH_KEY_LEN + 1));
656        assert!(parse_peer_reply(&serde_json::to_vec(&v).unwrap(), &ok).is_none());
657        v["auth_key"] = json!("");
658        assert!(parse_peer_reply(&serde_json::to_vec(&v).unwrap(), &ok).is_none());
659    }
660
661    #[test]
662    fn a_new_peer_is_recorded_under_a_udp_key_with_a_short_ttl() {
663        let mut t = HashMap::new();
664        assert_eq!(
665            merge_udp_peer(&mut t, &peer("abc", "10.0.0.26", 29700), 100),
666            Merge::Inserted
667        );
668        let e = &t["udp:10.0.0.26:29700"];
669        assert_eq!(
670            (e.last_seen, e.first_seen, e.other_ttl_secs),
671            (100, 100, UDP_PEER_TTL_SECS)
672        );
673        assert!(e.agents.is_empty());
674    }
675
676    #[test]
677    fn a_peer_mdns_already_knows_is_not_listed_twice() {
678        // By address and port, whatever the TXT record says or has not said yet.
679        for known in [
680            mdns_entry("abc", "10.0.0.26", 29700),
681            mdns_entry("", "10.0.0.26", 29700),
682        ] {
683            let mut t = HashMap::new();
684            t.insert("agentmux-x._agentmux._tcp.local.".to_string(), known);
685            assert_eq!(
686                merge_udp_peer(&mut t, &peer("abc", "10.0.0.26", 29700), 500),
687                Merge::Refreshed
688            );
689            assert_eq!(t.len(), 1, "no second entry");
690            let e = &t["agentmux-x._agentmux._tcp.local."];
691            assert_eq!(e.last_seen, 500, "liveness moves");
692            assert_eq!(e.hostname, "mdns-name", "mDNS data is authoritative");
693            assert_eq!(e.auth_key, "mdns-key");
694        }
695    }
696
697    #[test]
698    fn a_reply_without_a_channel_keeps_the_known_one() {
699        // Codex P2 on #4241: an older build (or an oversize field) sends none.
700        let mut t = HashMap::new();
701        merge_udp_peer(&mut t, &peer("abc", "10.0.0.26", 29700), 100);
702        assert_eq!(t["udp:10.0.0.26:29700"].channel, "stable");
703        let mut no_channel = peer("abc", "10.0.0.26", 29700);
704        no_channel.channel = String::new();
705        merge_udp_peer(&mut t, &no_channel, 200);
706        assert_eq!(t["udp:10.0.0.26:29700"].channel, "stable");
707    }
708
709    #[test]
710    fn a_later_reply_updates_a_udp_entry_in_place() {
711        let mut t = HashMap::new();
712        merge_udp_peer(&mut t, &peer("abc", "10.0.0.26", 29700), 100);
713        let mut renamed = peer("abc", "10.0.0.26", 29700);
714        renamed.hostname = "area54-renamed".into();
715        assert_eq!(merge_udp_peer(&mut t, &renamed, 200), Merge::Refreshed);
716        assert_eq!(t.len(), 1);
717        let e = &t["udp:10.0.0.26:29700"];
718        assert_eq!((e.hostname.as_str(), e.last_seen), ("area54-renamed", 200));
719    }
720
721    /// Codex P1 on #4241: the instance id is the release (`v<version>`), so two
722    /// machines on the same release send the same one. They are two peers.
723    #[test]
724    fn two_machines_on_the_same_release_are_two_peers() {
725        let mut t = HashMap::new();
726        assert_eq!(
727            merge_udp_peer(&mut t, &peer("v0.59.5", "10.0.0.26", 29700), 1),
728            Merge::Inserted
729        );
730        assert_eq!(
731            merge_udp_peer(&mut t, &peer("v0.59.5", "10.0.0.195", 29700), 1),
732            Merge::Inserted
733        );
734        assert_eq!(t.len(), 2);
735        // And an mDNS entry for one of them does not swallow the other.
736        t.insert(
737            "mdns-a".into(),
738            mdns_entry("v0.59.5", "10.0.0.26", 29700),
739        );
740        drop_udp_duplicates(&mut t);
741        assert!(t.contains_key("udp:10.0.0.195:29700"));
742        assert!(!t.contains_key("udp:10.0.0.26:29700"));
743    }
744
745    #[test]
746    fn the_udp_peer_table_is_bounded() {
747        let mut t = HashMap::new();
748        for n in 0..MAX_UDP_PEERS {
749            assert_eq!(
750                merge_udp_peer(
751                    &mut t,
752                    &peer(
753                        &format!("id{n}"),
754                        &format!("10.0.{}.{}", n / 200, n % 200 + 1),
755                        29700
756                    ),
757                    1
758                ),
759                Merge::Inserted
760            );
761        }
762        assert_eq!(
763            merge_udp_peer(&mut t, &peer("one-too-many", "10.1.0.1", 29700), 1),
764            Merge::Dropped
765        );
766        // A peer already in the table still refreshes at the cap.
767        assert_eq!(
768            merge_udp_peer(&mut t, &peer("id0", "10.0.0.1", 29700), 2),
769            Merge::Refreshed
770        );
771        // mDNS entries are not counted against the UDP cap.
772        t.insert("mdns".into(), mdns_entry("m", "10.2.0.1", 29700));
773        assert_eq!(
774            t.keys().filter(|k| k.starts_with("udp:")).count(),
775            MAX_UDP_PEERS
776        );
777    }
778
779    #[test]
780    fn an_mdns_resolution_after_the_udp_one_replaces_it() {
781        let mut t = HashMap::new();
782        merge_udp_peer(&mut t, &peer("abc", "10.0.0.26", 29700), 100);
783        merge_udp_peer(&mut t, &peer("other", "10.0.0.40", 29700), 100);
784        t.insert(
785            "agentmux-x._agentmux._tcp.local.".to_string(),
786            mdns_entry("abc", "10.0.0.26", 29700),
787        );
788        drop_udp_duplicates(&mut t);
789        assert!(!t.contains_key("udp:10.0.0.26:29700"));
790        assert!(
791            t.contains_key("udp:10.0.0.40:29700"),
792            "an unrelated UDP peer stays"
793        );
794        assert!(t.contains_key("agentmux-x._agentmux._tcp.local."));
795    }
796
797    #[test]
798    fn probes_go_to_the_limited_and_every_directed_broadcast_once() {
799        let t = probe_targets(
800            [
801                "192.168.1.255".parse().unwrap(),
802                "172.17.31.255".parse().unwrap(),
803                "192.168.1.255".parse().unwrap(),
804                "127.255.255.255".parse().unwrap(),
805            ],
806            DESKTOP_DISCOVERY_PORT,
807        );
808        let t: Vec<String> = t.iter().map(|a| a.to_string()).collect();
809        assert_eq!(
810            t,
811            [
812                "172.17.31.255:29700",
813                "192.168.1.255:29700",
814                "255.255.255.255:29700"
815            ]
816        );
817        // No interface at all still probes the limited broadcast.
818        assert_eq!(probe_targets([], 29700).len(), 1);
819    }
820
821    #[test]
822    fn the_probe_is_one_every_responder_already_accepts() {
823        assert!(is_valid_probe(&probe_datagram()));
824    }
825
826    #[test]
827    fn the_desktop_port_is_in_the_fixed_block() {
828        assert!(crate::backend::lan::ports::LAN_PORT_RANGE.contains(&DESKTOP_DISCOVERY_PORT));
829        assert!(
830            DESKTOP_DISCOVERY_PORT < 32768,
831            "below every OS's ephemeral range"
832        );
833    }
834
835    /// A `LanDiscovery` with a real (idle) mDNS daemon but none of `start()`'s
836    /// registration or tasks, as `handle_event_tests` builds one.
837    fn instance(id: &str, host: &str, port: u16, key: &str) -> Arc<LanDiscovery> {
838        Arc::new(LanDiscovery {
839            daemon: ServiceDaemon::new().expect("daemon construction (no register/browse)"),
840            instances: Arc::new(RwLock::new(HashMap::new())),
841            instance_id: id.to_string(),
842            event_bus: Arc::new(crate::backend::eventbus::EventBus::new()),
843            service_fullname: String::new(),
844            auth_key: key.to_string(),
845            hostname: host.to_string(),
846            version: "0.59.4".to_string(),
847            port,
848            udp_cancel: Mutex::new(None),
849            udp_peer_cancel: Mutex::new(None),
850            agent_names_cancel: Mutex::new(None),
851            instance_record_cancel: Mutex::new(None),
852            instances_dir: None,
853            instance_record_live: Mutex::new(false),
854            announced_v4: Arc::new(Mutex::new(BTreeSet::new())),
855            monitored: true,
856            started_at: std::time::Instant::now(),
857        })
858    }
859
860    /// The whole route, with mDNS out of the picture: two instances probe each
861    /// other over loopback sockets and each ends up with exactly one entry for
862    /// the other, carrying what it advertised.
863    #[tokio::test]
864    async fn two_instances_find_each_other_by_probe_alone() {
865        let a = instance("id-a", "host-a", 55001, "key-a");
866        let b = instance("id-b", "host-b", 55002, "key-b");
867        let sa = UdpSocket::bind("127.0.0.1:0").await.unwrap();
868        let sb = UdpSocket::bind("127.0.0.1:0").await.unwrap();
869        let (addr_a, addr_b) = (sa.local_addr().unwrap(), sb.local_addr().unwrap());
870        let (cancel_a, rx_a) = oneshot::channel();
871        let (cancel_b, rx_b) = oneshot::channel();
872        let every = std::time::Duration::from_millis(50);
873        // Each also probes its own address, as a real broadcast comes back to the
874        // sender's own socket.
875        tokio::spawn(
876            a.clone()
877                .udp_peer_loop_on(sa, move || vec![addr_b, addr_a], every, rx_a),
878        );
879        tokio::spawn(
880            b.clone()
881                .udp_peer_loop_on(sb, move || vec![addr_a, addr_b], every, rx_b),
882        );
883
884        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
885        let (seen_by_a, seen_by_b) = loop {
886            let (x, y) = (a.get_instances(), b.get_instances());
887            if (!x.is_empty() && !y.is_empty()) || std::time::Instant::now() > deadline {
888                break (x, y);
889            }
890            tokio::time::sleep(std::time::Duration::from_millis(25)).await;
891        };
892        let _ = (cancel_a.send(()), cancel_b.send(()));
893
894        assert_eq!(seen_by_a.len(), 1, "a sees b once: {seen_by_a:?}");
895        assert_eq!(seen_by_b.len(), 1, "b sees a once: {seen_by_b:?}");
896        let b_as_seen = &seen_by_a[0];
897        assert_eq!(
898            (
899                b_as_seen.instance_id.as_str(),
900                b_as_seen.hostname.as_str(),
901                b_as_seen.port,
902                b_as_seen.auth_key.as_str()
903            ),
904            ("id-b", "host-b", 55002, "key-b")
905        );
906        assert_eq!(
907            b_as_seen.address, "127.0.0.1",
908            "the address is the datagram's source"
909        );
910        assert_eq!(seen_by_b[0].instance_id, "id-a");
911        // Neither listed itself, which its own broadcast would have caused.
912        tokio::time::sleep(std::time::Duration::from_millis(300)).await;
913        assert!(
914            a.get_instances().iter().all(|i| i.instance_id != "id-a"),
915            "a listed itself"
916        );
917        assert!(
918            b.get_instances().iter().all(|i| i.instance_id != "id-b"),
919            "b listed itself"
920        );
921    }
922
923    /// "Us" is our own address serving our own port, not our instance id: that
924    /// id is the release, shared by every machine on it (Codex P1 on #4241).
925    #[tokio::test]
926    async fn a_machine_on_our_release_is_a_peer_and_our_own_address_is_us() {
927        let a = instance("v0.59.5", "host-a", 55001, "key-a");
928        let socket = UdpSocket::bind("127.0.0.1:0").await.unwrap();
929        let own_port = socket.local_addr().unwrap().port();
930        // Same instance id as ours (the release), from another machine: a peer.
931        let from: std::net::SocketAddr = "10.0.0.77:29700".parse().unwrap();
932        a.handle_datagram(&socket, own_port, &reply("v0.59.5", 29799), from)
933            .await;
934        assert_eq!(
935            a.get_instances().len(),
936            1,
937            "another machine on our release is not us"
938        );
939        // Our own address serving our own port: us, never a peer.
940        if let Some(own) = crate::backend::lan::listeners::cached_local_addresses()
941            .iter()
942            .find(|ip| ip.is_ipv4() && !ip.is_loopback())
943        {
944            let from_self = std::net::SocketAddr::new(*own, 29700);
945            a.handle_datagram(&socket, own_port, &reply("v0.59.5", 55001), from_self)
946                .await;
947            assert_eq!(a.get_instances().len(), 1, "our own address and port is us");
948        }
949    }
950
951    /// A UDP peer is listed for the staleness floor after its last reply and not
952    /// a second longer, whatever `other_ttl_secs` says (ReAgent P2 on #4230: the
953    /// constant used to claim 120 s while the floor made it 300).
954    #[tokio::test]
955    async fn a_udp_peer_is_listed_for_exactly_the_staleness_floor() {
956        let a = instance("id-a", "host-a", 55001, "key-a");
957        let now = agentmux_common::time::now_secs_u64();
958        let floor = LAN_PEER_STALE_TIMEOUT_FLOOR_SECS;
959        assert_eq!(
960            u64::from(UDP_PEER_TTL_SECS),
961            floor,
962            "the constant states the real lifetime"
963        );
964        for (age, listed) in [(0, true), (floor - 5, true), (floor + 5, false)] {
965            merge_udp_peer(
966                &mut a.instances.write(),
967                &peer("abc", "10.0.0.26", 29700),
968                now - age,
969            );
970            assert_eq!(a.get_instances().len(), usize::from(listed), "age {age}s");
971            a.instances.write().clear();
972        }
973    }
974
975    /// A peer that restarts keeps its address and port and gets a new instance
976    /// id (ReAgent P2 on #4230): the entry follows it, re-keyed, so id-based
977    /// dedup compares against the live id and not a stale one.
978    #[test]
979    fn a_restarted_peer_keeps_one_entry_under_its_new_id() {
980        let mut t = HashMap::new();
981        merge_udp_peer(&mut t, &peer("v0.59.4", "10.0.0.26", 29700), 100);
982        assert_eq!(
983            merge_udp_peer(&mut t, &peer("v0.59.5", "10.0.0.26", 29700), 200),
984            Merge::Refreshed
985        );
986        assert_eq!(t.len(), 1, "{:?}", t.keys().collect::<Vec<_>>());
987        let e = &t["udp:10.0.0.26:29700"];
988        assert_eq!(
989            (e.instance_id.as_str(), e.first_seen, e.last_seen),
990            ("v0.59.5", 100, 200)
991        );
992    }
993}