agentmux_srv_core/backend/lan/discovery.rs
1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! LAN instance discovery via mDNS/DNS-SD.
5//!
6//! Each AgentMux backend advertises itself as `_agentmux._tcp.local.` and
7//! continuously browses for peers. Discovered instances are tracked in memory
8//! and broadcast to frontend clients via EventBus.
9
10use std::collections::{BTreeMap, BTreeSet, HashMap};
11use std::net::{IpAddr, Ipv4Addr};
12use std::sync::Arc;
13
14use mdns_sd::{ServiceDaemon, ServiceEvent, ServiceInfo};
15use parking_lot::{Mutex, RwLock};
16
17use crate::backend::agent_state::AgentState;
18use crate::backend::lan::mdns_diag;
19use crate::backend::lan::mdns_health;
20use serde::{Deserialize, Serialize};
21use serde_json::json;
22use tokio::net::UdpSocket;
23use tokio::sync::oneshot;
24
25use crate::backend::eventbus::EventBus;
26
27pub mod agent_names;
28pub mod events;
29pub mod lan_instances;
30pub mod one_per_instance;
31mod probe_version;
32pub mod udp_peers;
33pub mod uid_refetch;
34
35pub use events::{LanDiscoverability, LanDiscoveryError, LanInstanceList};
36pub use agent_names::{agent_names_body, parse_agent_names_body, PeerAgents};
37pub use one_per_instance::{one_per_instance, peer_base_url};
38pub(crate) use udp_peers::DESKTOP_DISCOVERY_PORT;
39
40const SERVICE_TYPE: &str = "_agentmux._tcp.local.";
41const LAN_AGENT_CACHE_TTL_SECS: u64 = 60;
42const LAN_PEER_QUERY_TIMEOUT_SECS: u64 = 2;
43/// How long a peer is kept after its most recent `ServiceResolved` before
44/// `get_instances()` treats it as gone. mdns-sd's own `ServiceRemoved` event
45/// is NOT used for this (see the `ServiceRemoved` arm of `handle_event`
46/// below) — live logs showed it firing on ordinary TTL churn seconds before
47/// the same peer re-resolved, and every re-resolution after a `remove()` came
48/// back with a blank TXT record, so deleting on `ServiceRemoved` permanently
49/// wiped a live peer's hostname/instance_id/version/auth_key for no real
50/// disappearance.
51///
52/// This is a FLOOR, not the actual timeout — see `peer_staleness_window_secs`.
53/// A fixed 300s (this constant's original, only value — see
54/// docs/retro/retro-lan-peer-stale-timeout-too-short-for-slow-reannounce-peers-2026-09-17.md)
55/// was tuned against one fast-reannouncing peer seen in live logs (1-2 minute
56/// re-fire gaps) and wrongly pruned peers whose own advertised record TTL is
57/// much longer: RFC 6762 §10's recommended (and mdns-sd 0.12's hardcoded,
58/// unconfigurable-from-this-crate-version) default `other_ttl` for PTR/TXT
59/// records is 4500s/75min, and real LAN peers were observed re-announcing on
60/// gaps up to ~46 minutes — comfortably inside that TTL, but 9x past the old
61/// fixed cutoff. 300s remains only as a safety floor against a peer that
62/// somehow advertises an implausibly small TTL.
63const LAN_PEER_STALE_TIMEOUT_FLOOR_SECS: u64 = 300;
64/// Ceiling on `other_ttl_secs`-driven staleness (ReAgent P1, PR #3301):
65/// `other_ttl_secs` is taken directly from a peer's own mDNS advertisement,
66/// which this file already treats as adversarial elsewhere (see
67/// `LAN_AGENT_NAMES_MAX_*` above — "anything that can fake an mDNS
68/// advertisement... makes it into `self.instances`"). Without a cap, a
69/// spoofed peer advertising `other_ttl` near `u32::MAX` (~136 years) would be
70/// honored by both `get_instances()` and the periodic GC, permanently pinning
71/// it as "alive" — defeating the entire self-pruning design this exists for.
72/// 2x the RFC 6762 §10 / mdns-sd 0.12 default (4500s) comfortably covers every
73/// legitimate cadence actually observed on this LAN (narko/starpower's ~46min
74/// gaps) with margin, while bounding attacker-controlled input the same way
75/// the byte/count/length caps above already do.
76const LAN_PEER_STALE_TIMEOUT_CEIL_SECS: u64 = 9000;
77
78/// A peer is stale once `last_seen` exceeds ITS OWN advertised `other_ttl` —
79/// the standards-defined lifetime of the PTR/TXT records that make up an mDNS
80/// announcement — not one fixed cutoff shared by every peer regardless of how
81/// often it actually re-announces. Clamped between
82/// `LAN_PEER_STALE_TIMEOUT_FLOOR_SECS` (guards an implausibly small
83/// advertised TTL) and `LAN_PEER_STALE_TIMEOUT_CEIL_SECS` (guards an
84/// adversarially large one — `other_ttl_secs` is untrusted peer input).
85fn peer_staleness_window_secs(other_ttl_secs: u32) -> u64 {
86 (other_ttl_secs as u64).clamp(LAN_PEER_STALE_TIMEOUT_FLOOR_SECS, LAN_PEER_STALE_TIMEOUT_CEIL_SECS)
87}
88/// How often each known LAN peer is asked for its agent-name list. Peers are
89/// few (one per machine) and the request is a single small GET, so this is
90/// cheap; it's deliberately slower than `LAN_AGENT_CACHE_TTL_SECS` because
91/// this list is for *display* ("who lives on that host"), not for delivery
92/// routing — `find_agent` still does its own authoritative lookup.
93const LAN_AGENT_NAMES_REFRESH_SECS: u64 = 30;
94/// Hard cap on a single peer's `/agentmux/reactive/agent-names` response body
95/// (Codex P1 on PR #3102): the `lan_key` a peer advertised authenticates
96/// THIS client TO that peer, not the peer to us — anything that can fake an
97/// mDNS advertisement for `_agentmux._tcp.local` makes it into
98/// `self.instances` and gets polled by this loop. Enforced while reading, not
99/// via `Content-Length` (a malicious peer can omit or lie about that while
100/// still streaming an unbounded chunked body). 64 KiB is generous for a
101/// plain name list — real fleets are agents-per-machine, not per-thousand.
102pub(crate) const LAN_AGENT_NAMES_MAX_RESPONSE_BYTES: usize = 64 * 1024;
103/// Defense in depth past the byte cap above: even a response that fits in
104/// 64 KiB could be an adversarially compact array of many short strings.
105const LAN_AGENT_NAMES_MAX_COUNT: usize = 500;
106/// A legitimate agent name is short; anything absurdly long is more likely
107/// an attempt to waste memory than a real name, so it's dropped rather than
108/// truncated (truncating could quietly merge two distinct long names).
109const LAN_AGENT_NAMES_MAX_NAME_LEN: usize = 256;
110
111/// UDP broadcast discovery fallback (Layer 2), for LANs where mDNS multicast
112/// is filtered (common on corporate/guest WiFi). Mobile clients broadcast a
113/// small JSON probe to this port; any listening desktop instance unicasts a
114/// response straight back to the sender's source address.
115///
116/// Port 47891 is picked from the "ephemeral-safe-but-memorable" range: above
117/// both the well-known (0-1023) and IANA-registered (1024-49151) ranges, so
118/// it never collides with a registered service, while still being a fixed,
119/// easy-to-grep value in logs and firewall rules (unlike a random ephemeral
120/// port, which a fixed-port broadcast probe cannot target).
121pub(crate) const UDP_DISCOVERY_PORT: u16 = 47891;
122
123/// Wire-protocol `type` value a probe datagram must carry.
124pub(crate) const UDP_PROBE_TYPE: &str = "agentmux_discover";
125/// Wire-protocol `type` value this responder replies with.
126const UDP_RESPONSE_TYPE: &str = "agentmux_discover_response";
127/// Wire-protocol version. Bump alongside the mobile client if the schema
128/// changes; `is_valid_probe` rejects anything else.
129pub(crate) const UDP_PROTOCOL_VERSION: u64 = 1;
130/// How often an instance that could not bind `UDP_DISCOVERY_PORT` tries
131/// again, so another LAN-enabled channel on this host takes over the probe
132/// port when its holder stops (SPEC_LAN_FLEET_FEED_2026_10_03.md §3).
133const UDP_RESPONDER_RETRY: std::time::Duration = std::time::Duration::from_secs(15);
134
135/// Build the JSON response payload for a valid probe. Pure/free function
136/// (no `&self`) so it is trivially testable without spinning up a full
137/// `LanDiscovery` (which owns a real mDNS `ServiceDaemon`). `LanDiscovery`'s
138/// production loop calls this via `build_probe_response`.
139fn probe_response_json(
140 instance_id: &str,
141 hostname: &str,
142 version: &str,
143 port: u16,
144 auth_key: &str,
145) -> serde_json::Value {
146 json!({
147 "type": UDP_RESPONSE_TYPE,
148 "v": UDP_PROTOCOL_VERSION,
149 "instance_id": instance_id,
150 "hostname": hostname,
151 "version": version,
152 "port": port,
153 "auth_key": auth_key,
154 })
155}
156
157/// Validate a received UDP datagram as an in-protocol discovery probe.
158/// Anything that fails to parse as JSON, or does not carry the exact
159/// `type`/`v` fields, is treated as noise (unrelated LAN traffic or a
160/// future/older protocol version) and silently ignored by the caller.
161fn is_valid_probe(bytes: &[u8]) -> bool {
162 let Ok(value) = serde_json::from_slice::<serde_json::Value>(bytes) else {
163 return false;
164 };
165 value.get("type").and_then(|t| t.as_str()) == Some(UDP_PROBE_TYPE) && is_probe_version_match(&value)
166}
167
168/// Match the probe's `v` field against `UDP_PROTOCOL_VERSION`, accepting
169/// either JSON integer or float encoding. Some JSON serializers (e.g. a
170/// client whose numeric type is inferred as `double`) emit a whole number
171/// like `1` as `1.0`; `Value::as_u64()` alone returns `None` for that
172/// representation, which would silently drop an otherwise-conformant probe.
173fn is_probe_version_match(value: &serde_json::Value) -> bool {
174 let Some(v) = value.get("v") else {
175 return false;
176 };
177 v.as_u64() == Some(UDP_PROTOCOL_VERSION) || v.as_f64() == Some(UDP_PROTOCOL_VERSION as f64)
178}
179
180/// Trust-boundary check for the UDP responder: is `addr` reachable only from
181/// a private/link-local network, i.e. plausibly on this LAN? Unlike mDNS
182/// (link-local multicast, structurally non-routable off-subnet), this socket
183/// binds `0.0.0.0` and would otherwise answer *any* routable unicast probe
184/// with `auth_key` — an internet-facing disclosure oracle / UDP reflection
185/// vector if the port is ever reachable externally (port forward, hairpin
186/// NAT). Mirrors the private/loopback/link-local classification used for the
187/// opposite purpose (SSRF egress checks) in
188/// `drone/executor/blocks/api.rs::is_reserved_v4`/`is_reserved_v6`, minus the
189/// broadcast/unspecified/multicast cases that don't apply to a source addr.
190fn is_lan_source(addr: &std::net::SocketAddr) -> bool {
191 match addr.ip() {
192 IpAddr::V4(v4) => v4.is_loopback() || v4.is_private() || v4.is_link_local(),
193 IpAddr::V6(v6) => {
194 if v6.is_loopback()
195 // unique-local fc00::/7
196 || (v6.segments()[0] & 0xfe00) == 0xfc00
197 // link-local fe80::/10
198 || (v6.segments()[0] & 0xffc0) == 0xfe80
199 {
200 return true;
201 }
202 // IPv4-mapped/-compatible v6 literals route to the embedded v4
203 // address on most kernels — delegate so a private v4 source
204 // wearing a v6 wrapper isn't misclassified as public.
205 if let Some(v4) = v6.to_ipv4_mapped() {
206 return v4.is_loopback() || v4.is_private() || v4.is_link_local();
207 }
208 #[allow(deprecated)]
209 if let Some(v4) = v6.to_ipv4() {
210 return v4.is_loopback() || v4.is_private() || v4.is_link_local();
211 }
212 false
213 }
214 }
215}
216
217#[derive(Debug, Clone, Serialize, Deserialize, ts_rs::TS)]
218#[ts(export, export_to = "../../../frontend/types/rpc/")]
219pub struct LanInstance {
220 pub instance_id: String,
221 pub hostname: String,
222 pub version: String,
223 /// The advertising instance's channel (`AGENTMUX_CHANNEL`, default
224 /// "stable"), so a host running two channels can be told apart in the
225 /// Swarm (SPEC_SWARM_OTHER_HOSTS_AND_CHANNELS_2026_10_02.md Phase 2). Empty
226 /// for a peer on a build from before it was advertised.
227 #[serde(default)] pub channel: String,
228 /// The peer's operating system (`windows`, `macos`, `linux`), for the
229 /// platform tag in the Swarm. Display only; empty for a peer that does not
230 /// advertise it (SPEC_SWARM_REMOTE_AGENTS_PLATFORM_TAG_AND_SELECTION_2026_10_03.md §3).
231 #[serde(default)] pub os: String,
232 /// The install's WAN instance id as the peer advertises it, a well-formed one only; empty for a peer that predates it. An identifier, never proof (`peer_words::install_id_token`).
233 #[serde(default)] #[ts(skip)] pub install_id: String,
234 /// How the peer is installed (`InstallKind::label`, e.g. `windows-store`); empty when it predates advertising it.
235 #[serde(default)] pub install: String,
236 /// The kind of build the peer says its binary is (`BuildKind::label`), never read off its channel; empty when it predates advertising it.
237 #[serde(default)] pub build: String,
238 pub address: String,
239 pub port: u16,
240 /// The peer's `lan_key`; never serialized, as no reader of the JSON needs it.
241 #[serde(skip_serializing, default)]
242 #[ts(skip)]
243 pub auth_key: String,
244 pub agents: Vec<String>,
245 /// Each listed agent's state and summary line as the peer reported them, by
246 /// lower-cased name (`lan/discovery/agent_names.rs`). Self-reported, for the Swarm.
247 #[serde(default)]
248 pub agent_status: BTreeMap<String, AgentState>,
249 #[serde(default)]
250 pub agent_lines: BTreeMap<String, String>,
251 /// Each listed agent's provider id, a known one only (`agent_names.rs`).
252 #[serde(default)]
253 pub agent_providers: BTreeMap<String, String>,
254 /// Each listed agent's runtime, `host` or `container`, as the peer reported it (`agent_names.rs`).
255 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
256 #[ts(as = "Option<BTreeMap<String, crate::backend::runtime_adapter::RuntimeKind>>", optional)]
257 pub agent_kinds: BTreeMap<String, crate::backend::runtime_adapter::RuntimeKind>,
258 /// Each listed agent's account, as the peer's stable account id (`agent_names.rs`,
259 /// SPEC_AGENTS_OPERATE_OTHER_MACHINES_2026_10_30.md §4.4). Omitted when none has one.
260 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
261 #[ts(as = "Option<BTreeMap<String, String>>", optional)]
262 pub agent_accounts: BTreeMap<String, String>,
263 /// Each limited agent's reset time (unix ms) as the peer reported it (`agent_names.rs`); omitted when none.
264 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
265 #[ts(as = "Option<BTreeMap<String, f64>>", optional)]
266 pub agent_resets: BTreeMap<String, u64>,
267 /// Each listed agent's seat as the peer reported it, by lower-cased name
268 /// (`agent_names.rs`; SPEC_AGENT_SEATS_IN_THE_UI_2026_10_23.md §5).
269 /// Omitted when none has one.
270 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
271 #[ts(as = "Option<BTreeMap<String, crate::backend::rpc_types::SeatSummary>>", optional)]
272 pub agent_seats: BTreeMap<String, crate::backend::rpc_types::SeatSummary>,
273 #[ts(type = "number")]
274 pub first_seen: u64,
275 #[ts(type = "number")]
276 pub last_seen: u64,
277 /// Unix seconds of the last answered agent-name poll, 0 for never. The Swarm
278 /// judges liveness by the later of this and `last_seen` (mDNS re-resolves only).
279 #[serde(default)]
280 #[ts(type = "number")]
281 pub last_polled_ok: u64,
282 /// This peer's advertised PTR/TXT record TTL (seconds) at its latest
283 /// `ServiceResolved` (`get_other_ttl()`); drives `peer_staleness_window_secs`.
284 pub other_ttl_secs: u32,
285}
286
287struct LanCacheEntry {
288 /// `None` = negative cache entry: agent is not on any LAN peer.
289 peer_url: Option<String>,
290 auth_key: String,
291 expires: std::time::Instant,
292}
293
294/// One in-flight `GET /agentmux/reactive/agent?id=…` against a single peer.
295type PeerQueryOutcome = (String, String, Result<reqwest::Response, reqwest::Error>);
296
297/// Query EVERY eligible LAN peer concurrently for `agent_id`, yielding results
298/// as they arrive.
299///
300/// Replaces the sequential `for peer in &peers { … .await }` both lookups used
301/// to run. That loop cost up to `LAN_PEER_QUERY_TIMEOUT_SECS × peer_count`
302/// before a message could be delivered — 10s across five peers — and the
303/// pathological ordering (a dead or slow peer ahead of the right one) is the
304/// common case on a laptop network where stale peers linger until their mDNS
305/// TTL expires. Fanning out makes the worst case ~one timeout regardless of
306/// peer count.
307///
308/// Returns a stream so each caller keeps its OWN acceptance rule: `find_agent`
309/// accepts any 2xx, while `find_agent_lan_pubkey` must keep trying after a 2xx
310/// whose body carries no `lan_public_key` (that peer hosts the agent but hasn't
311/// minted a key). A shared "first success wins" helper could not express both.
312///
313/// **Dropping the returned stream cancels every still-in-flight request** —
314/// so a caller that `break`s on the first acceptable answer stops paying for
315/// the rest, rather than merely ignoring them.
316fn query_peers_concurrently<'a>(
317 peers: &'a [LanInstance],
318 agent_id: &'a str,
319 http: &'a reqwest::Client,
320) -> futures_util::stream::FuturesUnordered<impl std::future::Future<Output = PeerQueryOutcome> + 'a> {
321 let futures = futures_util::stream::FuturesUnordered::new();
322 for peer in peers {
323 // Same eligibility rule the sequential loops used: a peer with no
324 // address or no scoped lan_key can't be queried at all.
325 if peer.address.is_empty() || peer.auth_key.is_empty() {
326 continue;
327 }
328 let peer_url = peer_base_url(&peer.address, peer.port);
329 let auth_key = peer.auth_key.clone();
330 futures.push(async move {
331 let result = http
332 .get(format!("{peer_url}/agentmux/reactive/agent"))
333 .query(&[("id", agent_id)])
334 .header(agentmux_common::AUTH_KEY_HEADER, &auth_key)
335 .timeout(std::time::Duration::from_secs(LAN_PEER_QUERY_TIMEOUT_SECS))
336 .send()
337 .await;
338 (peer_url, auth_key, result)
339 });
340 }
341 futures
342}
343
344/// Pure predicate behind `LanDiscovery::resolves_to_this_instance`, split out
345/// so it can be tested without standing up an mDNS `ServiceDaemon`.
346///
347/// `any` rather than `all` on the address match: a resolution for our own
348/// service can legitimately carry an address that interface enumeration missed
349/// (they race), and requiring every address to be ours would let that one
350/// stray entry resurrect the phantom. `any` cannot produce a false positive —
351/// combined with the port equality, a genuine remote peer would have to be
352/// listening on our port *at one of our own interface addresses*, which it
353/// cannot be. Another AgentMux instance on this same host does share our
354/// addresses, but never our port.
355fn is_self_resolution(
356 resolved_port: u16,
357 resolved_addrs: &[IpAddr],
358 own_port: u16,
359 own_addrs: &std::collections::HashSet<IpAddr>,
360) -> bool {
361 if resolved_port != own_port || own_addrs.is_empty() {
362 return false;
363 }
364 resolved_addrs.iter().any(|a| own_addrs.contains(a))
365}
366
367pub struct LanDiscovery {
368 daemon: ServiceDaemon,
369 instances: Arc<RwLock<HashMap<String, LanInstance>>>,
370 instance_id: String,
371 event_bus: Arc<EventBus>,
372 service_fullname: String,
373 auth_key: String,
374 hostname: String,
375 version: String,
376 port: u16,
377 /// Cancellation half for the UDP responder task spawned in `start()`.
378 /// `None` once `shutdown()` has fired. Set even if the UDP socket never
379 /// binds (`udp_responder_loop` then just exits, and `shutdown()`'s send
380 /// is a harmless no-op). Guarded by a sync mutex since
381 /// `shutdown()` is `&self` and called from both an explicit live-toggle
382 /// path and `Drop`.
383 udp_cancel: Mutex<Option<oneshot::Sender<()>>>,
384 /// Cancellation half for the desktop-to-desktop UDP discovery task
385 /// (`udp_peers`). Same contract as `udp_cancel`: the task holds its own
386 /// `Arc<LanDiscovery>`, so dropping the controller's Arc does not stop it.
387 udp_peer_cancel: Mutex<Option<oneshot::Sender<()>>>,
388 /// Cancels `agent_names_refresh_loop`. Needed for the same reason
389 /// `udp_cancel` is: that task holds its own `Arc<LanDiscovery>` clone, so
390 /// dropping the controller's Arc on `apply(false)` never reaches refcount
391 /// zero and the loop would otherwise keep issuing authenticated requests
392 /// to peers forever — leaking one orphaned task per disable/enable cycle.
393 agent_names_cancel: Mutex<Option<oneshot::Sender<()>>>,
394 /// Cancels `instance_record_loop`. Same contract as `udp_cancel`.
395 instance_record_cancel: Mutex<Option<oneshot::Sender<()>>>,
396 /// Where this instance's `lan_instances` record is written; `None` when
397 /// there is nowhere to write it (see `lan_instances::instances_dir`).
398 instances_dir: Option<std::path::PathBuf>,
399 /// `true` while the record may be (re)written; cleared for good by
400 /// `withdraw_instance_record`.
401 instance_record_live: Mutex<bool>,
402 /// IPv4 addresses `mdns-sd` reported announcing our service on, from its
403 /// monitor channel. An interface whose socket failed to bind never appears
404 /// here (see `lan::mdns_health`). Filled by `monitor_loop`.
405 announced_v4: Arc<Mutex<BTreeSet<Ipv4Addr>>>,
406 /// Whether the monitor channel was obtained. Without it `announced_v4` never
407 /// fills, so `health()` has no basis for a verdict and stays `Pending`.
408 monitored: bool,
409 /// When this daemon was built, for the start-up grace in `health()`.
410 started_at: std::time::Instant,
411}
412
413/// The mDNS *host record* (the A/AAAA name) this instance announces its addresses under: the instance label plus
414/// the `.local.` suffix mdns-sd's `ServiceInfo::new` requires.
415///
416/// It must be unique per instance, like the service name. It used to be the bare OS hostname, so two instances on
417/// one host (a Store copy next to a portable one) both claimed `<host>.local.`. mdns-sd then probed, saw the other
418/// instance's record as a conflict, and renamed the host (`<host>-2.local.`) over and over; the IPv6 link-local
419/// interfaces announced at once but the IPv4 ones only after ~30 s, past the watchdog's grace, which rebuilt the
420/// daemon without ever finishing ("mDNS announced on none of this host's IPv4 addresses"). A record named by
421/// `mdns_instance_label` has nothing to conflict with on the same host.
422fn mdns_host_record(hostname: &str, port: u16) -> String {
423 format!("{}.local.", mdns_instance_label(hostname, port))
424}
425
426/// Build this instance's DNS-SD *instance name* — the first label of the
427/// service fullname. Must be BOTH unique per running instance AND free of
428/// dots.
429///
430/// Both properties were violated before 2026-09-06, and together they broke
431/// LAN discovery outright between two hosts on the same build:
432///
433/// - **Not unique.** The name was `format!("agentmux-{instance_id}")`, and
434/// `instance_id` is the *version* (`config.rs`'s `args.instance`, which the
435/// launcher sets to e.g. `v0.55.37`). Every host on the same release
436/// therefore registered the identical name, and `handle_event`'s self-skip —
437/// which compares incoming fullnames against our own — discarded genuine
438/// peers as if they were us.
439/// - **Not a single label.** `v0.55.37` contains dots. In DNS-SD the instance
440/// name is ONE label and dots must be escaped; nothing escaped them, so
441/// mdns-sd split at the first dot, treated `agentmux-v0` as the label and
442/// `.55.37` as part of the service type. Observed verbatim in a peer's log
443/// as `agentmux-v0 (2).55.37._agentmux._tcp.local.` — note the conflict
444/// suffix landing mid-version-string.
445///
446/// The two compounded: the collision triggered mdns-sd's conflict-renaming,
447/// and because `service_fullname` was captured *before* `register()` (fixed
448/// alongside this), the renamed host kept a stale self-name that exactly
449/// matched the OTHER host's real name — so the renamed host silently dropped
450/// every announcement from its peer, permanently, with no self-heal. That is
451/// why discovery was observed to work in one direction only.
452///
453/// `hostname` + `port` is unique per instance (hostname per machine, port per
454/// srv on that machine) and carries no version, which is deliberate: a version
455/// does not belong in an identity key, and it was the version being in there
456/// that created the cross-host collision. Any character that isn't
457/// alphanumeric, `-` or `_` is replaced, so a FQDN hostname
458/// (`box.corp.example`) or an exotic one can't reintroduce the dot bug.
459fn mdns_instance_label(hostname: &str, port: u16) -> String {
460 let sanitized: String = hostname
461 .trim_end_matches('.')
462 .chars()
463 .map(|c| if c.is_ascii_alphanumeric() || c == '-' || c == '_' { c } else { '_' })
464 .collect();
465 // An empty/all-punctuation hostname would otherwise yield `agentmux--<port>`;
466 // the port alone still disambiguates instances on this host, and remote
467 // peers are disambiguated by address.
468 let host_part = if sanitized.is_empty() { "unknown".to_string() } else { sanitized };
469 // A DNS label is capped at 63 bytes. "agentmux-" (9) + "-" + a 5-digit port
470 // (6) leaves 48; truncate to 45 for headroom. Windows caps hostnames at 15
471 // but Linux allows 64, so this is reachable in practice, and an
472 // over-length label would be rejected or silently mangled rather than
473 // failing loudly [Manpo review, PR #3048].
474 let host_part: String = host_part.chars().take(45).collect();
475 // Residual collision: two hosts sharing BOTH hostname and port — e.g. two
476 // fresh VM clones that are each "ubuntu" — still produce the same label and
477 // will be conflict-renamed. That no longer blinds either host (the
478 // self-check requires port+address agreement, see `handle_event`), but the
479 // two do collapse into one peer-map entry with a flapping address. A
480 // persisted per-install random suffix would close it for good; not done
481 // here because it needs somewhere durable to live.
482 format!("agentmux-{host_part}-{port}")
483}
484
485impl LanDiscovery {
486 /// Start LAN discovery: register this instance and browse for peers.
487 pub fn start(
488 instance_id: String,
489 hostname: String,
490 version: String,
491 port: u16,
492 auth_key: String,
493 event_bus: Arc<EventBus>,
494 ) -> Result<Arc<Self>, String> {
495 let daemon = ServiceDaemon::new().map_err(|e| format!("mDNS daemon failed: {e}"))?;
496 // Taken before `register` so the registration's own announcement is not
497 // missed. Not fatal if unavailable: health then stays `Pending` and the
498 // watchdog never acts, which is the pre-existing behaviour.
499 let monitor = match daemon.monitor() {
500 Ok(rx) => Some(rx),
501 Err(e) => {
502 tracing::warn!("mDNS monitor unavailable, discoverability cannot be checked: {e}");
503 None
504 }
505 };
506 let announced_v4: Arc<Mutex<BTreeSet<Ipv4Addr>>> = Arc::new(Mutex::new(BTreeSet::new()));
507
508 // Register this instance. mdns-sd requires the host name passed to
509 // `ServiceInfo::new` to end with `.local.`; see `mdns_host_record` for why
510 // it is per instance and not the OS hostname.
511 // Unique per INSTANCE and dot-free — see `mdns_instance_label`. The
512 // version still travels in the TXT record (`instance_id` below), which
513 // is where peers actually read it from; it just must not be the
514 // identity key.
515 let service_name = mdns_instance_label(&hostname, port);
516 let host_name_mdns = mdns_host_record(&hostname, port);
517 let channel = crate::backend::reactive::registry::local_channel_id();
518 let os = crate::backend::host_os::local_os();
519 // Not `channels_running`: it changes, and a TXT update is costly; a
520 // peer reads it from the fleet feed instead.
521 let install_id = crate::backend::fleet_source::install_id();
522 let mut properties = vec![
523 ("version", version.as_str()),
524 ("hostname", hostname.as_str()),
525 ("instance_id", instance_id.as_str()),
526 ("channel", channel.as_str()),
527 ("os", os.as_str()), ("install", crate::backend::update::check::install_kind().label()), ("build", agentmux_common::build_kind::build_kind().label()),
528 ("auth_key", auth_key.as_str()),
529 ];
530 if let Some(id) = install_id.as_deref() {
531 properties.push(("install_id", id));
532 }
533 // `""` alone does NOT mean "auto-detect" despite how that reads —
534 // `AsIpAddrs for &str`'s own doc comment: "If the string is empty,
535 // will return an empty set." Auto-detection is a SEPARATE opt-in:
536 // `.enable_addr_auto()` tells the daemon to fill in (and keep
537 // updated) this service's addresses from the host's own interfaces.
538 // Without it, a service registered via `ServiceInfo::new(..., "",
539 // ...)` has zero addresses and `addr_auto: false` (the struct's
540 // hardcoded default) — `register()` still returns `Ok(())` (it just
541 // enqueues a `Command::Register`, no synchronous validation), so
542 // this silently produced a service that was never actually
543 // discoverable by ANY peer, not even another mDNS client on the same
544 // host. Caught by `a_registered_instance_is_discoverable_by_an_
545 // independent_mdns_client` below.
546 let service_info = ServiceInfo::new(
547 SERVICE_TYPE,
548 &service_name,
549 &host_name_mdns,
550 "",
551 port,
552 &properties[..],
553 )
554 .map_err(|e| format!("ServiceInfo creation failed: {e}"))?
555 .enable_addr_auto();
556
557 let service_fullname = service_info.get_fullname().to_string();
558
559 daemon
560 .register(service_info)
561 .map_err(|e| format!("mDNS register failed: {e}"))?;
562
563 // Log the name we registered under. Before this, an affected host was
564 // mute: the ONLY site that logged a fullname was the `ServiceRemoved`
565 // branch, so a host that discovered nothing (the exact failure this
566 // commit fixes) could not self-report its own service name at all, and
567 // the bug had to be diagnosed from the *peer's* log. `service_fullname`
568 // is the pre-register name — if mdns-sd ever conflict-renames us it
569 // will differ from what is actually on the wire, which is itself worth
570 // seeing, and is why the self-check below no longer trusts it alone.
571 tracing::info!(
572 service_fullname = %service_fullname,
573 instance_id = %instance_id,
574 port,
575 "LAN discovery registered mDNS service"
576 );
577
578 // Browse for peers — keep the receiver for the event loop
579 let browse_receiver = daemon
580 .browse(SERVICE_TYPE)
581 .map_err(|e| format!("mDNS browse failed: {e}"))?;
582
583 let instances = Arc::new(RwLock::new(HashMap::new()));
584
585 let discovery = Arc::new(Self {
586 daemon,
587 instances: instances.clone(),
588 instance_id: instance_id.clone(),
589 event_bus: event_bus.clone(),
590 service_fullname,
591 auth_key,
592 hostname,
593 version,
594 port,
595 udp_cancel: Mutex::new(None),
596 udp_peer_cancel: Mutex::new(None),
597 agent_names_cancel: Mutex::new(None),
598 instance_record_cancel: Mutex::new(None),
599 instances_dir: lan_instances::instances_dir(),
600 instance_record_live: Mutex::new(true),
601 announced_v4: announced_v4.clone(),
602 monitored: monitor.is_some(),
603 started_at: std::time::Instant::now(),
604 });
605
606 if let Some(rx) = monitor {
607 tokio::task::spawn_blocking(move || monitor_loop(rx, announced_v4));
608 }
609
610 // Spawn event receiver on a blocking thread to avoid starving the tokio runtime
611 let disc = discovery.clone();
612 tokio::task::spawn_blocking(move || {
613 disc.event_loop(browse_receiver);
614 });
615
616 // Spawn the UDP broadcast-probe responder (Layer 2 fallback for
617 // filtered mDNS). `UdpSocket::recv_from` is natively async, so this
618 // uses `tokio::spawn` (not `spawn_blocking`, unlike the mdns-sd event
619 // loop above whose receiver is a sync channel).
620 let (cancel_tx, cancel_rx) = oneshot::channel();
621 *discovery.udp_cancel.lock() = Some(cancel_tx);
622 let disc_udp = discovery.clone();
623 tokio::spawn(async move {
624 disc_udp.udp_responder_loop(cancel_rx).await;
625 });
626
627 // Desktop-to-desktop discovery that does not depend on mDNS: probes the
628 // LAN by broadcast and records who answers (`udp_peers`). Started
629 // whenever LAN discovery is, so a host whose mDNS is blocked or
630 // contested still finds, and is found by, its peers.
631 let (peer_cancel_tx, peer_cancel_rx) = oneshot::channel();
632 *discovery.udp_peer_cancel.lock() = Some(peer_cancel_tx);
633 tokio::spawn(discovery.clone().udp_peer_loop(peer_cancel_rx));
634
635 // Keeps each peer's `agents` list populated (see
636 // `agent_names_refresh_loop`). Cancelled explicitly by `shutdown()`
637 // via its own oneshot — NOT by Arc drop, since this task holds its
638 // own clone and would otherwise outlive `apply(false)` forever.
639 let (names_cancel_tx, names_cancel_rx) = oneshot::channel();
640 *discovery.agent_names_cancel.lock() = Some(names_cancel_tx);
641 tokio::spawn(
642 discovery
643 .clone()
644 .agent_names_refresh_loop(names_cancel_rx),
645 );
646
647 // Lists this instance as a sibling for whichever channel on this host
648 // holds the UDP probe port (`lan_instances`). Written now, then kept
649 // fresh; `shutdown()` withdraws it.
650 discovery.publish_instance_record();
651 let (record_cancel_tx, record_cancel_rx) = oneshot::channel();
652 *discovery.instance_record_cancel.lock() = Some(record_cancel_tx);
653 tokio::spawn(discovery.clone().instance_record_loop(record_cancel_rx));
654
655 tracing::info!(
656 instance_id = %instance_id,
657 port = port,
658 "LAN discovery started (mDNS)"
659 );
660
661 Ok(discovery)
662 }
663
664 /// Periodically ask every known peer which agents it hosts, so
665 /// `LanInstance::agents` reflects reality instead of staying the empty
666 /// vec it's created with. Without this, a peer shows up with a correct
667 /// hostname/version/address but `agents: []`, so there is no way to
668 /// discover *which* agents live on another machine — you can only
669 /// address one blind by name and hope. See
670 /// `handle_reactive_agent_names`' doc comment for the security scoping
671 /// of the endpoint this calls (names only, `lan_key`-readable).
672 ///
673 /// Failures are deliberately non-destructive: a peer that's briefly
674 /// unreachable keeps its last-known list rather than being blanked, since
675 /// staleness is already tracked by `last_seen` and a flapping list is
676 /// worse than a slightly-old one.
677 async fn agent_names_refresh_loop(self: Arc<Self>, mut cancel: oneshot::Receiver<()>) {
678 let http = match crate::http_client::builder()
679 .timeout(std::time::Duration::from_secs(LAN_PEER_QUERY_TIMEOUT_SECS))
680 .build()
681 {
682 Ok(c) => c,
683 Err(e) => {
684 tracing::warn!(error = %e, "LAN agent-name refresh disabled: HTTP client build failed");
685 return;
686 }
687 };
688
689 loop {
690 // Cancellation is checked at the sleep, not just between
691 // iterations: this task holds its own `Arc<LanDiscovery>`, so
692 // without an explicit signal `apply(false)` cannot stop it and it
693 // would keep hitting peers indefinitely (one leaked task per
694 // toggle cycle).
695 tokio::select! {
696 _ = tokio::time::sleep(std::time::Duration::from_secs(
697 LAN_AGENT_NAMES_REFRESH_SECS,
698 )) => {}
699 _ = &mut cancel => {
700 tracing::debug!("LAN agent-name refresh loop cancelled");
701 return;
702 }
703 }
704
705 // Garbage-collect entries `get_instances()` would already hide as
706 // stale. This is the only place `self.instances` actually shrinks
707 // now that `ServiceRemoved` no longer deletes (see
708 // `peer_staleness_window_secs`) — without it a genuinely departed
709 // peer would sit in the map forever and this very loop would keep
710 // polling it every cycle.
711 let any_pruned = {
712 let now = agentmux_common::time::now_secs_u64();
713 let mut instances = self.instances.write();
714 let before = instances.len();
715 instances.retain(|_, inst| now.saturating_sub(inst.last_seen) <= peer_staleness_window_secs(inst.other_ttl_secs));
716 one_per_instance::drop_superseded(&mut instances);
717 instances.len() != before
718 };
719 // A connected frontend only updates `lanInstancesAtom` on a
720 // `laninstances` WS event — without this, a peer pruned here
721 // would keep showing in an already-open client until some
722 // unrelated ServiceResolved happened to fire a broadcast
723 // [Codex P1 on PR #3245].
724 if any_pruned {
725 self.broadcast_instances();
726 }
727
728 // Snapshot (key, url, lan_key) so the lock is not held across any
729 // await — the map is read by every inject/discovery call.
730 let targets: Vec<(String, String, String)> = {
731 let instances = self.instances.read();
732 instances
733 .iter()
734 .map(|(key, inst)| {
735 (
736 key.clone(),
737 peer_base_url(&inst.address, inst.port),
738 inst.auth_key.clone(),
739 )
740 })
741 .collect()
742 };
743
744 // Fan out concurrently, same pattern as `query_peers_concurrently`
745 // — sequential awaits here would let N stale/unreachable peers
746 // each burn their full LAN_PEER_QUERY_TIMEOUT_SECS in turn
747 // (Codex P2 on PR #3102), stretching the nominal 30s refresh
748 // interval by however many peers are currently slow to answer.
749 let outcomes: Vec<(String, Option<PeerAgents>)> = {
750 use futures_util::StreamExt as _;
751 let http_ref = &http;
752 let mut inflight = futures_util::stream::FuturesUnordered::new();
753 for (key, base_url, lan_key) in &targets {
754 inflight.push(async move {
755 (
756 key.clone(),
757 Self::fetch_peer_agent_names(http_ref, base_url, lan_key).await,
758 )
759 });
760 }
761 let mut out = Vec::with_capacity(targets.len());
762 while let Some(item) = inflight.next().await {
763 out.push(item);
764 }
765 out
766 };
767
768 // Only broadcast `laninstances` when something actually changed
769 // (Codex P2 on PR #3102) — otherwise the display-oriented point
770 // of this loop is defeated: without this, a refresh that DOES
771 // find new names still leaves connected clients showing the
772 // stale `agents: []` from first mDNS resolution until some
773 // unrelated, unsynchronized mDNS event happens to fire.
774 let mut changed = false;
775 {
776 let mut instances = self.instances.write();
777 for (key, peer) in outcomes {
778 if let Some(entry) = instances.get_mut(&key) {
779 let now = agentmux_common::time::now_secs_u64();
780 changed |= agent_names::apply_agent_names_poll(entry, peer, now);
781 }
782 }
783 }
784 if changed {
785 self.broadcast_instances();
786 }
787 }
788 }
789
790 /// One peer's contribution to `agent_names_refresh_loop`. Returns `None`
791 /// on any failure (unreachable, non-2xx, oversized, or malformed body) —
792 /// this list is display-only, so a bad peer response should leave the
793 /// last-known list in place rather than blank it (see the loop's own
794 /// "non-destructive" framing).
795 async fn fetch_peer_agent_names(
796 http: &reqwest::Client,
797 base_url: &str,
798 lan_key: &str,
799 ) -> Option<PeerAgents> {
800 let url = format!("{base_url}/agentmux/reactive/agent-names");
801 let resp = match http.get(&url).header(agentmux_common::AUTH_KEY_HEADER, lan_key).send().await {
802 Ok(r) => r,
803 Err(e) => {
804 tracing::debug!(peer = %base_url, error = %e, "LAN agent-name refresh: unreachable");
805 return None;
806 }
807 };
808 if !resp.status().is_success() {
809 // A peer running a build without this route answers 404 —
810 // expected during a rolling upgrade, not an error.
811 tracing::debug!(peer = %base_url, status = %resp.status(), "LAN agent-name refresh: non-2xx");
812 return None;
813 }
814
815 let body = match Self::read_body_capped(resp, LAN_AGENT_NAMES_MAX_RESPONSE_BYTES).await {
816 Ok(b) => b,
817 Err(e) => {
818 tracing::warn!(peer = %base_url, error = %e, "LAN agent-name refresh: response too large, discarded");
819 return None;
820 }
821 };
822
823 let value: serde_json::Value = match serde_json::from_slice(&body) {
824 Ok(v) => v,
825 Err(e) => {
826 tracing::debug!(peer = %base_url, error = %e, "LAN agent-name refresh: bad JSON");
827 return None;
828 }
829 };
830
831 Some(parse_agent_names_body(&value))
832 }
833
834 /// Reads an HTTP response body up to `max_bytes`, erroring out as soon as
835 /// the cap is exceeded rather than buffering the full body first —
836 /// `Response::bytes()`/`.json()` have no size limit of their own, so a
837 /// peer that responds successfully but with an enormous body would
838 /// otherwise be read into memory in full before this code ever gets a
839 /// chance to reject it.
840 pub(crate) async fn read_body_capped(
841 mut resp: reqwest::Response,
842 max_bytes: usize,
843 ) -> Result<Vec<u8>, String> {
844 let mut buf = Vec::new();
845 while let Some(chunk) = resp.chunk().await.map_err(|e| e.to_string())? {
846 buf.extend_from_slice(&chunk);
847 if buf.len() > max_bytes {
848 return Err(format!("response exceeded {max_bytes}-byte cap"));
849 }
850 }
851 Ok(buf)
852 }
853
854 /// Build the JSON identity payload for this instance — see
855 /// `probe_response_json` for the pure field-assembly logic shared with
856 /// tests. Desktop peers get this (`udp_peers`); phones get
857 /// [`Self::build_probe_response`].
858 fn build_identity_response(&self) -> serde_json::Value {
859 self.identity_response_with(
860 crate::backend::fleet_source::install_id().as_deref(),
861 crate::backend::fleet_source::latest_channels_running(),
862 crate::backend::viewer::advertised_viewer_port(),
863 )
864 }
865
866 /// [`Self::build_identity_response`] with the install id, channel count
867 /// and viewer port given, so a test needs no WAN identity or fleet feed.
868 fn identity_response_with(
869 &self,
870 install_id: Option<&str>,
871 channels_running: Option<u32>,
872 viewer_port: Option<u16>,
873 ) -> serde_json::Value {
874 let mut response = probe_response_json(
875 &self.instance_id,
876 &self.hostname,
877 &self.version,
878 self.port,
879 &self.auth_key,
880 );
881 // The channel, as the TXT record carries it, so a desktop that finds
882 // this instance over UDP can tell two channels on one host apart. An
883 // extra field: older parsers (mobile included) ignore it.
884 response["channel"] = json!(crate::backend::reactive::registry::local_channel_id());
885 response["os"] = json!(crate::backend::host_os::local_os()); response["install"] = json!(crate::backend::update::check::install_kind().label()); response["build"] = json!(agentmux_common::build_kind::build_kind().label());
886 // What a phone merges this install with its cloud record by, and how
887 // many channels this machine runs, shared on the LAN or not
888 // (agentmux-mobile's SPEC_FLEET_HOST_TAGS_AND_CLOUD_HOSTS_2026_10_06
889 // §5.3). Both only when known.
890 if let Some(id) = install_id {
891 response["install_id"] = json!(id);
892 }
893 if let Some(n) = channels_running {
894 response["channels_running"] = json!(n);
895 }
896 // The viewer listener's port while it is up, so a paired device finds
897 // it again after an address change (agentmux-mobile's
898 // SPEC_AGENT_STATUS_AND_LIVE_PANE_FEED_2026_10_07 §13.2).
899 if let Some(port) = viewer_port {
900 response["viewer_port"] = json!(port);
901 }
902 response
903 }
904
905 /// The 47891 reply: the identity payload plus `siblings`, the other
906 /// LAN-enabled channels on this host (`lan_instances`), kept within one
907 /// datagram (`lan_instances::MAX_REPLY_BYTES`). Each sibling carries its
908 /// own `lan_key`, which it already broadcasts over mDNS.
909 fn build_probe_response(&self) -> serde_json::Value {
910 self.probe_response_with(
911 crate::backend::fleet_source::install_id().as_deref(),
912 crate::backend::fleet_source::latest_channels_running(),
913 crate::backend::viewer::advertised_viewer_port(),
914 )
915 }
916
917 fn probe_response_with(
918 &self,
919 install_id: Option<&str>,
920 channels_running: Option<u32>,
921 viewer_port: Option<u16>,
922 ) -> serde_json::Value {
923 let mut response = self.identity_response_with(install_id, channels_running, viewer_port);
924 lan_instances::attach_siblings(&mut response, &self.sibling_entries(), lan_instances::MAX_REPLY_BYTES);
925 response
926 }
927
928 /// UDP broadcast-probe responder loop (Layer 2 discovery fallback).
929 ///
930 /// Binds `0.0.0.0:UDP_DISCOVERY_PORT` and answers valid probes from
931 /// private/link-local source addresses (see `is_lan_source`) with a
932 /// unicast response back to the sender's `recv_from` source address.
933 /// Deliberately does NOT set `SO_REUSEADDR`: this codebase supports
934 /// running multiple AgentMux instances on one host simultaneously, and
935 /// on Windows `SO_REUSEADDR` lets a second process silently steal a UDP
936 /// port already owned by another — an inappropriate risk for a socket
937 /// that hands out `auth_key`. If the bind fails (most likely because
938 /// another local instance already holds the port), this task retries
939 /// every `UDP_RESPONDER_RETRY` until it gets the port or is cancelled, so
940 /// the next LAN-enabled channel takes over when the holder stops. mDNS
941 /// discovery (already running via `event_loop`) is unaffected either way,
942 /// matching the "never fail `start()` over this" contract.
943 ///
944 /// We do not call `set_broadcast(true)`: that flag is only required to
945 /// *send* to a broadcast address, and this socket only receives (probes
946 /// arrive as broadcast/subnet-broadcast datagrams addressed to us, which
947 /// requires no special socket option on the receiving end) and replies
948 /// with a plain unicast send back to the probe's source address.
949 async fn udp_responder_loop(self: Arc<Self>, cancel_rx: oneshot::Receiver<()>) {
950 self.udp_responder_loop_on(UDP_DISCOVERY_PORT, UDP_RESPONDER_RETRY, cancel_rx)
951 .await;
952 }
953
954 /// [`Self::udp_responder_loop`] on a given port and retry interval, so a
955 /// test can drive the takeover without the production port.
956 async fn udp_responder_loop_on(
957 self: Arc<Self>,
958 port: u16,
959 retry_every: std::time::Duration,
960 mut cancel_rx: oneshot::Receiver<()>,
961 ) {
962 let mut retrying = false;
963 let socket = loop {
964 match UdpSocket::bind(("0.0.0.0", port)).await {
965 Ok(s) => break s,
966 Err(e) => {
967 // Logged once, not per attempt: a second channel on this
968 // host retries for as long as the holder runs.
969 if !retrying {
970 tracing::debug!(
971 port,
972 "UDP discovery responder waiting for the port (bind failed, likely \
973 another local instance holds it); retrying every {}s: {e}",
974 retry_every.as_secs()
975 );
976 retrying = true;
977 }
978 tokio::select! {
979 _ = tokio::time::sleep(retry_every) => {}
980 _ = &mut cancel_rx => {
981 tracing::debug!("UDP discovery responder stopping before it got the port");
982 return;
983 }
984 }
985 }
986 }
987 };
988
989 if retrying {
990 tracing::info!(port, "UDP discovery responder took over the probe port");
991 } else {
992 tracing::debug!(port, "UDP discovery responder listening");
993 }
994
995 let mut buf = [0u8; 1024];
996 loop {
997 tokio::select! {
998 _ = &mut cancel_rx => {
999 tracing::debug!("UDP discovery responder stopping");
1000 break;
1001 }
1002 result = socket.recv_from(&mut buf) => {
1003 match result {
1004 Ok((len, src)) => {
1005 // Noise (unrelated LAN UDP traffic, malformed
1006 // packets) is expected on a live network — do
1007 // not log per-packet above debug.
1008 if probe_version::declined(&socket, &buf[..len], src, &self.version).await { continue; }
1009 // Trust boundary: never hand out auth_key to a
1010 // source address outside the private/link-local
1011 // ranges, even if the packet is a well-formed
1012 // probe (see is_lan_source doc comment).
1013 if !is_lan_source(&src) {
1014 tracing::debug!(
1015 src = %src,
1016 "UDP discovery probe from non-LAN source, ignoring"
1017 );
1018 continue;
1019 }
1020 tracing::debug!(src = %src, "UDP discovery probe received");
1021 let response = self.build_probe_response();
1022 match serde_json::to_vec(&response) {
1023 Ok(payload) => {
1024 if let Err(e) = socket.send_to(&payload, src).await {
1025 tracing::debug!("UDP discovery response send failed: {e}");
1026 } else {
1027 tracing::debug!(src = %src, "UDP discovery probe answered");
1028 }
1029 }
1030 Err(e) => {
1031 tracing::debug!("UDP discovery response serialize failed: {e}");
1032 }
1033 }
1034 }
1035 Err(e) => {
1036 // A persistent OS-level error (e.g. Windows
1037 // WSAECONNRESET/10054 from an ICMP
1038 // port-unreachable triggered by our own prior
1039 // send_to) would otherwise spin this loop at
1040 // full CPU with no delay between retries.
1041 tracing::debug!("UDP discovery recv_from error: {e}");
1042 tokio::time::sleep(std::time::Duration::from_millis(200)).await;
1043 }
1044 }
1045 }
1046 }
1047 }
1048 }
1049
1050 fn event_loop(&self, receiver: mdns_sd::Receiver<ServiceEvent>) {
1051 loop {
1052 match receiver.recv() {
1053 Ok(event) => self.handle_event(event),
1054 Err(_) => {
1055 tracing::warn!("mDNS event receiver closed");
1056 break;
1057 }
1058 }
1059 }
1060 }
1061
1062 /// True when a resolved service is really this instance, reached over one
1063 /// of this host's own addresses.
1064 ///
1065 /// Both conditions are required. The port alone is far too weak (two hosts
1066 /// can land on the same ephemeral port), and an address alone is too weak
1067 /// while several AgentMux instances share a machine — but no remote peer
1068 /// can be listening on OUR port at an address that is OURS.
1069 fn resolves_to_this_instance(&self, info: &ServiceInfo) -> bool {
1070 // Port first, and BEFORE touching the address set. A resolution on a
1071 // different port cannot be us, and that is the overwhelmingly common
1072 // case (every genuine remote peer), so it must not pay for an address
1073 // lookup. Passing the set as an argument would defeat this — arguments
1074 // are evaluated eagerly, so the cheap check inside `is_self_resolution`
1075 // would come too late [reagent #3025 P2].
1076 if info.get_port() != self.port {
1077 return false;
1078 }
1079 let addrs: Vec<IpAddr> = info.get_addresses().iter().copied().collect();
1080 is_self_resolution(
1081 info.get_port(),
1082 &addrs,
1083 self.port,
1084 &crate::backend::lan::listeners::cached_local_addresses(),
1085 )
1086 }
1087
1088 fn handle_event(&self, event: ServiceEvent) {
1089 match event {
1090 ServiceEvent::ServiceResolved(info) => {
1091 let fullname = info.get_fullname().to_string();
1092
1093 // Skip self. Compared by `fullname` (deterministic from
1094 // `service_name`, set once at registration — see `start()`)
1095 // rather than the TXT-record `instance_id` property: on this
1096 // machine's own virtual/link-local interfaces (WSL/Hyper-V/
1097 // VPN adapters), `enable_addr_auto()` re-fires
1098 // `ServiceResolved` far more often than fresh TXT data
1099 // arrives — most of those events resolve with an empty TXT
1100 // record (confirmed via `LAN peer discovered` log: ~96% of
1101 // events for this instance's own addresses logged
1102 // `peer_id=""`). Comparing on `instance_id` alone meant a
1103 // blank-TXT self-resolution was never recognized as self and
1104 // was inserted as a phantom peer that could never self-heal
1105 // (see the instance_id-preservation fix below for why).
1106 // THE self-check. One test, and it is the only one: a service
1107 // on OUR port at an address belonging to THIS machine is us. A
1108 // genuine remote peer cannot satisfy both — it would have to be
1109 // reachable at one of our own interface addresses.
1110 //
1111 // There used to be a second, independent check above this one
1112 // comparing the resolved `fullname` against our own. It is gone
1113 // as of 2026-09-06, because it was actively harmful and,
1114 // once this check existed, entirely redundant (any event a
1115 // fullname match could legitimately skip is one this check
1116 // already skips — reagent P2 on PR #3048 caught that keeping it
1117 // as a conjunct left dead code that also bypassed the debug log
1118 // below).
1119 //
1120 // Why it was harmful, and the answer to a question the previous
1121 // revision of this comment recorded as unexplained ("Why the
1122 // fullname check misses them is not established — plausibly
1123 // mdns-sd conflict-renaming"): it WAS conflict-renaming. The
1124 // mDNS instance label used to be `agentmux-{instance_id}` where
1125 // `instance_id` is the VERSION, so every host on a release
1126 // registered the same name AND that name contained dots, which
1127 // is malformed for a single DNS-SD label. mdns-sd split it at
1128 // the first dot and conflict-renamed the loser
1129 // ("agentmux-v0 (2).55.37._agentmux._tcp.local."). Two
1130 // consequences: a genuine peer's fullname could equal ours
1131 // exactly, and on a renamed host `service_fullname` — captured
1132 // before `register()` — went stale and matched the peer that
1133 // WON the name. Either way that host silently dropped every
1134 // announcement from its peer, forever, reporting `lan: []`
1135 // while the peer saw it fine. `mdns_instance_label` now makes
1136 // the collision impossible; deleting the check makes the
1137 // consequence impossible even if a future naming scheme
1138 // regresses.
1139 //
1140 // The blank-TXT self-resolution storm the fullname check was
1141 // originally added for is still caught here: live logs showed
1142 // ~96% of resolution events for this instance's own
1143 // virtual/link-local addresses carrying an empty TXT record
1144 // (`peer_id=""`), all on this instance's own port at its own
1145 // addresses — so this check catches them on its own, which is
1146 // what made the fullname comparison redundant rather than
1147 // load-bearing.
1148 //
1149 // Cost of getting it wrong, and why it is worth being careful:
1150 // `find_agent` fans out concurrently to every known peer, so a
1151 // phantom self-entry spent a request per lookup asking
1152 // ourselves a question we had already answered locally.
1153 if self.resolves_to_this_instance(&info) {
1154 tracing::debug!(
1155 address = %info.get_addresses().iter().next().map(|a| a.to_string()).unwrap_or_default(),
1156 port = info.get_port(),
1157 "skipping mDNS resolution of this instance's own service"
1158 );
1159 return;
1160 }
1161
1162 let peer_id = info
1163 .get_property_val_str("instance_id")
1164 .unwrap_or_default()
1165 .to_string();
1166
1167 let now = agentmux_common::time::now_secs_u64();
1168
1169 let address = info
1170 .get_addresses()
1171 .iter()
1172 .find(|a| matches!(a, IpAddr::V4(_)))
1173 .or_else(|| info.get_addresses().iter().next())
1174 .map(|a| a.to_string())
1175 .unwrap_or_default();
1176
1177 let hostname = info
1178 .get_property_val_str("hostname")
1179 .unwrap_or_default()
1180 .to_string();
1181 let version = info
1182 .get_property_val_str("version")
1183 .unwrap_or_default()
1184 .to_string();
1185 let auth_key = info
1186 .get_property_val_str("auth_key")
1187 .unwrap_or_default()
1188 .to_string();
1189 let channel = info.get_property_val_str("channel").unwrap_or_default().to_string();
1190 // Self-reported by the peer, so only a plain token is kept.
1191 let (os, install, build, install_id) = crate::backend::lan::peer_words::advertised(&info);
1192 let other_ttl_secs = info.get_other_ttl();
1193
1194 let mut instances = self.instances.write();
1195 // Cloned for the log line below: `entry()` takes ownership of
1196 // the key, and the peer's service name is the field that makes
1197 // that line correlatable with the sender's own registration.
1198 let fullname_for_log = fullname.clone();
1199 let entry = instances.entry(fullname).or_insert_with(|| LanInstance {
1200 instance_id: peer_id.clone(),
1201 hostname: hostname.clone(),
1202 version: version.clone(),
1203 channel: channel.clone(),
1204 os: os.clone(), install: install.clone(), build: build.clone(), install_id: install_id.clone(),
1205 address: address.clone(),
1206 port: info.get_port(),
1207 auth_key: auth_key.clone(),
1208 agents: Vec::new(),
1209 agent_status: Default::default(),
1210 agent_lines: Default::default(),
1211 agent_providers: Default::default(), agent_kinds: Default::default(),
1212 agent_accounts: Default::default(),
1213 agent_resets: Default::default(),
1214 agent_seats: Default::default(),
1215 first_seen: now,
1216 last_seen: now,
1217 last_polled_ok: 0,
1218 other_ttl_secs,
1219 });
1220 entry.last_seen = now;
1221 entry.address = one_per_instance::keep_better_address(&entry.address, address);
1222 entry.port = info.get_port();
1223 // A record TTL, not TXT content — always present on a real
1224 // resolution (unlike hostname/version/auth_key below), so it's
1225 // safe to overwrite unconditionally the same as address/port.
1226 entry.other_ttl_secs = other_ttl_secs;
1227 // TXT-derived fields only: `enable_addr_auto()` re-fires
1228 // `ServiceResolved` on every interface/address change, and
1229 // most of those re-fires resolve with an empty TXT record
1230 // (see the self-skip comment above) — apply a value only
1231 // when this event actually carried one, so a stale re-fire
1232 // never erases previously-known-good peer identity. Address/
1233 // port come from the SRV/A record, not TXT, and are always
1234 // populated, so they're safe to overwrite unconditionally.
1235 if !peer_id.is_empty() {
1236 entry.instance_id = peer_id.clone();
1237 }
1238 crate::backend::lan::peer_words::keep_known(&mut entry.install, install); crate::backend::lan::peer_words::keep_known(&mut entry.build, build); crate::backend::lan::peer_words::keep_known(&mut entry.install_id, install_id);
1239 if !hostname.is_empty() {
1240 entry.hostname = hostname;
1241 }
1242 if !version.is_empty() {
1243 entry.version = version;
1244 }
1245 if !auth_key.is_empty() {
1246 entry.auth_key = auth_key;
1247 }
1248 if !channel.is_empty() {
1249 entry.channel = channel;
1250 }
1251 if !os.is_empty() {
1252 entry.os = os;
1253 }
1254 // The UDP route may have found this peer first; one entry per
1255 // peer, the mDNS one (udp_peers::merge_udp_peer is the converse).
1256 udp_peers::drop_udp_duplicates(&mut instances);
1257 drop(instances);
1258
1259 tracing::info!(
1260 peer_id = %peer_id,
1261 // The peer's own service name. Without it this line could
1262 // not be correlated with the sender's registration, which
1263 // is what made the 2026-09-06 collision take two hosts and
1264 // an ssh session to pin down [Manpo review, PR #3048].
1265 fullname = %fullname_for_log,
1266 address = %info.get_addresses().iter().next().map(|a| a.to_string()).unwrap_or_default(),
1267 port = info.get_port(),
1268 "LAN peer discovered"
1269 );
1270
1271 self.broadcast_instances();
1272 }
1273 ServiceEvent::ServiceRemoved(_, fullname) => {
1274 // Deliberately NOT deleted from `self.instances` here (see
1275 // `peer_staleness_window_secs`): a real departure and ordinary
1276 // TTL/interface churn look identical on the wire, and removing
1277 // throws away last-known-good TXT fields that a post-removal
1278 // re-resolution (almost always blank-TXT) can never restore.
1279 // `get_instances()` prunes on `last_seen` age instead, which
1280 // only advances on an actual `ServiceResolved`.
1281 tracing::debug!(
1282 fullname = %fullname,
1283 "mDNS ServiceRemoved received (not acted on; peer expires via last_seen staleness instead)"
1284 );
1285 }
1286 _ => {}
1287 }
1288 }
1289
1290 fn broadcast_instances(&self) {
1291 // Via `get_instances()`, not a raw map read, so a stale entry never
1292 // reaches the frontend over the live `laninstances` event when the
1293 // REST/RPC path (which calls the same method) would already hide it.
1294 let instances: Vec<LanInstance> = self.get_instances();
1295 self.event_bus.broadcast_event(&EventBus::typed_ws_event::<crate::backend::mps_events::LanInstances>(&LanInstanceList(instances), String::new()));
1296 }
1297
1298 /// Is this instance really announced on an IPv4 interface other machines
1299 /// can reach? `Pending` until the start-up grace has passed.
1300 pub fn health(&self) -> mdns_health::MdnsHealth {
1301 // Cheap exits first: no monitor, or still inside the grace.
1302 if !self.monitored || self.started_at.elapsed() < mdns_health::GRACE {
1303 return mdns_health::MdnsHealth::Pending;
1304 }
1305 // Grouped by interface: `mdns-sd` announces on one address per
1306 // interface and IP version, so an interface with two IPv4 addresses is
1307 // covered by either one (ReAgent P2 on #4148).
1308 let local = if_addrs::get_if_addrs()
1309 .unwrap_or_default()
1310 .into_iter()
1311 .map(|i| (i.name.clone(), i.ip()));
1312 let expected = mdns_health::expected_by_interface(local);
1313 let announced = self.announced_v4.lock().clone();
1314 mdns_health::verdict(self.monitored, self.started_at.elapsed(), &expected, &announced)
1315 }
1316
1317 /// Get current list of discovered LAN peers (excludes self), each instance once (`one_per_instance`).
1318 pub fn get_instances(&self) -> Vec<LanInstance> {
1319 one_per_instance(self.get_all_instances())
1320 }
1321
1322 /// Get peer count (excludes self).
1323 #[allow(dead_code)]
1324 pub fn peer_count(&self) -> usize {
1325 self.instances.read().len()
1326 }
1327
1328 /// Stop the mDNS daemon and the UDP broadcast-probe responder.
1329 ///
1330 /// The mDNS side synchronously closes the daemon socket (UDP:5353),
1331 /// causing the `browse_receiver` to return Err and the event-loop thread
1332 /// spawned by `start()` to exit. The UDP responder is stopped by firing
1333 /// its cancellation channel, which the `tokio::select!` in
1334 /// `udp_responder_loop` is racing against `recv_from` — this is what
1335 /// makes a live setting toggle actually stop responding to probes, not
1336 /// just stop the mDNS advertisement.
1337 ///
1338 /// Required for live-disable to actually stop discovery: both background
1339 /// tasks hold their own `Arc<Self>` clone, so simply dropping the
1340 /// controller's Arc never reaches refcount zero and `Drop` does not
1341 /// run. Callers must invoke `shutdown()` before clearing their Arc.
1342 /// Idempotent — safe to call from both the explicit path and `Drop`.
1343 pub fn shutdown(&self) {
1344 if let Some(tx) = self.udp_cancel.lock().take() {
1345 // Ignore send errors: an `Err` here just means the responder
1346 // task already exited on its own (e.g. the bind failed), which
1347 // is a no-op we're happy with.
1348 let _ = tx.send(());
1349 }
1350 if let Some(tx) = self.udp_peer_cancel.lock().take() {
1351 let _ = tx.send(());
1352 }
1353 // Same contract as `udp_cancel` above — and load-bearing rather than
1354 // tidy-up: the refresh task owns an `Arc<LanDiscovery>` clone, so
1355 // without this signal it survives `apply(false)` and keeps issuing
1356 // authenticated requests to LAN peers indefinitely.
1357 if let Some(tx) = self.agent_names_cancel.lock().take() {
1358 let _ = tx.send(());
1359 }
1360 if let Some(tx) = self.instance_record_cancel.lock().take() {
1361 let _ = tx.send(());
1362 }
1363 self.withdraw_instance_record();
1364 if let Err(e) = self.daemon.unregister(&self.service_fullname) {
1365 // Likely already unregistered; do not warn loudly.
1366 tracing::debug!("mDNS unregister returned: {e}");
1367 }
1368 if let Err(e) = self.daemon.shutdown() {
1369 tracing::debug!("mDNS daemon shutdown returned: {e}");
1370 }
1371 }
1372}
1373
1374impl Drop for LanDiscovery {
1375 fn drop(&mut self) {
1376 // Fallback path. Under normal live-toggle flow the controller calls
1377 // `shutdown()` explicitly; this only fires for process exit, when
1378 // the event-loop thread has already terminated and the final Arc
1379 // is being released.
1380 self.shutdown();
1381 }
1382}
1383
1384/// How often the watchdog looks at discoverability. Two consecutive
1385/// undiscoverable ticks are needed before a rebuild
1386/// (`mdns_health::STRIKES_BEFORE_REBUILD`).
1387const HEALTH_TICK: std::time::Duration = std::time::Duration::from_secs(15);
1388
1389/// Reads the daemon's monitor channel and records the IPv4 addresses it
1390/// announced our service on. Ends when the daemon shuts down (the channel
1391/// disconnects). Runs on a blocking thread, like the browse loop.
1392fn monitor_loop(
1393 rx: mdns_sd::Receiver<mdns_sd::DaemonEvent>,
1394 announced: Arc<Mutex<BTreeSet<Ipv4Addr>>>,
1395) {
1396 while let Ok(event) = rx.recv() {
1397 record_daemon_event(event, &announced);
1398 }
1399}
1400
1401/// Folds one daemon event into the set of IPv4 addresses we announced on.
1402fn record_daemon_event(event: mdns_sd::DaemonEvent, announced: &Mutex<BTreeSet<Ipv4Addr>>) {
1403 use mdns_sd::DaemonEvent;
1404 match event {
1405 DaemonEvent::Announce(_, addrs) => {
1406 let found = mdns_health::ipv4_in(&addrs);
1407 if !found.is_empty() {
1408 announced.lock().extend(found);
1409 }
1410 }
1411 DaemonEvent::IpDel(IpAddr::V4(gone)) => {
1412 announced.lock().remove(&gone);
1413 }
1414 DaemonEvent::Error(e) => {
1415 tracing::warn!("mDNS daemon error: {e}");
1416 }
1417 _ => {}
1418 }
1419}
1420
1421/// Controller for live start/stop of `LanDiscovery` in response to setting changes.
1422///
1423/// Owns the daemon slot plus the start arguments, so toggling
1424/// `network:lan_discovery` from the UI (or from an external edit of
1425/// `settings.json`) can start or stop the daemon without restarting the
1426/// process.
1427///
1428/// Spec: docs/specs/lan-discovery-toggle.md
1429pub struct LanDiscoveryController {
1430 slot: Arc<RwLock<Option<Arc<LanDiscovery>>>>,
1431 /// What the last `apply` asked for: LAN discovery should be running. Set
1432 /// under the slot's write lock, so it never disagrees with the slot for
1433 /// longer than one `apply`. It stays `true` when a start fails, which is how
1434 /// the watchdog tells "wanted but down" (retry) from "off" (leave alone).
1435 desired: std::sync::atomic::AtomicBool,
1436 instance_id: String,
1437 hostname: String,
1438 version: String,
1439 port: u16,
1440 auth_key: String,
1441 event_bus: Arc<EventBus>,
1442 /// Short-lived cache mapping agent_id → (peer_url, auth_key). Entries expire
1443 /// after LAN_AGENT_CACHE_TTL_SECS to handle agent migration between peers.
1444 agent_cache: std::sync::RwLock<HashMap<String, LanCacheEntry>>,
1445 /// Separate cache mapping agent_id → LAN Ed25519 public key bytes.
1446 /// SPEC_JEKT_LAN_TIER_SIGNING_2026_08_15.md §2.2 — deliberately its own
1447 /// map rather than folded into `agent_cache`: the two are keyed by the
1448 /// same agent_id but answer different questions ("which peer currently
1449 /// hosts this agent" churns on process restarts/migration; "what is
1450 /// this agent's public key" is effectively static for the agent's
1451 /// lifetime), and a lookup for one is not always paired with a lookup
1452 /// for the other (a message TO agent X needs `agent_cache`'s entry for
1453 /// X; verifying a message FROM agent Y needs `pubkey_cache`'s entry for
1454 /// Y — different agent_ids on the same inbound request).
1455 pubkey_cache: std::sync::RwLock<HashMap<String, LanPubkeyCacheEntry>>,
1456 /// reagentx P1 on the LAN signing PR: `find_agent_lan_pubkey`'s negative
1457 /// cache is keyed by agent_id, so a caller holding only the `lan_key`
1458 /// can force a fresh multi-peer fan-out on every single request just by
1459 /// sending a novel random `source_agent` each time — the cache never
1460 /// hits, and this expensive walk runs (in `verify_lan_signature`)
1461 /// BEFORE `Handler::inject_message`'s own rate limiter is ever reached.
1462 /// A simple global token bucket on the fan-out ITSELF (not per-agent_id
1463 /// — the abuse pattern is specifically about varying the id to dodge a
1464 /// per-id cache) bounds the damage regardless of how many distinct
1465 /// identities are probed.
1466 pubkey_lookup_limiter: std::sync::Mutex<LookupRateLimiter>,
1467 #[cfg(any(test, feature = "test-support"))]
1468 peers_for_test: std::sync::Mutex<Vec<LanInstance>>,
1469}
1470
1471struct LanPubkeyCacheEntry {
1472 /// `None` = negative cache entry: no peer has a LAN public key on file
1473 /// for this agent_id (never minted one, or genuinely unknown).
1474 public_key: Option<Vec<u8>>,
1475 /// Identity M4d-6: the UID and UID key from the same peer's answer, when
1476 /// it gave both.
1477 uid_key: Option<(String, Vec<u8>)>,
1478 /// The hosting install's certificate for the name key (`lan_cert`), when
1479 /// its answer had one (docs/specs/SPEC_LAN_KEY_CONTINUITY_2026_10_29.md).
1480 cert: Option<agentmux_common::jekt_sign::WanKeyRecord>,
1481 /// The agent's own signature that the certifying install hosts it (`lan_install_sig`), when the answer had one.
1482 install_sig: Option<String>,
1483 expires: std::time::Instant,
1484}
1485
1486/// Outcome of `find_agent_lan_pubkey`. Three states, not two — reagentx P0
1487/// follow-up on the LAN signing PR: collapsing "the lookup was skipped
1488/// (rate-limited)" into the same `None`/"not found" outcome as "genuinely
1489/// no peer has this key" let an attacker exhaust
1490/// `LAN_PUBKEY_LOOKUP_RATE_LIMIT` with junk lookups, then slip a forged
1491/// signature for a REAL agent's identity through as unverified (benign)
1492/// instead of a verification failure (forced sensitive). By the time this
1493/// function is ever called, `verify_lan_signature` has already confirmed a
1494/// `lan_sig` was actually presented — so "we didn't check" must be
1495/// distinguishable from "there was nothing to check."
1496pub enum LanPubkeyLookup {
1497 /// A peer has a public key on file for this agent_id.
1498 Found(Vec<u8>),
1499 /// No peer (that answered) has ever minted a LAN key for this agent_id
1500 /// — genuinely unknown sender, not a red flag on its own (same
1501 /// "unverified, not escalated" treatment self-declared senders already
1502 /// get elsewhere in this system).
1503 NotFound,
1504 /// The lookup was skipped by the rate limiter — unknown, NOT the same
1505 /// as `NotFound`. Callers verifying an actual signature attempt must
1506 /// treat this conservatively (as a failure), never as "nothing to
1507 /// check."
1508 RateLimited,
1509 /// No peer has a key for this name, and one says it is a slug its agent
1510 /// was renamed from, now going by the name given (`current_name`;
1511 /// `SPEC_FORK_SLUG_MIGRATION_2026_10_22.md` Phase 1). A former slug never
1512 /// signs, so a signature claiming it is a failure. Nothing from that
1513 /// answer is cached, under either name: the current name's key is found
1514 /// by a lookup of its own, under the usual pinning.
1515 Renamed(String),
1516}
1517
1518/// The name a peer's answer says `agent_id` now goes by (`current_name`), when
1519/// it is a valid agent id other than `agent_id`. Only ever reported, never
1520/// trusted: no key is cached under it.
1521fn renamed_to(agent_id: &str, body: &serde_json::Value) -> Option<String> {
1522 let current = body.get("current_name")?.as_str()?.trim();
1523 (agentmux_common::slug::is_agent_id(current) && !current.eq_ignore_ascii_case(agent_id)).then(|| current.to_string())
1524}
1525
1526/// Minimal token bucket, refilled once per second — same shape as
1527/// `backend::reactive::handler::RateLimiter`, duplicated locally rather
1528/// than widening that one's visibility across modules for a single caller.
1529struct LookupRateLimiter {
1530 tokens: u32,
1531 max_tokens: u32,
1532 last_refill: std::time::Instant,
1533}
1534
1535impl LookupRateLimiter {
1536 fn new(max_tokens: u32) -> Self {
1537 Self {
1538 tokens: max_tokens,
1539 max_tokens,
1540 last_refill: std::time::Instant::now(),
1541 }
1542 }
1543
1544 fn check(&mut self) -> bool {
1545 let now = std::time::Instant::now();
1546 if now.duration_since(self.last_refill) >= std::time::Duration::from_secs(1) {
1547 self.tokens = self.max_tokens;
1548 self.last_refill = now;
1549 }
1550 if self.tokens > 0 {
1551 self.tokens -= 1;
1552 true
1553 } else {
1554 false
1555 }
1556 }
1557}
1558
1559/// Fan-outs per second `find_agent_lan_pubkey` will perform before failing
1560/// closed (returning `None` without querying any peer). Generous for
1561/// legitimate traffic — LAN jekts to previously-unseen senders are rare
1562/// once agents have been talking a while, and the 60s positive/negative
1563/// cache absorbs repeat lookups for the SAME agent_id — while still
1564/// bounding the worst case to a small, fixed number of outbound requests
1565/// per second regardless of how many distinct agent_ids are probed.
1566const LAN_PUBKEY_LOOKUP_RATE_LIMIT: u32 = 10;
1567
1568impl LanDiscoveryController {
1569 pub fn new(
1570 instance_id: String,
1571 hostname: String,
1572 version: String,
1573 port: u16,
1574 event_bus: Arc<EventBus>,
1575 auth_key: String,
1576 ) -> Self {
1577 Self {
1578 slot: Arc::new(RwLock::new(None)),
1579 desired: std::sync::atomic::AtomicBool::new(false),
1580 instance_id,
1581 hostname,
1582 version,
1583 port,
1584 auth_key,
1585 event_bus,
1586 agent_cache: std::sync::RwLock::new(HashMap::new()),
1587 pubkey_cache: std::sync::RwLock::new(HashMap::new()),
1588 #[cfg(any(test, feature = "test-support"))]
1589 peers_for_test: Default::default(),
1590 pubkey_lookup_limiter: std::sync::Mutex::new(LookupRateLimiter::new(LAN_PUBKEY_LOOKUP_RATE_LIMIT)),
1591 }
1592 }
1593
1594 /// Query LAN peers for which one hosts `agent_id`. Returns `(peer_url,
1595 /// lan_key)` for the first peer that responds 2xx to the agent-lookup
1596 /// endpoint. Results — both positive and negative — are cached for
1597 /// `LAN_AGENT_CACHE_TTL_SECS` seconds to avoid a blocking peer fan-out on
1598 /// every inject for cloud-only agents.
1599 ///
1600 /// Security:
1601 /// the value broadcast in the mDNS TXT record / UDP probe response
1602 /// (`self.auth_key` field name kept for wire back-compat with older
1603 /// peer versions — see `Config::lan_key`'s doc comment) is now a
1604 /// separate, narrowly-scoped credential, NOT the instance's full-access
1605 /// `auth_key`. A passive LAN listener who captures it gets standing
1606 /// access to only the three LAN-forwarding routes
1607 /// (`lan_or_full_auth_middleware` in `server/mod.rs`) — not the full
1608 /// `/agentmux/service` surface this used to expose. Broadcasting
1609 /// *something* in cleartext to the LAN is still an accepted trade-off
1610 /// of this opt-in feature (mDNS/UDP have no confidentiality of their
1611 /// own); this change is about shrinking what a captured value is worth,
1612 /// not about hiding it in transit — see the spec's LAN P1-1 for the
1613 /// separate, not-yet-implemented "encrypt/authenticate the transport
1614 /// too" hardening.
1615 pub async fn find_agent(
1616 &self,
1617 agent_id: &str,
1618 http: &reqwest::Client,
1619 ) -> Option<(String, String)> {
1620 // Fast path: valid cache hit (positive or negative)
1621 if let Ok(cache) = self.agent_cache.read() {
1622 if let Some(e) = cache.get(agent_id) {
1623 if e.expires > std::time::Instant::now() {
1624 return e.peer_url.as_ref().map(|url| (url.clone(), e.auth_key.clone()));
1625 }
1626 }
1627 }
1628
1629 // Slow path: fan out to every peer CONCURRENTLY and take the first
1630 // 2xx. Use reqwest's .query() for safe percent-encoding of the
1631 // agent_id (handles spaces, &, =, #, etc.) — see
1632 // `query_peers_concurrently`, which also explains why this is a stream
1633 // rather than a first-success-wins helper.
1634 let peers = self.get_all_instances();
1635 {
1636 use futures_util::StreamExt as _;
1637 let mut inflight = query_peers_concurrently(&peers, agent_id, http);
1638 while let Some((peer_url, auth_key, result)) = inflight.next().await {
1639 if matches!(result, Ok(ref r) if r.status().is_success()) {
1640 tracing::debug!(agent_id, peer_url = %peer_url, "LAN agent found on peer");
1641 if let Ok(mut cache) = self.agent_cache.write() {
1642 cache.insert(
1643 agent_id.to_string(),
1644 LanCacheEntry {
1645 peer_url: Some(peer_url.clone()),
1646 auth_key: auth_key.clone(),
1647 expires: std::time::Instant::now()
1648 + std::time::Duration::from_secs(LAN_AGENT_CACHE_TTL_SECS),
1649 },
1650 );
1651 }
1652 // Dropping `inflight` here cancels the remaining requests.
1653 return Some((peer_url, auth_key));
1654 }
1655 }
1656 }
1657
1658 // No peer has this agent — write a negative cache entry so future
1659 // injects for cloud-only agents skip the full peer fan-out.
1660 if let Ok(mut cache) = self.agent_cache.write() {
1661 cache.insert(
1662 agent_id.to_string(),
1663 LanCacheEntry {
1664 peer_url: None,
1665 auth_key: String::new(),
1666 expires: std::time::Instant::now()
1667 + std::time::Duration::from_secs(LAN_AGENT_CACHE_TTL_SECS),
1668 },
1669 );
1670 }
1671 None
1672 }
1673
1674 /// Look up a claimed LAN sender's Ed25519 public key by fanning out to
1675 /// every discovered LAN peer, same query the target-agent lookup above
1676 /// makes (`GET /agentmux/reactive/agent?id=<agent_id>`, now extended —
1677 /// see `handle_reactive_agent` — to embed `lan_public_key` when the
1678 /// responding peer has minted one). A SEPARATE lookup from `find_agent`
1679 /// even though it hits the same endpoint: verifying an inbound message
1680 /// FROM agent Y needs Y's key, which is almost never the same agent_id
1681 /// as whatever THIS request's own target-agent lookup (if any) was for.
1682 ///
1683 /// Returns the raw decoded public key bytes, or `None` if no peer has
1684 /// one on file for this agent_id (cached negatively, same as
1685 /// `find_agent`'s "not found" case) — callers (`verify_lan_signature`)
1686 /// treat that identically to "no signature attempted": nothing to check
1687 /// against, not a red flag on its own.
1688 pub async fn find_agent_lan_pubkey(&self, agent_id: &str, http: &reqwest::Client) -> LanPubkeyLookup {
1689 if let Ok(cache) = self.pubkey_cache.read() {
1690 if let Some(e) = cache.get(agent_id) {
1691 if e.expires > std::time::Instant::now() {
1692 return match &e.public_key {
1693 Some(k) => LanPubkeyLookup::Found(k.clone()),
1694 None => LanPubkeyLookup::NotFound,
1695 };
1696 }
1697 }
1698 }
1699
1700 // reagentx P1: fail closed on the FAN-OUT (no outbound peer
1701 // queries) rather than let an attacker force unbounded network
1702 // traffic by varying agent_id on every request — see
1703 // LAN_PUBKEY_LOOKUP_RATE_LIMIT's doc comment. Returning
1704 // `RateLimited` here (reagentx P0 follow-up, NOT the same as
1705 // `NotFound`) is the point: by the time this function is called at
1706 // all, `verify_lan_signature` has already confirmed a `lan_sig` WAS
1707 // presented, so "we didn't check" must never collapse into the same
1708 // outcome as "genuinely nothing to check" — a caller could
1709 // otherwise exhaust this limiter with junk lookups, then slip a
1710 // forged signature for a REAL agent's identity through unverified
1711 // instead of forced-sensitive.
1712 if !self.pubkey_lookup_allowed() {
1713 tracing::debug!(agent_id, "LAN pubkey lookup rate-limited — skipping peer fan-out");
1714 return LanPubkeyLookup::RateLimited;
1715 }
1716
1717 // Concurrent fan-out, same as `find_agent` — but note the acceptance
1718 // rule differs: a 2xx whose body has no `lan_public_key` means that
1719 // peer hosts the agent but hasn't minted a key, so we must keep
1720 // consuming the stream rather than stopping at the first 2xx.
1721 self.pubkey_from_peers(&self.get_all_instances(), agent_id, http).await
1722 }
1723
1724 /// [`Self::find_agent_lan_pubkey`]'s fan-out over `peers`. A key is only
1725 /// ever cached under the name asked for.
1726 async fn pubkey_from_peers(&self, peers: &[LanInstance], agent_id: &str, http: &reqwest::Client) -> LanPubkeyLookup {
1727 let mut renamed = None;
1728 let mut answered = false;
1729 {
1730 use futures_util::StreamExt as _;
1731 let mut inflight = query_peers_concurrently(peers, agent_id, http);
1732 while let Some((peer_url, _auth_key, result)) = inflight.next().await {
1733 let Ok(resp) = result else { continue };
1734 // "No such agent" is an answer; a refusal (401, 429), a server
1735 // error or a body that is not JSON says nothing about the key.
1736 if resp.status() == reqwest::StatusCode::NOT_FOUND {
1737 answered = true;
1738 continue;
1739 }
1740 if !resp.status().is_success() {
1741 continue;
1742 }
1743 let Ok(body) = resp.json::<serde_json::Value>().await else { continue };
1744 answered = true;
1745 // A former slug: noted, and its key ignored. Another peer
1746 // may still answer for the name itself.
1747 if let Some(current) = renamed_to(agent_id, &body) {
1748 renamed = Some(current);
1749 continue;
1750 }
1751 use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};
1752 let Some(pubkey_b64) = body.get("lan_public_key").and_then(|v| v.as_str()) else {
1753 continue; // this peer has the agent but no LAN key minted for it yet
1754 };
1755 let Ok(pubkey_bytes) = BASE64.decode(pubkey_b64) else { continue };
1756 tracing::debug!(agent_id, peer_url = %peer_url, "LAN agent pubkey found on peer");
1757 let uid = body.get("uid").and_then(|v| v.as_str()).filter(|u| !u.is_empty());
1758 let uid_key = body.get("uid_public_key").and_then(|v| v.as_str()).and_then(|k| BASE64.decode(k).ok());
1759 let cert = body.get("lan_cert").and_then(|v| serde_json::from_value(v.clone()).ok());
1760 let install_sig = body.get("lan_install_sig").and_then(|v| v.as_str()).map(str::to_string);
1761 if let Ok(mut cache) = self.pubkey_cache.write() {
1762 cache.insert(
1763 agent_id.to_string(),
1764 LanPubkeyCacheEntry {
1765 public_key: Some(pubkey_bytes.clone()),
1766 uid_key: uid.zip(uid_key).map(|(u, k)| (u.to_string(), k)),
1767 cert,
1768 install_sig,
1769 expires: std::time::Instant::now()
1770 + std::time::Duration::from_secs(LAN_AGENT_CACHE_TTL_SECS),
1771 },
1772 );
1773 }
1774 // Dropping `inflight` here cancels the remaining requests.
1775 return LanPubkeyLookup::Found(pubkey_bytes);
1776 }
1777 }
1778 // Not cached: a repeat lookup asks again (rate-limited).
1779 if let Some(current) = renamed {
1780 return LanPubkeyLookup::Renamed(current);
1781 }
1782 // Peers that could not be reached say nothing about the key: only an
1783 // answered miss is cached.
1784 if let (true, Ok(mut cache)) = (answered, self.pubkey_cache.write()) {
1785 cache.insert(
1786 agent_id.to_string(),
1787 LanPubkeyCacheEntry {
1788 public_key: None,
1789 uid_key: None,
1790 cert: None,
1791 install_sig: None,
1792 expires: std::time::Instant::now()
1793 + std::time::Duration::from_secs(LAN_AGENT_CACHE_TTL_SECS),
1794 },
1795 );
1796 }
1797 LanPubkeyLookup::NotFound
1798 }
1799
1800 /// Cache a peer's answer for `agent_id` as `find_agent_lan_pubkey` would.
1801 #[cfg(any(test, feature = "test-support"))]
1802 pub fn seed_lan_pubkey_for_test(&self, agent_id: &str, public_key: Vec<u8>, uid_key: Option<(String, Vec<u8>)>) {
1803 self.pubkey_cache.write().unwrap().insert(
1804 agent_id.to_string(),
1805 LanPubkeyCacheEntry {
1806 public_key: Some(public_key),
1807 uid_key,
1808 cert: None,
1809 install_sig: None,
1810 expires: std::time::Instant::now() + std::time::Duration::from_secs(LAN_AGENT_CACHE_TTL_SECS),
1811 },
1812 );
1813 }
1814
1815 /// Evict a stale cache entry (e.g. after a forward to that peer failed).
1816 pub fn evict_agent(&self, agent_id: &str) {
1817 if let Ok(mut cache) = self.agent_cache.write() {
1818 cache.remove(agent_id);
1819 }
1820 }
1821
1822 /// Idempotent: starts the daemon when `enabled` and not running, stops it
1823 /// when `!enabled` and running. Re-entrant safe.
1824 ///
1825 /// Holds the slot's write lock for the entire check-and-modify transaction
1826 /// to avoid a TOCTOU race between the `is_running` read and the slot
1827 /// mutation. `apply()` is called from toggle clicks and setting writes —
1828 /// low frequency — so briefly blocking concurrent peer-list reads is
1829 /// acceptable. `LanDiscovery::start()` and `Drop` are both fast (mDNS
1830 /// daemon construction + service register/unregister are local socket ops).
1831 pub fn apply(&self, enabled: bool) {
1832 let mut slot = self.slot.write();
1833 self.desired.store(enabled, std::sync::atomic::Ordering::SeqCst);
1834 let is_running = slot.is_some();
1835 match (enabled, is_running) {
1836 (true, false) => {
1837 match self.start_daemon() {
1838 Ok(d) => {
1839 *slot = Some(d);
1840 tracing::info!("LAN discovery enabled via setting");
1841 }
1842 Err(e) => {
1843 tracing::warn!("LAN discovery start failed: {e}");
1844 // Surface to the UI so the user sees why the toggle
1845 // didn't take effect (e.g. Windows Firewall blocked).
1846 // `e` is already a String, but `.to_string()` is the
1847 // documented contract for the wire payload (frontend
1848 // reads `event.data.error` as a string).
1849 self.event_bus.broadcast_event(&EventBus::typed_ws_event::<crate::backend::mps_events::LanInstancesError>(&LanDiscoveryError { error: e.to_string() }, String::new()));
1850 }
1851 }
1852 }
1853 (false, true) => {
1854 // Explicitly shut down before dropping our Arc. The
1855 // spawn_blocking event-loop thread holds an `Arc<LanDiscovery>`
1856 // clone (see `start()` line ~94), so dropping the slot's Arc
1857 // alone does not reach refcount zero — `Drop` would never run
1858 // and the daemon would keep advertising/browsing. `shutdown()`
1859 // closes the mDNS socket synchronously, the receiver returns
1860 // Err, the event-loop exits, and the spawned thread releases
1861 // its Arc. `Drop`'s subsequent call to `shutdown()` is a
1862 // no-op (idempotent).
1863 if let Some(d) = slot.as_ref() {
1864 d.shutdown();
1865 }
1866 *slot = None;
1867 tracing::info!("LAN discovery disabled via setting");
1868 self.event_bus.broadcast_event(&EventBus::typed_ws_event::<crate::backend::mps_events::LanInstances>(&LanInstanceList(Vec::new()), String::new()));
1869 }
1870 _ => {}
1871 }
1872 }
1873
1874 fn start_daemon(&self) -> Result<Arc<LanDiscovery>, String> {
1875 // A started daemon registers on the real multicast group: a test that asked for LAN was listed as a fake peer by the AgentMux installed on the same machine.
1876 if cfg!(any(test, feature = "test-support")) { return Err("no mDNS daemon in a test build".to_string()); }
1877 LanDiscovery::start(self.instance_id.clone(), self.hostname.clone(), self.version.clone(), self.port, self.auth_key.clone(), self.event_bus.clone())
1878 }
1879
1880 /// Remove this instance's `lan_instances` record on clean process exit,
1881 /// when `LanDiscovery`'s own `Drop` may never run (its tasks hold `Arc`s).
1882 /// Leaves mDNS and the sockets alone; the process is going away.
1883 pub fn withdraw_instance_record(&self) {
1884 if let Some(d) = self.slot.read().as_ref() {
1885 d.withdraw_instance_record();
1886 }
1887 }
1888
1889 /// Should a daemon be running right now, per the last `apply`?
1890 pub fn is_wanted(&self) -> bool {
1891 self.desired.load(std::sync::atomic::Ordering::SeqCst)
1892 }
1893
1894 /// Start a daemon when one is wanted but none is running: the recovery for a
1895 /// rebuild whose new daemon failed to start (ReAgent P2 on #4148). Does
1896 /// nothing, and returns `false`, when LAN is not wanted or a daemon is
1897 /// already up, checked under the same write lock `apply` uses, so it cannot
1898 /// race a switch-off.
1899 pub fn restart_if_wanted(&self) -> bool {
1900 let mut slot = self.slot.write();
1901 if slot.is_some() || !self.is_wanted() {
1902 return false;
1903 }
1904 match self.start_daemon() {
1905 Ok(fresh) => {
1906 *slot = Some(fresh);
1907 // Clears the error a failed rebuild showed, and resets the peer list.
1908 self.event_bus.broadcast_event(&EventBus::typed_ws_event::<crate::backend::mps_events::LanInstances>(&LanInstanceList(Vec::new()), String::new()));
1909 tracing::info!("mDNS daemon restarted after a failed rebuild");
1910 true
1911 }
1912 Err(e) => {
1913 tracing::warn!("mDNS daemon restart failed: {e}");
1914 false
1915 }
1916 }
1917 }
1918
1919 /// Replace a RUNNING mDNS daemon with a fresh one, atomically.
1920 ///
1921 /// Only ever replaces: if no daemon is running (LAN was switched off, or the
1922 /// supervisor's `enabled && reachable` gate in `bootstrap/network.rs` stopped
1923 /// it) this does nothing and returns `false`, so a rebuild can never start
1924 /// advertising on its own. The whole swap happens under one write lock, so
1925 /// `apply(false)` from the supervisor cannot interleave between the stop and
1926 /// the start (ReAgent P1 on #4148). The first draft called `apply(false)` then
1927 /// `apply(true)`, which released the lock in between and would have restarted
1928 /// a daemon the setting had just turned off.
1929 pub fn rebuild(&self) -> bool {
1930 let mut slot = self.slot.write();
1931 let Some(old) = slot.take() else {
1932 return false;
1933 };
1934 old.shutdown();
1935 match self.start_daemon() {
1936 Ok(fresh) => {
1937 *slot = Some(fresh);
1938 // The peer list starts over with the new daemon.
1939 self.event_bus.broadcast_event(&EventBus::typed_ws_event::<crate::backend::mps_events::LanInstances>(&LanInstanceList(Vec::new()), String::new()));
1940 tracing::info!("mDNS daemon rebuilt");
1941 true
1942 }
1943 Err(e) => {
1944 tracing::warn!("mDNS daemon rebuild failed: {e}");
1945 self.event_bus.broadcast_event(&EventBus::typed_ws_event::<crate::backend::mps_events::LanInstancesError>(&LanDiscoveryError { error: e.to_string() }, String::new()));
1946 false
1947 }
1948 }
1949 }
1950
1951 /// The running daemon's discoverability, or `None` when LAN discovery is
1952 /// off or failed to start.
1953 pub fn health(&self) -> Option<mdns_health::MdnsHealth> {
1954 self.slot.read().as_ref().map(|d| d.health())
1955 }
1956
1957 /// Start the watchdog that notices an instance nobody can find and
1958 /// rebuilds its mDNS daemon, the same path as switching LAN off and on
1959 /// (which cleared the fault on Area54, SPEC_LAN_FIREWALL_SETUP 8.1). It
1960 /// also tells the frontend, via `laninstances:health`, so the indicator can
1961 /// say so: a host can see peers and still be invisible to them.
1962 pub fn spawn_health_watchdog(self: Arc<Self>) {
1963 tokio::spawn(async move {
1964 let mut watchdog = mdns_health::Watchdog::default();
1965 let mut last_sent: Option<(String, Vec<Ipv4Addr>, u32)> = None;
1966 let mut tick = tokio::time::interval(HEALTH_TICK);
1967 tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
1968 loop {
1969 tick.tick().await;
1970 let Some(health) = self.health().map(mdns_health::corrected) else {
1971 if self.is_wanted() {
1972 // Wanted but no daemon: a rebuild whose new daemon failed to
1973 // start. Retry, and keep the rebuild budget (no `reset`).
1974 if watchdog.observe_down() {
1975 self.restart_if_wanted();
1976 }
1977 continue;
1978 }
1979 watchdog.reset();
1980 // LAN went off: clear whatever the indicator was showing.
1981 if last_sent.as_ref().is_some_and(|(state, _, _)| state != "off") {
1982 self.publish_health("off", &[], 0);
1983 last_sent = Some(("off".to_string(), Vec::new(), 0));
1984 }
1985 continue;
1986 };
1987 let rebuilds_before = watchdog.rebuilds();
1988 match watchdog.observe(&health) {
1989 mdns_health::Action::Rebuild => {
1990 let missing = health.missing().to_vec();
1991 // Say WHY before rebuilding: replay the daemon's own socket set-up
1992 // on each address it failed to announce on, and name whoever holds
1993 // UDP 5353. `mdns-sd` knows, but only tells the log what it can, and
1994 // on Area54 this took several cloud round trips to find by hand.
1995 let probe_these = missing.clone();
1996 let diagnosis = tokio::task::spawn_blocking(move || mdns_diag::diagnose(&probe_these))
1997 .await
1998 .unwrap_or_else(|e| format!("the diagnosis did not run ({e})"));
1999 tracing::warn!(
2000 missing = ?missing,
2001 attempt = watchdog.rebuilds(),
2002 next_retry_secs = u64::from(watchdog.retry_in_ticks()) * HEALTH_TICK.as_secs(),
2003 %diagnosis,
2004 "mDNS announced on none of this host's IPv4 addresses, so other machines cannot find it; rebuilding the mDNS daemon"
2005 );
2006 self.rebuild();
2007 }
2008 mdns_health::Action::Nothing => {
2009 if matches!(health, mdns_health::MdnsHealth::Healthy) && rebuilds_before > 0 {
2010 tracing::info!(rebuilds = rebuilds_before, "mDNS is announced on this host's IPv4 addresses again");
2011 }
2012 if let mdns_health::MdnsHealth::Degraded { missing } = &health {
2013 // Logged once per change below, not per tick.
2014 if last_sent.as_ref().map(|(s, _, _)| s.as_str()) != Some("degraded") {
2015 tracing::warn!(
2016 ?missing,
2017 "mDNS announced on some of this host's IPv4 addresses but not these (often a virtual adapter)"
2018 );
2019 }
2020 }
2021 }
2022 }
2023 let sent = (
2024 health.wire_state().to_string(),
2025 health.missing().to_vec(),
2026 watchdog.rebuilds(),
2027 );
2028 // A standing problem is re-sent every tick so a window opened later
2029 // (or a reconnected WebSocket) learns of it; see `should_publish`.
2030 let changed = last_sent.as_ref() != Some(&sent);
2031 if mdns_health::should_publish(&health, changed) {
2032 self.publish_health(&sent.0, &sent.1, sent.2);
2033 last_sent = Some(sent);
2034 }
2035 }
2036 });
2037 }
2038
2039 fn publish_health(&self, state: &str, missing: &[Ipv4Addr], rebuilds: u32) {
2040 let health = LanDiscoverability {
2041 state: state.to_string(),
2042 missing: missing.iter().map(|a| a.to_string()).collect(),
2043 rebuilds,
2044 };
2045 self.event_bus.broadcast_event(&EventBus::typed_ws_event::<crate::backend::mps_events::LanInstancesHealth>(&health, String::new()));
2046 }
2047
2048 /// Read the current peer list. Returns empty when the daemon is not
2049 /// running (discovery disabled or start failed).
2050 pub fn get_instances(&self) -> Vec<LanInstance> {
2051 self.slot
2052 .read()
2053 .as_ref()
2054 .map(|d| d.get_instances())
2055 .unwrap_or_default()
2056 }
2057}
2058
2059#[cfg(test)]
2060mod tests {
2061 use super::{
2062 is_lan_source, is_valid_probe, mdns_host_record, probe_response_json, record_daemon_event,
2063 LanDiscovery, SERVICE_TYPE, UDP_PROBE_TYPE, UDP_PROTOCOL_VERSION, UDP_RESPONSE_TYPE,
2064 };
2065 use crate::backend::lan::mdns_health;
2066 use mdns_sd::ServiceEvent;
2067 use parking_lot::Mutex;
2068 use serde_json::json;
2069 use std::collections::BTreeSet;
2070 use std::net::{Ipv4Addr, SocketAddr};
2071 use std::sync::Arc;
2072 use tokio::net::UdpSocket;
2073
2074 #[test]
2075 fn is_lan_source_accepts_private_v4_ranges() {
2076 for addr in [
2077 "127.0.0.1:1234",
2078 "10.0.0.5:1234",
2079 "172.16.4.4:1234",
2080 "192.168.1.50:1234",
2081 "169.254.1.1:1234", // link-local / APIPA
2082 ] {
2083 let addr: SocketAddr = addr.parse().unwrap();
2084 assert!(is_lan_source(&addr), "{addr} should be treated as LAN");
2085 }
2086 }
2087
2088 #[test]
2089 fn is_lan_source_rejects_public_v4() {
2090 for addr in ["8.8.8.8:1234", "1.1.1.1:1234", "203.0.113.7:1234"] {
2091 let addr: SocketAddr = addr.parse().unwrap();
2092 assert!(!is_lan_source(&addr), "{addr} should NOT be treated as LAN");
2093 }
2094 }
2095
2096 #[test]
2097 fn is_lan_source_accepts_v6_loopback_and_local_ranges() {
2098 for addr in ["[::1]:1234", "[fe80::1]:1234", "[fc00::1]:1234"] {
2099 let addr: SocketAddr = addr.parse().unwrap();
2100 assert!(is_lan_source(&addr), "{addr} should be treated as LAN");
2101 }
2102 }
2103
2104 #[test]
2105 fn is_lan_source_rejects_public_v6() {
2106 let addr: SocketAddr = "[2001:4860:4860::8888]:1234".parse().unwrap();
2107 assert!(!is_lan_source(&addr));
2108 }
2109
2110 #[test]
2111 fn is_lan_source_unwraps_v4_mapped_v6() {
2112 // A private v4 address wearing a v6 mapped-address wrapper must
2113 // still be classified by its embedded v4 range, not treated as an
2114 // opaque public v6 address.
2115 let addr: SocketAddr = "[::ffff:10.0.0.5]:1234".parse().unwrap();
2116 assert!(is_lan_source(&addr));
2117 let addr: SocketAddr = "[::ffff:8.8.8.8]:1234".parse().unwrap();
2118 assert!(!is_lan_source(&addr));
2119 }
2120
2121 #[test]
2122 fn the_host_record_is_one_local_label_per_instance() {
2123 let record = mdns_host_record("narko", 29700);
2124 assert_eq!(record, "agentmux-narko-29700.local.");
2125 // One label under `.local.`, so mdns-sd does not read it as a sub-domain.
2126 assert_eq!(record.trim_end_matches(".local.").matches('.').count(), 0);
2127 }
2128
2129 #[test]
2130 fn two_instances_on_one_host_get_different_host_records() {
2131 // The Store copy (29703) next to the portable (29700) used to share `<host>.local.`.
2132 assert_ne!(mdns_host_record("Area54", 29700), mdns_host_record("Area54", 29703));
2133 }
2134
2135 #[test]
2136 fn the_host_record_label_fits_a_dns_label_for_any_hostname() {
2137 for host in ["", ".", "box.corp.example", &"h".repeat(200)] {
2138 let record = mdns_host_record(host, 65535);
2139 let label = record.strip_suffix(".local.").expect("ends in .local.");
2140 assert!(label.len() <= 63, "{record}");
2141 assert!(!label.contains('.'), "{record}");
2142 }
2143 }
2144
2145 // -- UDP broadcast-probe wire protocol (Layer 2 discovery fallback) --
2146
2147 #[test]
2148 fn is_valid_probe_accepts_well_formed_probe() {
2149 let bytes = serde_json::to_vec(&json!({"type": UDP_PROBE_TYPE, "v": 1})).unwrap();
2150 assert!(is_valid_probe(&bytes));
2151 }
2152
2153 #[test]
2154 fn is_valid_probe_rejects_non_json() {
2155 assert!(!is_valid_probe(b"not json at all"));
2156 }
2157
2158 #[test]
2159 fn is_valid_probe_rejects_wrong_type() {
2160 let bytes = serde_json::to_vec(&json!({"type": "something_else", "v": 1})).unwrap();
2161 assert!(!is_valid_probe(&bytes));
2162 }
2163
2164 #[test]
2165 fn is_valid_probe_rejects_wrong_version() {
2166 let bytes = serde_json::to_vec(&json!({"type": UDP_PROBE_TYPE, "v": 2})).unwrap();
2167 assert!(!is_valid_probe(&bytes));
2168 }
2169
2170 #[test]
2171 fn is_valid_probe_accepts_version_encoded_as_float() {
2172 // A client whose JSON serializer infers a `double` type for the
2173 // version field emits `1.0` rather than `1` — both must validate.
2174 let bytes = serde_json::to_vec(&json!({"type": UDP_PROBE_TYPE, "v": 1.0})).unwrap();
2175 assert!(is_valid_probe(&bytes));
2176 }
2177
2178 #[test]
2179 fn is_valid_probe_rejects_version_encoded_as_non_integral_float() {
2180 let bytes = serde_json::to_vec(&json!({"type": UDP_PROBE_TYPE, "v": 1.5})).unwrap();
2181 assert!(!is_valid_probe(&bytes));
2182 }
2183
2184 #[test]
2185 fn is_valid_probe_rejects_unrelated_json() {
2186 // Simulates non-AgentMux JSON noise landing on the port.
2187 let bytes = serde_json::to_vec(&json!({"hello": "world"})).unwrap();
2188 assert!(!is_valid_probe(&bytes));
2189 }
2190
2191 #[test]
2192 fn is_valid_probe_rejects_missing_version_field() {
2193 let bytes = serde_json::to_vec(&json!({"type": UDP_PROBE_TYPE})).unwrap();
2194 assert!(!is_valid_probe(&bytes));
2195 }
2196
2197 #[test]
2198 fn is_valid_probe_rejects_missing_type_field() {
2199 let bytes = serde_json::to_vec(&json!({"v": UDP_PROTOCOL_VERSION})).unwrap();
2200 assert!(!is_valid_probe(&bytes));
2201 }
2202
2203 #[test]
2204 fn probe_response_json_populates_all_fields() {
2205 let response = probe_response_json("inst-1", "myhost", "1.2.3", 9999, "secret-key");
2206 assert_eq!(response["type"], UDP_RESPONSE_TYPE);
2207 assert_eq!(response["v"], UDP_PROTOCOL_VERSION);
2208 assert_eq!(response["instance_id"], "inst-1");
2209 assert_eq!(response["hostname"], "myhost");
2210 assert_eq!(response["version"], "1.2.3");
2211 assert_eq!(response["port"], 9999);
2212 assert_eq!(response["auth_key"], "secret-key");
2213 }
2214
2215 // -- Real mDNS registration round-trip (reagent-style investigation:
2216 // LAN peer discovery was silently broken end-to-end — see below) --
2217
2218 /// Registers a real LanDiscovery instance (exactly as `start()` does in
2219 /// production) and browses for it with a SEPARATE, independent
2220 /// `mdns_sd::ServiceDaemon` — mirroring what a real peer's browse-side
2221 /// would see. This is the one test in this module that touches the real
2222 /// network stack (multicast on 5353) — it's slow (~3s) but it's the only
2223 /// way to catch a registration bug that a browse-only or probe-only unit
2224 /// test can't reach.
2225 ///
2226 /// This test is the reason the `""` (empty string) IP passed to
2227 /// `ServiceInfo::new` in `start()` was found to be broken: mdns-sd's own
2228 /// doc comment on `AsIpAddrs for &str` says plainly "If the string is
2229 /// empty, will return an empty set" — NOT "auto-detect". Combined with
2230 /// `ServiceInfo::new` hardcoding `addr_auto: false` and `start()` never
2231 /// calling the builder's `.enable_addr_auto()`, every registered service
2232 /// had zero addresses and no instruction to ever fill them in — it was
2233 /// never actually discoverable, not by a real peer, not even by another
2234 /// mDNS client on the SAME machine. `register()` itself has no
2235 /// synchronous validation for this (it just enqueues a `Command::
2236 /// Register` and returns `Ok`), so `start()` logged "LAN discovery
2237 /// started" successfully every time despite never actually working.
2238 ///
2239 /// IGNORED by default (opt in with `cargo test -- --ignored`) —
2240 /// confirmed environment-fragile in two independent, unrelated ways, not
2241 /// just "flaky CI networking":
2242 ///
2243 /// 1. GitHub Actions' `macos-latest` runner doesn't support UDP
2244 /// multicast at all: `mDNSResponder` is disabled there
2245 /// (actions/runner-images#9628) and macOS 15+ runners separately lack
2246 /// the "Local Network" permission sandboxed processes need for
2247 /// multicast (actions/runner-images discussion #170669). Confirmed
2248 /// deterministic (3/3 nightly runs), not intermittent.
2249 /// 2. Fails on real macOS hardware too, outside any CI — reproduced with
2250 /// a minimal from-scratch `mdns-sd` program (no AgentMux code at all)
2251 /// on a dev machine with several active VPN/tunnel interfaces: two
2252 /// `ServiceDaemon`s in the *same process*, both sharing port 5353
2253 /// with the OS's own `mDNSResponder`, and the browse side received
2254 /// zero packets — not even `ServiceFound`. The OS-level `dns-sd`
2255 /// CLI (two separate *processes*) discovers the identical
2256 /// registration instantly on the same machine, so this isn't a
2257 /// broken network or firewall; it's specific to same-process
2258 /// multi-`ServiceDaemon` port-5353 sharing in this crate.
2259 ///
2260 /// Both failure modes are outside this codebase's control (GitHub's
2261 /// runner sandboxing; mdns-sd's own same-process daemon behavior), so
2262 /// this stays a real, valuable, manually-run integration check —
2263 /// exactly how the bug above was actually caught — rather than
2264 /// something CI can gate on. See
2265 /// docs/retro/retro-macos-ci-mdns-multicast-unsupported-2026-08-12.md.
2266 #[tokio::test]
2267 #[ignore = "environment-fragile: real multicast, not gateable in GH Actions macOS CI \
2268 (no multicast support there) or reliably on multi-interface dev machines \
2269 (same-process ServiceDaemon port-5353 sharing) — see retro doc"]
2270 async fn a_registered_instance_is_discoverable_by_an_independent_mdns_client() {
2271 let event_bus = Arc::new(crate::backend::eventbus::EventBus::new());
2272 let instance_id = format!("test-{}", std::process::id());
2273 let discovery = LanDiscovery::start(
2274 instance_id.clone(),
2275 "test-host".to_string(),
2276 "0.0.0-test".to_string(),
2277 54321,
2278 "test-auth-key".to_string(),
2279 event_bus,
2280 )
2281 .expect("LanDiscovery::start should succeed");
2282
2283 // Independent daemon — a stand-in for a real peer's browse side.
2284 // Deliberately NOT the same ServiceDaemon `discovery` uses; a
2285 // same-process shortcut (e.g. reading `discovery`'s own in-memory
2286 // `instances` map) wouldn't exercise the actual wire announcement.
2287 let browser_daemon = mdns_sd::ServiceDaemon::new().expect("browser daemon");
2288 let receiver = browser_daemon.browse(SERVICE_TYPE).expect("browse");
2289
2290 let mut found = false;
2291 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
2292 while std::time::Instant::now() < deadline {
2293 if let Ok(event) = receiver.recv_timeout(std::time::Duration::from_millis(200)) {
2294 if let ServiceEvent::ServiceResolved(info) = event {
2295 if info.get_property_val_str("instance_id") == Some(instance_id.as_str()) {
2296 found = true;
2297 break;
2298 }
2299 }
2300 }
2301 }
2302
2303 let _ = browser_daemon.shutdown();
2304 discovery.shutdown();
2305
2306 assert!(
2307 found,
2308 "an independent mDNS client must be able to discover a freshly-registered LanDiscovery instance within 5s"
2309 );
2310 }
2311
2312 /// ReAgent P1 on #4148: a rebuild may only REPLACE a running daemon. With none
2313 /// running (LAN switched off, or the supervisor's `enabled && reachable` gate
2314 /// stopped it) it must do nothing, never start advertising on its own.
2315 #[tokio::test]
2316 async fn a_rebuild_never_starts_a_daemon_that_is_not_running() {
2317 let controller = super::LanDiscoveryController::new(
2318 "test-instance".to_string(),
2319 "test-host".to_string(),
2320 "0.0.0-test".to_string(),
2321 54323,
2322 Arc::new(crate::backend::eventbus::EventBus::new()),
2323 "test-key".to_string(),
2324 );
2325 assert!(controller.health().is_none());
2326 assert!(!controller.rebuild(), "nothing to rebuild");
2327 assert!(controller.health().is_none(), "and it must not have started one");
2328 assert!(controller.get_instances().is_empty());
2329
2330 // The same after LAN was on and has been switched off again.
2331 controller.apply(true);
2332 controller.apply(false);
2333 assert!(!controller.rebuild());
2334 assert!(controller.health().is_none());
2335 }
2336
2337 /// ReAgent P2 on #4148: the controller remembers that LAN is wanted even when
2338 /// the start failed, so the watchdog can retry; and it never restarts a
2339 /// daemon the setting has switched off.
2340 #[tokio::test]
2341 async fn a_restart_only_happens_while_lan_is_wanted() {
2342 let controller = super::LanDiscoveryController::new(
2343 "test-instance".to_string(),
2344 "test-host".to_string(),
2345 "0.0.0-test".to_string(),
2346 54324,
2347 Arc::new(crate::backend::eventbus::EventBus::new()),
2348 "test-key".to_string(),
2349 );
2350 assert!(!controller.is_wanted());
2351 assert!(!controller.restart_if_wanted(), "not wanted: nothing to restart");
2352 assert!(controller.health().is_none());
2353
2354 controller.apply(true); // wanted whether or not this host can start mDNS
2355 assert!(controller.is_wanted());
2356 controller.apply(false);
2357 assert!(!controller.is_wanted());
2358 assert!(!controller.restart_if_wanted(), "switched off again: must not restart");
2359 assert!(controller.health().is_none());
2360 }
2361
2362 /// The daemon's announcements, in the two payload shapes `mdns-sd` 0.12 uses,
2363 /// accumulate into the announced set, and an address that goes away leaves it.
2364 #[test]
2365 fn daemon_events_fold_into_the_announced_set() {
2366 use mdns_sd::DaemonEvent;
2367 let announced = Mutex::new(BTreeSet::new());
2368 record_daemon_event(
2369 DaemonEvent::Announce("a._agentmux._tcp.local.".into(), "[192.168.1.26, fe80::1]".into()),
2370 &announced,
2371 );
2372 record_daemon_event(
2373 DaemonEvent::Announce("a._agentmux._tcp.local.".into(), "Area54.local.:172.17.16.1".into()),
2374 &announced,
2375 );
2376 // Unrelated events change nothing.
2377 record_daemon_event(DaemonEvent::IpAdd("10.0.0.9".parse().unwrap()), &announced);
2378 record_daemon_event(DaemonEvent::Respond("192.168.1.26".parse().unwrap()), &announced);
2379 let want: BTreeSet<Ipv4Addr> = ["192.168.1.26", "172.17.16.1"].iter().map(|s| s.parse().unwrap()).collect();
2380 assert_eq!(*announced.lock(), want);
2381
2382 record_daemon_event(DaemonEvent::IpDel("172.17.16.1".parse().unwrap()), &announced);
2383 assert!(!announced.lock().contains(&"172.17.16.1".parse::<Ipv4Addr>().unwrap()));
2384 assert!(announced.lock().contains(&"192.168.1.26".parse::<Ipv4Addr>().unwrap()));
2385 }
2386
2387 /// Real daemon, real multicast: a freshly started instance must report itself
2388 /// announced on this host's IPv4 addresses. This is what proves the payload
2389 /// shape `ipv4_in` parses is the one the crate actually emits, and it is the
2390 /// check that would have failed on Area54. Manual, like the neighbouring
2391 /// test, for the same reason (CI has no reliable multicast).
2392 #[tokio::test]
2393 #[ignore = "real multicast: run by hand, e.g. `cargo test -p agentmux-srv-core -- --ignored a_started_instance_reports_itself_healthy`"]
2394 async fn a_started_instance_reports_itself_healthy() {
2395 let event_bus = Arc::new(crate::backend::eventbus::EventBus::new());
2396 let discovery = LanDiscovery::start(
2397 format!("health-{}", std::process::id()),
2398 "health-host".to_string(),
2399 "0.0.0-test".to_string(),
2400 54322,
2401 "test-auth-key".to_string(),
2402 event_bus,
2403 )
2404 .expect("LanDiscovery::start should succeed");
2405
2406 tokio::time::sleep(mdns_health::GRACE + std::time::Duration::from_secs(1)).await;
2407 let health = discovery.health();
2408 let announced = discovery.announced_v4.lock().clone();
2409 discovery.shutdown();
2410
2411 assert!(
2412 matches!(health, mdns_health::MdnsHealth::Healthy | mdns_health::MdnsHealth::Degraded { .. }),
2413 "a started instance must be announced on at least one IPv4 address; health={health:?} announced={announced:?}"
2414 );
2415 }
2416
2417 /// End-to-end probe/response round trip over real loopback sockets
2418 /// (ephemeral ports, NOT the fixed UDP_DISCOVERY_PORT — avoids CI port
2419 /// collisions and avoids needing a full `LanDiscovery` + real mDNS
2420 /// `ServiceDaemon` just to exercise the wire format). Exercises the same
2421 /// `is_valid_probe` / `probe_response_json` functions the production
2422 /// `udp_responder_loop` calls.
2423 #[tokio::test]
2424 async fn udp_probe_round_trip_returns_valid_response() {
2425 let responder = UdpSocket::bind("127.0.0.1:0").await.unwrap();
2426 let responder_addr = responder.local_addr().unwrap();
2427 let prober = UdpSocket::bind("127.0.0.1:0").await.unwrap();
2428
2429 let probe = json!({"type": UDP_PROBE_TYPE, "v": UDP_PROTOCOL_VERSION});
2430 prober
2431 .send_to(&serde_json::to_vec(&probe).unwrap(), responder_addr)
2432 .await
2433 .unwrap();
2434
2435 let mut buf = [0u8; 1024];
2436 let (len, src) = responder.recv_from(&mut buf).await.unwrap();
2437 assert!(is_valid_probe(&buf[..len]));
2438
2439 let response = probe_response_json("inst-1", "myhost", "1.2.3", 9999, "secret-key");
2440 responder
2441 .send_to(&serde_json::to_vec(&response).unwrap(), src)
2442 .await
2443 .unwrap();
2444
2445 let (len, _) = prober.recv_from(&mut buf).await.unwrap();
2446 let received: serde_json::Value = serde_json::from_slice(&buf[..len]).unwrap();
2447 assert_eq!(received["type"], UDP_RESPONSE_TYPE);
2448 assert_eq!(received["v"], UDP_PROTOCOL_VERSION);
2449 assert_eq!(received["instance_id"], "inst-1");
2450 assert_eq!(received["hostname"], "myhost");
2451 assert_eq!(received["version"], "1.2.3");
2452 assert_eq!(received["port"], 9999);
2453 assert_eq!(received["auth_key"], "secret-key");
2454 }
2455}
2456
2457// -- `handle_event` self-skip + TXT-clobber regression tests --
2458//
2459// See docs/specs/SPEC_LAN_DISCOVERY_TXT_CLOBBER_FIX_2026_08_16.md. Root
2460// cause: `enable_addr_auto()` makes mdns-sd re-fire `ServiceResolved` for
2461// the SAME service far more often than fresh TXT data actually arrives —
2462// live logs showed ~96% of resolution events for this instance's own
2463// virtual/link-local addresses carrying an empty TXT record while
2464// address/port were always populated. These tests exercise
2465// `LanDiscovery::handle_event` directly against hand-built `ServiceInfo`
2466// values (no real daemon register/browse — construction of a
2467// `ServiceDaemon` is required only to satisfy the struct field, exactly
2468// as the existing ignored round-trip test above already relies on being
2469// safe) so they run fast and are not subject to that test's documented
2470// multicast flakiness.
2471#[cfg(test)]
2472mod handle_event_tests {
2473 use super::{LanDiscovery, LanInstance, SERVICE_TYPE};
2474 use mdns_sd::{ServiceEvent, ServiceInfo};
2475 use parking_lot::{Mutex, RwLock};
2476 use std::collections::{BTreeSet, HashMap};
2477 use std::sync::Arc;
2478 use tokio::sync::oneshot;
2479
2480 /// Build a `ServiceInfo` for `instance_id`, mirroring the exact
2481 /// `service_name`/host-name shape `LanDiscovery::start()` registers
2482 /// with, so `get_fullname()` matches what production code would
2483 /// compute for the same `instance_id`.
2484 fn test_service_info(host_seed: &str, port: u16, properties: &[(&str, &str)]) -> ServiceInfo {
2485 test_service_info_at(host_seed, port, "127.0.0.1", properties)
2486 }
2487
2488 /// As [`test_service_info`], but with an explicit address. Self-fixtures
2489 /// need a genuinely local one, because the self-check now requires the
2490 /// port AND address to say "this is us" — a fullname match alone no
2491 /// longer skips. See `handle_event`.
2492 fn test_service_info_at(
2493 host_seed: &str,
2494 port: u16,
2495 addr: &str,
2496 properties: &[(&str, &str)],
2497 ) -> ServiceInfo {
2498 // Mirror production's naming exactly (`mdns_instance_label`), so
2499 // `get_fullname()` is what `start()` would really register.
2500 let service_name = super::mdns_instance_label(host_seed, port);
2501 test_service_info_with_label(&service_name, port, addr, properties)
2502 }
2503
2504 /// Build a `ServiceInfo` with an explicit instance label, decoupled from
2505 /// the SRV port. Needed because the peer map is keyed by fullname and the
2506 /// label now embeds the port: a test that models "the SAME service moved
2507 /// to a new port" must hold the label fixed while the SRV port changes,
2508 /// which the label-derives-from-port helpers cannot express.
2509 fn test_service_info_with_label(
2510 label: &str,
2511 port: u16,
2512 addr: &str,
2513 properties: &[(&str, &str)],
2514 ) -> ServiceInfo {
2515 ServiceInfo::new(SERVICE_TYPE, label, "test-host.local.", addr, port, properties)
2516 .expect("ServiceInfo::new should succeed for a well-formed test fixture")
2517 }
2518
2519 /// One address that genuinely belongs to this host, so a self-fixture
2520 /// satisfies `resolves_to_this_instance`. Falls back to loopback on the
2521 /// (practically impossible) empty-set machine.
2522 fn own_addr() -> String {
2523 crate::backend::lan::listeners::cached_local_addresses()
2524 .iter()
2525 .next()
2526 .map(|a| a.to_string())
2527 .unwrap_or_else(|| "127.0.0.1".to_string())
2528 }
2529
2530 /// A `LanDiscovery` whose `service_fullname` is derived the same way
2531 /// production's `start()` derives it (from a real `ServiceInfo` for
2532 /// `self_host_seed`), so the self-skip comparison in `handle_event`
2533 /// is exercised exactly as it runs in production — not asserted
2534 /// against a hand-typed guess at mdns-sd's fullname format.
2535 /// `self_port` is now load-bearing: it is BOTH the port baked into our
2536 /// own `service_fullname` and the `port` the self-check compares against,
2537 /// exactly as in production where both come from the same bind. The old
2538 /// fixture set `port: 0` while minting self-events on a different port —
2539 /// harmless when a bare fullname match was enough to skip, but it did not
2540 /// represent a real self-resolution.
2541 fn test_discovery(self_host_seed: &str, self_port: u16) -> LanDiscovery {
2542 let self_info = test_service_info(self_host_seed, self_port, &[]);
2543 LanDiscovery {
2544 daemon: mdns_sd::ServiceDaemon::new().expect("daemon construction (no register/browse)"),
2545 instances: Arc::new(RwLock::new(HashMap::new())),
2546 instance_id: self_host_seed.to_string(),
2547 event_bus: Arc::new(crate::backend::eventbus::EventBus::new()),
2548 service_fullname: self_info.get_fullname().to_string(),
2549 auth_key: String::new(),
2550 hostname: String::new(),
2551 version: String::new(),
2552 port: self_port,
2553 udp_cancel: Mutex::new(None),
2554 udp_peer_cancel: Mutex::new(None),
2555 agent_names_cancel: Mutex::new(None),
2556 instance_record_cancel: Mutex::new(None),
2557 instances_dir: None,
2558 instance_record_live: Mutex::new(false),
2559 announced_v4: Arc::new(Mutex::new(BTreeSet::new())),
2560 monitored: true,
2561 started_at: std::time::Instant::now(),
2562 }
2563 }
2564
2565 fn get(instances: &[LanInstance], instance_id: &str) -> Option<LanInstance> {
2566 instances.iter().find(|i| i.instance_id == instance_id).cloned()
2567 }
2568
2569 // -- cross-host discovery regression (2026-09-06) --
2570 //
2571 // Two hosts on the same build stopped discovering each other in one
2572 // direction. `service_name` was `agentmux-{instance_id}` and `instance_id`
2573 // is the VERSION, so both hosts registered the identical fullname; the
2574 // self-skip then dropped the genuine peer as "us". The dots in the version
2575 // also made the label malformed, triggering mdns-sd conflict-renaming,
2576 // which left the renamed host with a stale `service_fullname` that matched
2577 // its peer's real name — so the renamed host went blind permanently.
2578 // Found jointly with Manpo@gamerlove against two live hosts.
2579
2580 #[test]
2581 fn a_peer_whose_fullname_equals_ours_is_still_discovered() {
2582 // THE regression. A remote peer announcing under a fullname identical
2583 // to our own (same-version collision, or a stale self-name after a
2584 // conflict-rename) must NOT be mistaken for us: it is on a different
2585 // port, which is proof it is somebody else.
2586 let discovery = test_discovery("collide", 59859);
2587
2588 // The peer must carry OUR EXACT fullname while arriving from a foreign
2589 // address on a foreign port — that is the shape the old
2590 // `fullname == self.service_fullname` guard silently dropped. Pin the
2591 // label explicitly: deriving it from the peer's own (foreign) port
2592 // would produce a DIFFERENT fullname, the old guard would never fire
2593 // on it, and this test would pass against the unfixed code — vacuous.
2594 // (Caught by Manpo@gamerlove reviewing this PR; verified by reverting
2595 // the guard locally and watching this test go red.)
2596 let self_label = super::mdns_instance_label("collide", 59859);
2597 let remote_peer = test_service_info_with_label(
2598 &self_label,
2599 60237,
2600 "192.168.1.68",
2601 &[("instance_id", "v0.55.37"), ("hostname", "gamerlove")],
2602 );
2603 assert_eq!(
2604 remote_peer.get_fullname(),
2605 discovery.service_fullname,
2606 "fixture must actually reproduce the fullname collision, or this test proves nothing"
2607 );
2608
2609 discovery.handle_event(ServiceEvent::ServiceResolved(remote_peer));
2610
2611 assert_eq!(
2612 discovery.get_instances().len(),
2613 1,
2614 "a remote peer must be discovered even when its fullname collides with ours"
2615 );
2616 }
2617
2618 #[test]
2619 fn instance_label_is_free_of_dots_and_unique_per_instance() {
2620 // Dots made the label malformed (mdns-sd split it and appended its
2621 // conflict suffix mid-string, observed as
2622 // "agentmux-v0 (2).55.37._agentmux._tcp.local.").
2623 let fqdn = super::mdns_instance_label("box.corp.example", 59859);
2624 assert!(!fqdn.contains('.'), "label must contain no dots, got {fqdn}");
2625
2626 // Same host, two instances -> different labels (differing ports).
2627 assert_ne!(
2628 super::mdns_instance_label("narko", 59859),
2629 super::mdns_instance_label("narko", 60237),
2630 );
2631 // Two hosts on the SAME version -> different labels. This is the
2632 // property the old version-derived name did not have.
2633 assert_ne!(
2634 super::mdns_instance_label("narko", 59859),
2635 super::mdns_instance_label("gamerlove", 59859),
2636 );
2637 // No version anywhere in it, deliberately.
2638 assert!(!super::mdns_instance_label("narko", 59859).contains("0.55"));
2639 }
2640
2641 #[test]
2642 fn instance_label_survives_a_hostname_with_no_usable_characters() {
2643 let label = super::mdns_instance_label("...", 59859);
2644 assert!(!label.contains('.'));
2645 assert_eq!(label, "agentmux-unknown-59859");
2646 }
2647
2648 #[test]
2649 fn self_resolution_with_blank_txt_is_never_inserted_as_a_peer() {
2650 // This is the exact failure mode from the live logs: mdns-sd
2651 // re-resolves this instance's own service on a virtual/link-local
2652 // interface and the TXT record (instance_id/hostname/version/
2653 // auth_key) comes back empty. Skipping by `fullname` (SRV-record
2654 // derived, always present) rather than the TXT `instance_id`
2655 // property must catch this even though the property itself is
2656 // blank on this event.
2657 let discovery = test_discovery("self-id", 56023);
2658 let blank_self_event = test_service_info_at("self-id", 56023, &own_addr(), &[]);
2659
2660 discovery.handle_event(ServiceEvent::ServiceResolved(blank_self_event));
2661
2662 assert!(
2663 discovery.get_instances().is_empty(),
2664 "a blank-TXT resolution of this instance's own service must never appear as a peer"
2665 );
2666 }
2667
2668 #[test]
2669 fn self_resolution_with_full_txt_is_also_never_inserted_as_a_peer() {
2670 // Sanity check that the fullname-based skip doesn't regress the
2671 // straightforward case (this was already correct before the fix).
2672 let discovery = test_discovery("self-id", 56023);
2673 let full_self_event = test_service_info_at(
2674 "self-id",
2675 56023,
2676 &own_addr(),
2677 &[("instance_id", "self-id"), ("hostname", "myhost")],
2678 );
2679
2680 discovery.handle_event(ServiceEvent::ServiceResolved(full_self_event));
2681
2682 assert!(discovery.get_instances().is_empty());
2683 }
2684
2685 #[test]
2686 fn blank_txt_refire_does_not_clobber_previously_known_good_peer_fields() {
2687 let discovery = test_discovery("self-id", 56023);
2688
2689 let full_event = test_service_info(
2690 "peer-1",
2691 9999,
2692 &[
2693 ("instance_id", "peer-1"),
2694 ("hostname", "realhost"),
2695 ("version", "1.2.3"),
2696 ("auth_key", "secret"),
2697 ],
2698 );
2699 discovery.handle_event(ServiceEvent::ServiceResolved(full_event));
2700
2701 let after_full = get(&discovery.get_instances(), "peer-1").expect("peer-1 should be discovered");
2702 assert_eq!(after_full.hostname, "realhost");
2703 assert_eq!(after_full.version, "1.2.3");
2704 assert_eq!(after_full.auth_key, "secret");
2705
2706 // Same service (same fullname), a re-resolution with an empty TXT
2707 // record — exactly what mdns-sd's `enable_addr_auto()` produces on
2708 // most re-fires per the live-log evidence.
2709 let blank_refire = test_service_info("peer-1", 9999, &[]);
2710 discovery.handle_event(ServiceEvent::ServiceResolved(blank_refire));
2711
2712 let instances = discovery.get_instances();
2713 assert_eq!(instances.len(), 1, "the blank re-fire must update the existing entry, not create a duplicate");
2714 let after_blank = get(&instances, "peer-1").expect("peer-1 must still be present");
2715 assert_eq!(after_blank.hostname, "realhost", "hostname must survive a blank-TXT re-fire");
2716 assert_eq!(after_blank.version, "1.2.3", "version must survive a blank-TXT re-fire");
2717 assert_eq!(after_blank.auth_key, "secret", "auth_key must survive a blank-TXT re-fire");
2718 assert_eq!(after_blank.instance_id, "peer-1", "instance_id must survive a blank-TXT re-fire");
2719 }
2720
2721 #[test]
2722 fn service_removed_does_not_delete_a_known_peer() {
2723 // The live-log failure mode this guards against: mdns-sd fires
2724 // `ServiceRemoved` on ordinary TTL/interface churn, not just on a
2725 // genuine peer departure. The old handler deleted the map entry on
2726 // that event, so the peer's identity (hostname/version/auth_key) was
2727 // gone — and every subsequent re-resolution came back blank-TXT (see
2728 // the refire test above), so it could never recover. `ServiceRemoved`
2729 // must be inert; only staleness (`get_instances()`'s `last_seen`
2730 // check) may make a peer disappear.
2731 let discovery = test_discovery("self-id", 56023);
2732
2733 let full_event = test_service_info(
2734 "peer-1",
2735 9999,
2736 &[
2737 ("instance_id", "peer-1"),
2738 ("hostname", "realhost"),
2739 ("version", "1.2.3"),
2740 ("auth_key", "secret"),
2741 ],
2742 );
2743 let fullname = full_event.get_fullname().to_string();
2744 discovery.handle_event(ServiceEvent::ServiceResolved(full_event));
2745 assert_eq!(discovery.get_instances().len(), 1, "peer-1 should be discovered");
2746
2747 discovery.handle_event(ServiceEvent::ServiceRemoved(SERVICE_TYPE.to_string(), fullname.clone()));
2748
2749 let after_removed = get(&discovery.get_instances(), "peer-1")
2750 .expect("ServiceRemoved must not delete the peer");
2751 assert_eq!(after_removed.hostname, "realhost", "hostname must survive a ServiceRemoved event");
2752 assert_eq!(after_removed.version, "1.2.3", "version must survive a ServiceRemoved event");
2753 assert_eq!(after_removed.auth_key, "secret", "auth_key must survive a ServiceRemoved event");
2754
2755 // The failure mode in full: Removed, then a blank-TXT re-resolution
2756 // (the realistic post-removal shape per live logs) must still not
2757 // lose the identity established by the original full resolution.
2758 let blank_refire = test_service_info("peer-1", 9999, &[]);
2759 discovery.handle_event(ServiceEvent::ServiceResolved(blank_refire));
2760 let after_refire = get(&discovery.get_instances(), "peer-1")
2761 .expect("peer-1 must still be present after a post-removal blank refire");
2762 assert_eq!(after_refire.hostname, "realhost");
2763 assert_eq!(after_refire.version, "1.2.3");
2764 assert_eq!(after_refire.auth_key, "secret");
2765 }
2766
2767 #[test]
2768 fn get_instances_hides_a_peer_stale_past_its_own_ttl() {
2769 let discovery = test_discovery("self-id", 56023);
2770
2771 let full_event = test_service_info(
2772 "peer-1",
2773 9999,
2774 &[("instance_id", "peer-1"), ("hostname", "realhost")],
2775 );
2776 discovery.handle_event(ServiceEvent::ServiceResolved(full_event));
2777 assert_eq!(discovery.get_instances().len(), 1);
2778
2779 // mdns-sd 0.12 exposes no way to construct a ServiceInfo with a
2780 // custom TTL, so the fixture above always resolves with the crate's
2781 // real default (`other_ttl_secs: 4500`) — set it directly to a value
2782 // ABOVE `LAN_PEER_STALE_TIMEOUT_FLOOR_SECS` (300) so the boundary
2783 // being tested is the peer's own TTL, not the floor underneath it.
2784 {
2785 let mut instances = discovery.instances.write();
2786 for inst in instances.values_mut() {
2787 inst.other_ttl_secs = 1000;
2788 }
2789 }
2790
2791 // Backdate past the floor (300s) but still within this peer's own
2792 // 1000s TTL: must still be reported — proves the peer's own TTL, not
2793 // the floor, is what's controlling visibility here.
2794 {
2795 let mut instances = discovery.instances.write();
2796 for inst in instances.values_mut() {
2797 inst.last_seen = inst.last_seen.saturating_sub(600);
2798 }
2799 }
2800 assert_eq!(
2801 discovery.get_instances().len(),
2802 1,
2803 "600s of silence is past the old 300s floor but within this peer's own 1000s TTL"
2804 );
2805
2806 // Now push past the peer's own TTL too.
2807 {
2808 let mut instances = discovery.instances.write();
2809 for inst in instances.values_mut() {
2810 inst.last_seen = inst.last_seen.saturating_sub(401);
2811 }
2812 }
2813 assert!(
2814 discovery.get_instances().is_empty(),
2815 "a peer with no ServiceResolved in over its own advertised TTL must not be reported"
2816 );
2817 }
2818
2819 #[test]
2820 fn peer_staleness_window_secs_ceils_an_adversarially_large_advertised_ttl() {
2821 // ReAgent P1, PR #3301: other_ttl_secs comes straight from a peer's own
2822 // (spoofable) mDNS advertisement — this file already treats that input
2823 // as adversarial elsewhere (LAN_AGENT_NAMES_MAX_*). Without a ceiling, a
2824 // peer claiming an other_ttl near u32::MAX (~136 years) would be
2825 // honored forever, permanently pinning it as "alive" and defeating the
2826 // entire staleness design.
2827 assert_eq!(
2828 super::peer_staleness_window_secs(u32::MAX),
2829 super::LAN_PEER_STALE_TIMEOUT_CEIL_SECS,
2830 "an implausibly large advertised TTL must be capped, not honored as-is"
2831 );
2832 }
2833
2834 #[test]
2835 fn get_instances_hides_a_peer_with_an_adversarial_ttl_once_the_ceiling_elapses() {
2836 let discovery = test_discovery("self-id", 56023);
2837
2838 let full_event = test_service_info(
2839 "peer-1",
2840 9999,
2841 &[("instance_id", "peer-1"), ("hostname", "realhost")],
2842 );
2843 discovery.handle_event(ServiceEvent::ServiceResolved(full_event));
2844 assert_eq!(discovery.get_instances().len(), 1);
2845
2846 {
2847 let mut instances = discovery.instances.write();
2848 for inst in instances.values_mut() {
2849 inst.other_ttl_secs = u32::MAX;
2850 inst.last_seen = inst.last_seen.saturating_sub(super::LAN_PEER_STALE_TIMEOUT_CEIL_SECS + 1);
2851 }
2852 }
2853
2854 assert!(
2855 discovery.get_instances().is_empty(),
2856 "a peer claiming an implausibly large TTL must still expire at the ceiling, \
2857 not be pinned as permanently alive"
2858 );
2859 }
2860
2861 #[test]
2862 fn get_instances_does_not_prune_a_slow_reannouncing_peer_within_its_ttl() {
2863 // The real bug this guards against (2026-09-17): narko and starpower
2864 // re-announce roughly every 40-46 minutes (their actual mDNS `other_ttl`
2865 // record cycle), well past the old fixed 300s cutoff but comfortably
2866 // inside the real advertised TTL (4500s/75min default — RFC 6762 §10,
2867 // mdns-sd 0.12's hardcoded `DNS_OTHER_TTL`). A peer silent for 46
2868 // minutes is still alive and must still be reported.
2869 let discovery = test_discovery("self-id", 56023);
2870
2871 let full_event = test_service_info(
2872 "peer-1",
2873 9999,
2874 &[("instance_id", "peer-1"), ("hostname", "realhost")],
2875 );
2876 discovery.handle_event(ServiceEvent::ServiceResolved(full_event));
2877 assert_eq!(discovery.get_instances().len(), 1);
2878
2879 const FORTY_SIX_MINUTES_SECS: u64 = 46 * 60;
2880 {
2881 let mut instances = discovery.instances.write();
2882 for inst in instances.values_mut() {
2883 inst.last_seen = inst.last_seen.saturating_sub(FORTY_SIX_MINUTES_SECS);
2884 }
2885 }
2886
2887 assert_eq!(
2888 discovery.get_instances().len(),
2889 1,
2890 "a peer silent for less than its own advertised TTL must still be reported, \
2891 even though that gap is far past the old fixed 300s cutoff"
2892 );
2893 }
2894
2895 #[test]
2896 fn address_and_port_still_update_unconditionally_on_a_blank_txt_refire() {
2897 // address/port come from the SRV/A record, not TXT, and are always
2898 // populated by mdns-sd — a genuine interface/address change must
2899 // still be reflected even when the TXT-derived fields are absent
2900 // on that same event.
2901 let discovery = test_discovery("self-id", 56023);
2902
2903 // One stable label across both events: this models the same mDNS
2904 // service re-resolving on a new port, not a different service. (The
2905 // label embeds a port in production, so it is pinned here explicitly
2906 // rather than derived from the changing SRV port.)
2907 let label = super::mdns_instance_label("peer-1", 9999);
2908 let first = test_service_info_with_label(
2909 &label,
2910 9999,
2911 "127.0.0.1",
2912 &[("instance_id", "peer-1"), ("hostname", "realhost")],
2913 );
2914 discovery.handle_event(ServiceEvent::ServiceResolved(first));
2915 assert_eq!(get(&discovery.get_instances(), "peer-1").unwrap().port, 9999);
2916
2917 let moved = test_service_info_with_label(&label, 8888, "127.0.0.1", &[]);
2918 discovery.handle_event(ServiceEvent::ServiceResolved(moved));
2919
2920 let instances = discovery.get_instances();
2921 let entry = get(&instances, "peer-1").expect("peer-1 must still be present");
2922 assert_eq!(entry.port, 8888, "port must update even on a blank-TXT event");
2923 assert_eq!(entry.hostname, "realhost", "hostname must still survive despite the address/port change");
2924 }
2925
2926 #[test]
2927 fn a_new_peer_first_seen_via_blank_txt_has_no_data_to_preserve() {
2928 // Not a regression this fix is responsible for solving — merely
2929 // documents the expected (acceptable) behavior for a genuinely
2930 // first-seen blank-TXT event: nothing was ever known, so nothing
2931 // can be preserved. hostname stays empty until a TXT-bearing event
2932 // eventually arrives.
2933 let discovery = test_discovery("self-id", 56023);
2934 let blank_first = test_service_info("peer-2", 7777, &[]);
2935
2936 discovery.handle_event(ServiceEvent::ServiceResolved(blank_first));
2937
2938 let instances = discovery.get_instances();
2939 assert_eq!(instances.len(), 1);
2940 assert_eq!(instances[0].hostname, "");
2941 assert_eq!(instances[0].instance_id, "");
2942 }
2943
2944 /// The refresh loop holds its own `Arc<LanDiscovery>`, so dropping the
2945 /// controller's Arc on `apply(false)` can never stop it — only an explicit
2946 /// signal can. Without this, disabling LAN discovery left the task issuing
2947 /// authenticated requests to peers forever, leaking one per toggle cycle
2948 /// (ReAgent P1 on PR #3102 — the first version of this code shipped a doc
2949 /// comment claiming cancellation it did not actually implement, which is
2950 /// exactly why this is asserted here rather than described).
2951 #[tokio::test]
2952 async fn shutdown_cancels_the_agent_names_refresh_loop() {
2953 let discovery = Arc::new(test_discovery("cancel-host", 55123));
2954
2955 let (tx, rx) = oneshot::channel();
2956 *discovery.agent_names_cancel.lock() = Some(tx);
2957 let handle = tokio::spawn(discovery.clone().agent_names_refresh_loop(rx));
2958
2959 // Still parked on its sleep — nothing has cancelled it yet.
2960 assert!(!handle.is_finished());
2961
2962 discovery.shutdown();
2963
2964 // Must return promptly on the signal rather than after the full
2965 // LAN_AGENT_NAMES_REFRESH_SECS sleep, which is the whole point of
2966 // selecting on the cancel inside the sleep.
2967 let stopped = tokio::time::timeout(std::time::Duration::from_secs(5), handle).await;
2968 assert!(
2969 stopped.is_ok(),
2970 "refresh loop did not exit within 5s of shutdown() - it would outlive apply(false)"
2971 );
2972 }
2973}
2974
2975#[cfg(test)]
2976#[path = "discovery_rate_limiter_tests.rs"]
2977mod lookup_rate_limiter_tests;
2978
2979#[cfg(test)]
2980#[path = "discovery_peer_fanout_tests.rs"]
2981mod peer_fanout_tests;
2982
2983/// `is_self_resolution` — the guard that stops this instance inserting itself
2984/// as a LAN peer.
2985///
2986/// The scenario these encode was measured on 2026-09-06, not imagined: four
2987/// `LAN peer discovered` events, all `peer_id=""`, all on this instance's own
2988/// port 55019, at 192.168.1.230 / 172.23.176.1 / fe80::5c1e:c2bb:b5bc:9655 —
2989/// every one an address of this host. The pre-existing fullname-based self-skip
2990/// did not catch them.
2991#[cfg(test)]
2992mod self_resolution_tests {
2993 use super::is_self_resolution;
2994 use std::collections::HashSet;
2995 use std::net::IpAddr;
2996
2997 fn own() -> HashSet<IpAddr> {
2998 ["192.168.1.230", "172.23.176.1", "fe80::5c1e:c2bb:b5bc:9655", "127.0.0.1"]
2999 .iter()
3000 .map(|s| s.parse().unwrap())
3001 .collect()
3002 }
3003
3004 fn ip(s: &str) -> IpAddr {
3005 s.parse().unwrap()
3006 }
3007
3008 /// The exact observed case, one per address the log showed.
3009 #[test]
3010 fn our_own_addresses_on_our_own_port_are_self() {
3011 for addr in ["192.168.1.230", "172.23.176.1", "fe80::5c1e:c2bb:b5bc:9655"] {
3012 assert!(
3013 is_self_resolution(55019, &[ip(addr)], 55019, &own()),
3014 "{addr}:55019 is this host on this instance's port — must be skipped"
3015 );
3016 }
3017 }
3018
3019 /// A real peer: different machine, so its addresses are not ours. Sharing
3020 /// our ephemeral port by coincidence must NOT be enough to discard it —
3021 /// that would silently drop a genuine peer, which is far worse than the
3022 /// phantom this guard exists to remove.
3023 #[test]
3024 fn a_remote_peer_on_a_coincidentally_equal_port_is_not_self() {
3025 assert!(!is_self_resolution(55019, &[ip("192.168.1.77")], 55019, &own()));
3026 }
3027
3028 /// Another AgentMux instance on THIS host does share our addresses — it is
3029 /// the port that distinguishes it. Two instances never hold the same port.
3030 #[test]
3031 fn a_sibling_instance_on_this_host_is_not_self() {
3032 assert!(
3033 !is_self_resolution(51095, &[ip("192.168.1.230")], 55019, &own()),
3034 "same host, different port — a real sibling instance, not us"
3035 );
3036 }
3037
3038 /// `any`, not `all`: interface enumeration and mDNS resolution race, so a
3039 /// resolution of our own service can carry one address we didn't enumerate.
3040 /// Requiring every address to match would let that stray entry resurrect
3041 /// the phantom.
3042 #[test]
3043 fn one_matching_address_is_enough_even_beside_an_unknown_one() {
3044 assert!(is_self_resolution(
3045 55019,
3046 &[ip("10.99.99.99"), ip("172.23.176.1")],
3047 55019,
3048 &own()
3049 ));
3050 }
3051
3052 /// Enumeration failing means "we cannot prove any address is ours". Degrade
3053 /// to the old behaviour (a phantom peer) rather than to something worse —
3054 /// an empty set must never make everything look like self.
3055 #[test]
3056 fn an_empty_own_set_never_claims_self() {
3057 assert!(!is_self_resolution(55019, &[ip("192.168.1.230")], 55019, &HashSet::new()));
3058 }
3059
3060 #[test]
3061 fn a_resolution_with_no_addresses_is_not_self() {
3062 assert!(!is_self_resolution(55019, &[], 55019, &own()));
3063 }
3064}
3065
3066/// `agent_names_refresh_loop`'s peer-response handling — real HTTP round
3067/// trips against a raw fake server, same style as
3068/// `server::tests::spawn_fake_browser_api`, because the behavior under test
3069/// (bailing out mid-body, not just rejecting on `Content-Length`) can't be
3070/// exercised through an in-process `tower::ServiceExt::oneshot` call.
3071#[cfg(test)]
3072mod agent_names_refresh_tests {
3073 use super::{LanDiscovery, LAN_AGENT_NAMES_MAX_COUNT, LAN_AGENT_NAMES_MAX_NAME_LEN};
3074 use tokio::io::{AsyncReadExt, AsyncWriteExt};
3075
3076 /// Starts a raw TCP server that always answers
3077 /// `/agentmux/reactive/agent-names` with `body` verbatim (caller supplies
3078 /// correct headers/framing), and returns its `http://127.0.0.1:<port>`
3079 /// base URL. One-shot: serves exactly one connection then stops, which is
3080 /// all a single `fetch_peer_agent_names` call makes.
3081 async fn spawn_fake_agent_names_server(response: &'static str) -> String {
3082 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
3083 let port = listener.local_addr().unwrap().port();
3084 tokio::spawn(async move {
3085 let Ok((mut stream, _)) = listener.accept().await else { return };
3086 let mut buf = [0u8; 4096];
3087 let _ = stream.read(&mut buf).await;
3088 let _ = stream.write_all(response.as_bytes()).await;
3089 });
3090 format!("http://127.0.0.1:{port}")
3091 }
3092
3093 /// Codex P1 on PR #3102: the `lan_key` a peer advertises authenticates
3094 /// THIS client to that peer, not the other way round — anything able to
3095 /// fake an mDNS advertisement gets into `self.instances` and is polled.
3096 /// A response larger than the cap must be rejected outright, not
3097 /// buffered in full and then discarded.
3098 #[tokio::test]
3099 async fn oversized_response_is_rejected_not_buffered() {
3100 // 4x the cap, filled with a repeating byte inside a JSON string so a
3101 // parser that ignored the cap would otherwise succeed.
3102 let oversized_len = 4 * super::LAN_AGENT_NAMES_MAX_RESPONSE_BYTES;
3103 let filler = "a".repeat(oversized_len);
3104 let json_body = format!(r#"{{"agents":["{filler}"]}}"#);
3105 let response = format!(
3106 "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
3107 json_body.len(),
3108 json_body
3109 );
3110 let leaked: &'static str = Box::leak(response.into_boxed_str());
3111 let base_url = spawn_fake_agent_names_server(leaked).await;
3112 let http = reqwest::Client::new();
3113
3114 let names = LanDiscovery::fetch_peer_agent_names(&http, &base_url, "irrelevant").await;
3115 assert!(
3116 names.is_none(),
3117 "an oversized response must be discarded entirely, not truncated into a result"
3118 );
3119 }
3120
3121 /// The happy path, plus defense-in-depth entry capping: a valid response
3122 /// with a name that's too long and more names than the count cap allows
3123 /// should keep the good names and drop the rest, not fail outright.
3124 #[tokio::test]
3125 async fn valid_response_is_parsed_and_excess_entries_are_capped() {
3126 let too_long_name = "x".repeat(LAN_AGENT_NAMES_MAX_NAME_LEN + 1);
3127 let mut names_json: Vec<String> = (0..LAN_AGENT_NAMES_MAX_COUNT + 10)
3128 .map(|i| format!("\"agent-{i}\""))
3129 .collect();
3130 names_json.push(format!("\"{too_long_name}\""));
3131 let json_body = format!(r#"{{"agents":[{}]}}"#, names_json.join(","));
3132 let response = format!(
3133 "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
3134 json_body.len(),
3135 json_body
3136 );
3137 let leaked: &'static str = Box::leak(response.into_boxed_str());
3138 let base_url = spawn_fake_agent_names_server(leaked).await;
3139 let http = reqwest::Client::new();
3140
3141 let names = LanDiscovery::fetch_peer_agent_names(&http, &base_url, "irrelevant")
3142 .await
3143 .expect("a well-formed, appropriately-sized response must parse")
3144 .names;
3145
3146 assert_eq!(names.len(), LAN_AGENT_NAMES_MAX_COUNT, "must truncate to the count cap");
3147 assert!(names.contains(&"agent-0".to_string()));
3148 assert!(
3149 !names.iter().any(|n| n.len() > LAN_AGENT_NAMES_MAX_NAME_LEN),
3150 "an over-length name must never survive into the result"
3151 );
3152 }
3153
3154 /// Codex P2 on PR #3102: sequential polling lets N stale/unreachable
3155 /// peers each burn their full timeout in turn. Two peers that each take
3156 /// ~300ms to answer must complete in ~300ms total, not ~600ms — proving
3157 /// the fan-out is real concurrency, not just non-blocking syntax that
3158 /// still executes one after another.
3159 #[tokio::test]
3160 async fn peers_are_polled_concurrently_not_sequentially() {
3161 async fn spawn_slow_agent_names_server(delay_ms: u64) -> String {
3162 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
3163 let port = listener.local_addr().unwrap().port();
3164 tokio::spawn(async move {
3165 let Ok((mut stream, _)) = listener.accept().await else { return };
3166 let mut buf = [0u8; 4096];
3167 let _ = stream.read(&mut buf).await;
3168 tokio::time::sleep(std::time::Duration::from_millis(delay_ms)).await;
3169 let body = r#"{"agents":["slow-agent"]}"#;
3170 let resp = format!(
3171 "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
3172 body.len(),
3173 body
3174 );
3175 let _ = stream.write_all(resp.as_bytes()).await;
3176 });
3177 format!("http://127.0.0.1:{port}")
3178 }
3179
3180 let delay_ms = 300;
3181 let url_a = spawn_slow_agent_names_server(delay_ms).await;
3182 let url_b = spawn_slow_agent_names_server(delay_ms).await;
3183 let http = reqwest::Client::new();
3184
3185 let started = std::time::Instant::now();
3186 use futures_util::StreamExt as _;
3187 let mut inflight = futures_util::stream::FuturesUnordered::new();
3188 inflight.push(LanDiscovery::fetch_peer_agent_names(&http, &url_a, "k"));
3189 inflight.push(LanDiscovery::fetch_peer_agent_names(&http, &url_b, "k"));
3190 while inflight.next().await.is_some() {}
3191 let elapsed = started.elapsed();
3192
3193 assert!(
3194 elapsed < std::time::Duration::from_millis(delay_ms * 2 - 100),
3195 "two {delay_ms}ms peers took {elapsed:?} — looks sequential, not concurrent"
3196 );
3197 }
3198}