Skip to main content

agentmux_srv/server/app_api/
fleet_forward.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The receiving end of a Swarm broadcast forwarded between channels of one install, and the
5//! confirmation that decides how it is delivered.
6//!
7//! A forward is the person's own broadcast (the user-voice header, `MessageOrigin::broadcast()`)
8//! only when another instance on this machine confirms it sent that forward from the operator's
9//! window. Any other forward is delivered as an ordinary agent message from `swarm-forward`,
10//! labelled self-declared. The sending instance keeps what it is about to forward in memory
11//! (`vouch_for_forward`, called only by `fleet_broadcast_impl`, which only the operator's window
12//! reaches) and answers a confirmation once, for exactly that forward; a confirmation carries the
13//! body's SHA-256, never the words. An answer counts only when the listener that gives it is an
14//! AgentMux instance: one held by a process inside an agent's process tree, or one the system
15//! cannot identify, does not count and the forward is delivered as an ordinary agent message, with
16//! the audit saying which case it was.
17
18use agentmux_common::AUTH_KEY_HEADER;
19
20use crate::backend::message_origin::MessageOrigin;
21use crate::backend::reactive::broadcast_turn_message;
22
23use super::fleet::{deliver_broadcast_turn, BroadcastForward, FLEET_BROADCAST_AUDIT_ACTION, NO_REGISTERED_AGENT};
24use super::AppState;
25use crate::server::agent_handlers::AgentTurnDeps;
26use crate::server::peer_process::{self, Descriptors, Listeners};
27
28/// The broadcasts this instance has sent on to another channel and not yet had confirmed.
29static VOUCHED_FORWARDS: std::sync::OnceLock<std::sync::Mutex<std::collections::HashMap<(String, String), VouchedForward>>> = std::sync::OnceLock::new();
30const VOUCH_FOR: std::time::Duration = std::time::Duration::from_secs(120);
31
32struct VouchedForward {
33    body_sha256: String,
34    recipients: usize,
35    until: std::time::Instant,
36}
37
38/// The SHA-256 of a forwarded body, in hex: what a confirmation carries instead of the words themselves.
39pub(crate) fn body_digest(body: &str) -> String {
40    use sha2::{Digest, Sha256};
41    Sha256::digest(body.as_bytes()).iter().map(|b| format!("{b:02x}")).collect()
42}
43
44fn vouched() -> std::sync::MutexGuard<'static, std::collections::HashMap<(String, String), VouchedForward>> {
45    VOUCHED_FORWARDS.get_or_init(Default::default).lock().unwrap_or_else(|e| e.into_inner())
46}
47
48/// Records a forward this instance is about to send (called only for a real operator broadcast).
49pub(super) fn vouch_for_forward(req: &BroadcastForward<'_>) {
50    let now = std::time::Instant::now();
51    let mut table = vouched();
52    table.retain(|_, v| v.until > now);
53    table.insert(
54        (req.msg_id.to_string(), req.block_id.to_string()),
55        VouchedForward { body_sha256: body_digest(req.body), recipients: req.recipients, until: now + VOUCH_FOR },
56    );
57}
58
59/// Whether this instance sent exactly this forward (the body given by its SHA-256): true once, and the entry is spent.
60pub(crate) fn confirm_forward(msg_id: &str, block_id: &str, body_sha256: &str, recipients: usize) -> bool {
61    let now = std::time::Instant::now();
62    let mut table = vouched();
63    table.retain(|_, v| v.until > now);
64    match table.get(&(msg_id.to_string(), block_id.to_string())) {
65        Some(v) if v.body_sha256 == body_sha256 && v.recipients == recipients => {
66            table.remove(&(msg_id.to_string(), block_id.to_string()));
67            true
68        }
69        _ => false,
70    }
71}
72
73/// Who holds the listener that would answer a confirmation.
74#[derive(Debug, Clone, PartialEq, Eq)]
75pub(crate) enum Standing {
76    /// The listener's processes (all of them), none inside an agent's process tree: an AgentMux instance. A listener whose
77    /// holder hides its descriptors (a packaged srv on Linux) counts when no process in any agent's tree hides its own.
78    Instance(Listeners),
79    /// A process of this agent's tree listens there: its answer does not count.
80    InsideAgent(String),
81    /// The lookup could not say (not supported, the table could not be read, the process tracker is not running, or the
82    /// address is not an IPv4 loopback address).
83    Unknown,
84}
85
86/// The standing of the listener at `url`. It reads the process table, so it runs off the async threads.
87async fn listener_standing(state: &AppState, url: &str) -> Standing {
88    let Some(addr) = loopback_addr(url) else { return Standing::Unknown };
89    #[cfg(test)]
90    if let Some(standing) = hook::standing_of(addr) {
91        return standing;
92    }
93    let state = state.clone();
94    tokio::task::spawn_blocking(move || listener_standing_now(&state, addr)).await.unwrap_or(Standing::Unknown)
95}
96
97fn listener_standing_now(state: &AppState, addr: std::net::SocketAddr) -> Standing {
98    let Some(found) = peer_process::listeners_at(addr) else { return Standing::Unknown };
99    let Some(registry) = crate::backend::process_tracker::registry::global() else { return Standing::Unknown };
100    standing_from(
101        found,
102        |pid| {
103            let block = registry.agent_block_holding(&crate::server::confirm_peer::with_ancestors(pid))?;
104            Some(crate::identity::resolver::block_agent_id(&state.mstore, &block).unwrap_or(block))
105        },
106        || registry.agent_member_pids().into_iter().map(|(_, pid)| pid).collect(),
107        peer_process::descriptors_of,
108    )
109}
110
111/// The standing of what was found listening. `agent_holding(pid)` names the agent whose process tree holds `pid`;
112/// `agent_pids` lists every process in every agent's tree; `descriptors(pid)` says whether a process's descriptors can be read.
113fn standing_from(
114    found: Listeners,
115    agent_holding: impl Fn(u32) -> Option<String>,
116    agent_pids: impl FnOnce() -> Vec<u32>,
117    descriptors: impl Fn(u32) -> Descriptors,
118) -> Standing {
119    match &found {
120        Listeners::Held(pids) => {
121            if let Some(agent) = pids.iter().find_map(|pid| agent_holding(*pid)) {
122                return Standing::InsideAgent(agent);
123            }
124        }
125        Listeners::Hidden(_) => {
126            // No readable process holds the socket, so its holder hides its descriptors. It is outside every agent's tree
127            // only if nothing in those trees hides its own: a hidden process of an agent could be the holder.
128            if agent_pids().into_iter().any(|pid| descriptors(pid) == Descriptors::Hidden) {
129                return Standing::Unknown;
130            }
131        }
132    }
133    Standing::Instance(found)
134}
135
136/// `http://127.0.0.1:<port>` (or `localhost`) as an address; anything else is not looked up.
137fn loopback_addr(url: &str) -> Option<std::net::SocketAddr> {
138    let parsed = reqwest::Url::parse(url).ok()?;
139    let ip = match parsed.host_str()? {
140        "localhost" => std::net::Ipv4Addr::LOCALHOST,
141        host => host.parse::<std::net::Ipv4Addr>().ok().filter(|ip| ip.is_loopback())?,
142    };
143    Some(std::net::SocketAddr::new(ip.into(), parsed.port_or_known_default()?))
144}
145
146/// The base URL a confirmation is sent to: the IPv4 loopback address of `url`, as a literal address.
147fn confirm_target(url: &str) -> Option<String> {
148    loopback_addr(url).map(|addr| format!("http://{addr}"))
149}
150
151/// What asking the other instances found, and so how the forward is delivered.
152#[derive(Debug, Clone, PartialEq, Eq)]
153pub(crate) enum ForwardProof {
154    /// An instance that is not inside an agent's process tree confirmed it sent this forward.
155    Confirmed,
156    /// No instance confirmed it.
157    NoInstanceConfirmed,
158    /// An answer came from a process inside this agent's process tree: it does not count.
159    AnsweredFromAgent(String),
160    /// The listener could not be identified, so its answer was not asked for or does not count.
161    ListenerNotIdentified,
162}
163
164impl ForwardProof {
165    /// How the audit says the forward was delivered.
166    fn how(&self) -> String {
167        match self {
168            ForwardProof::Confirmed => "forwarded from another channel on this machine".to_string(),
169            ForwardProof::NoInstanceConfirmed => "forward no other instance confirmed sending: delivered as an agent message, not as the person".to_string(),
170            ForwardProof::AnsweredFromAgent(agent) => format!("a listener inside agent:{agent}'s process tree answered, which does not count: delivered as an agent message, not as the person"),
171            ForwardProof::ListenerNotIdentified => "the instance that answered could not be identified: delivered as an agent message, not as the person".to_string(),
172        }
173    }
174
175    /// Which finding is kept when several instances were asked: an answer from inside an agent over an unidentified listener
176    /// over nothing.
177    fn weight(&self) -> u8 {
178        match self {
179            ForwardProof::Confirmed => 3,
180            ForwardProof::AnsweredFromAgent(_) => 2,
181            ForwardProof::ListenerNotIdentified => 1,
182            ForwardProof::NoInstanceConfirmed => 0,
183        }
184    }
185}
186
187/// Asks one instance whether it sent this forward. Its answer counts only when the listener that gives it is an AgentMux
188/// instance and not a process inside an agent's process tree: that is checked before the question is sent, and again on the
189/// answer (the same processes must still hold the listener).
190async fn ask_instance(state: &AppState, url: &str, auth_key: &str, block_id: &str, body: &str, msg_id: &str, recipients: usize) -> ForwardProof {
191    // The question goes to the very address that was looked up, never to a name that could resolve elsewhere (`localhost`
192    // can resolve to `::1`, which is not looked up).
193    let Some(target) = confirm_target(url) else { return ForwardProof::ListenerNotIdentified };
194    let before = match listener_standing(state, &target).await {
195        Standing::Instance(pids) => pids,
196        Standing::InsideAgent(agent) => return ForwardProof::AnsweredFromAgent(agent),
197        Standing::Unknown => return ForwardProof::ListenerNotIdentified,
198    };
199    let mut http = state
200        .http_client
201        .post(format!("{target}/agentmux/agent/broadcast/confirm"))
202        .timeout(std::time::Duration::from_secs(3))
203        // The digest, not the words: an instance asked here is not necessarily one of ours.
204        .json(&serde_json::json!({ "block_id": block_id, "body_sha256": body_digest(body), "msg_id": msg_id, "recipients": recipients }));
205    if !auth_key.is_empty() {
206        http = http.header(AUTH_KEY_HEADER, auth_key);
207    }
208    let Ok(resp) = http.send().await else { return ForwardProof::NoInstanceConfirmed };
209    let Ok(answer) = resp.json::<serde_json::Value>().await else { return ForwardProof::NoInstanceConfirmed };
210    if answer.get("confirmed").and_then(|v| v.as_bool()) != Some(true) {
211        return ForwardProof::NoInstanceConfirmed;
212    }
213    match listener_standing(state, &target).await {
214        Standing::Instance(after) if after == before => ForwardProof::Confirmed,
215        Standing::InsideAgent(agent) => ForwardProof::AnsweredFromAgent(agent),
216        _ => ForwardProof::ListenerNotIdentified,
217    }
218}
219
220/// The loopback address and key of every other instance on this machine that might have sent a forward: the shared agent
221/// registry's entries and the shared instance registry's live records, so a channel with no agent registered is asked too.
222async fn candidate_instances(state: &AppState) -> Vec<(String, String)> {
223    let agents: Vec<(String, String)> = crate::registry::resolve_shared_reactive_dir()
224        .map(|dir| crate::backend::reactive::registry::list_all_shared(&dir).into_iter().map(|e| (e.local_url, e.auth_key)).collect())
225        .unwrap_or_default();
226    // Under `cargo test` the instance records are not read: a test must not ask a developer's real instances.
227    #[cfg(not(test))]
228    let instances = tokio::task::spawn_blocking(|| {
229        crate::registry::resolve_shared_instances_dir().map(|dir| crate::backend::instance_registry::live_instances(&dir)).unwrap_or_default()
230    })
231    .await
232    .unwrap_or_default();
233    #[cfg(test)]
234    let instances = Vec::new();
235    candidates_from(agents, instances, &state.local_web_url, std::process::id())
236}
237
238/// The addresses to ask, in the order found, each once: never this instance, and only loopback ones. An instance record is
239/// listed only while its srv lives; either source is a file any local process can write, so each address is looked at
240/// (who listens there) before it is asked.
241fn candidates_from(agents: Vec<(String, String)>, instances: Vec<crate::backend::instance_registry::InstanceRecord>, own_url: &str, own_pid: u32) -> Vec<(String, String)> {
242    let from_instances = instances.into_iter().filter(|r| r.pid != own_pid).map(|r| (r.local_url, r.auth_key));
243    let mut asked = std::collections::HashSet::new();
244    agents
245        .into_iter()
246        .chain(from_instances)
247        .filter(|(url, _)| {
248            let loopback = url.starts_with("http://127.0.0.1") || url.starts_with("http://localhost") || url.starts_with("http://[::1]");
249            loopback && url != own_url && asked.insert(url.clone())
250        })
251        .collect()
252}
253
254/// Asks the other instances on this machine (never this one) whether one of them sent this forward. The channel that did
255/// answers yes, once.
256async fn forward_confirmed_by_a_sender(state: &AppState, block_id: &str, body: &str, msg_id: &str, recipients: usize) -> ForwardProof {
257    let mut found = ForwardProof::NoInstanceConfirmed;
258    for (url, auth_key) in candidate_instances(state).await {
259        let proof = ask_instance(state, &url, &auth_key, block_id, body, msg_id, recipients).await;
260        if proof == ForwardProof::Confirmed {
261            return proof;
262        }
263        if proof.weight() > found.weight() {
264            found = proof;
265        }
266    }
267    found
268}
269
270/// The receiving end of `forward_broadcast_to_channel`. A forward that another instance of this
271/// machine confirms it sent (from the operator's window) is delivered as the person's broadcast: the
272/// header is built here, from the target's own agent id, as any broadcast turn
273/// (`MessageOrigin::broadcast()`). Any other forward is delivered as an ordinary agent message from
274/// `swarm-forward`, labelled self-declared, never as the person. Audited on this side too, naming
275/// which of the two it was.
276pub(crate) async fn deliver_forwarded_broadcast(
277    state: &AppState,
278    block_id: &str,
279    body: &str,
280    msg_id: &str,
281    recipients: usize,
282) -> Result<(), String> {
283    let proof = if state.reactive_handler.get_agent_by_block(block_id).is_some() {
284        forward_confirmed_by_a_sender(state, block_id, body, msg_id, recipients).await
285    } else {
286        ForwardProof::NoInstanceConfirmed
287    };
288    deliver_forward(state, block_id, body, msg_id, recipients, proof).await.1
289}
290
291/// How a forwarded broadcast was delivered.
292#[derive(Debug, Clone, Copy, PartialEq, Eq)]
293pub(crate) enum ForwardedAs {
294    /// The person's own broadcast: the sending instance confirmed it came from the operator's window.
295    Person,
296    /// An ordinary agent message from `swarm-forward`.
297    AgentMessage,
298}
299
300async fn deliver_forward(
301    state: &AppState,
302    block_id: &str,
303    body: &str,
304    msg_id: &str,
305    recipients: usize,
306    proof: ForwardProof,
307) -> (ForwardedAs, Result<(), String>) {
308    let how = proof.how();
309    let mut kind = ForwardedAs::Person;
310    let result = match state.reactive_handler.get_agent_by_block(block_id) {
311        None => Err(NO_REGISTERED_AGENT.to_string()),
312        Some(agent) if proof == ForwardProof::Confirmed => {
313            let text = broadcast_turn_message(&agent.agent_id, recipients, msg_id, body);
314            let deps = AgentTurnDeps::from_state(state);
315            deliver_broadcast_turn(&deps, block_id.to_string(), text, MessageOrigin::broadcast()).await
316        }
317        Some(agent) => {
318            kind = ForwardedAs::AgentMessage;
319            deliver_unconfirmed_forward(state, &agent.agent_id, body).await
320        }
321    };
322    let target = state
323        .reactive_handler
324        .get_agent_by_block(block_id)
325        .map(|a| a.agent_id)
326        .unwrap_or_else(|| block_id.to_string());
327    state.reactive_handler.log_fleet_action_audit(
328        None,
329        &target,
330        block_id,
331        FLEET_BROADCAST_AUDIT_ACTION,
332        result.is_ok(),
333        result.as_ref().err().map(String::as_str),
334        msg_id,
335        Some(how.as_str()),
336    );
337    (kind, result)
338}
339
340/// A forward nobody confirmed: an ordinary message to the agent from the sender name `swarm-forward`,
341/// through the same delivery as any unattributed one (labelled self-declared, never host-verified).
342async fn deliver_unconfirmed_forward(state: &AppState, agent_id: &str, body: &str) -> Result<(), String> {
343    let req = crate::backend::reactive::InjectionRequest {
344        target_agent: agent_id.to_string(),
345        message: format!("A Swarm broadcast was forwarded to you but not proven to come from the person's window, so it is delivered as an ordinary message:\n{body}"),
346        source_agent: Some("swarm-forward".to_string()),
347        reply: Some("none".to_string()),
348        ..Default::default()
349    };
350    let answer = crate::server::reactive::deliver(state, crate::server::ReactiveAuthVia::FullAuthKey, "", req).await;
351    if answer.get("success").and_then(|v| v.as_bool()) == Some(true) {
352        Ok(())
353    } else {
354        Err(answer.get("error").and_then(|v| v.as_str()).unwrap_or("not delivered").to_string())
355    }
356}
357
358#[cfg(test)]
359mod tests {
360    use super::*;
361
362    #[test]
363    fn a_forward_is_confirmed_once_and_only_as_it_was_sent() {
364        let f = BroadcastForward { block_id: "blk-confirm", body: "ship it", msg_id: "m-confirm", recipients: 2 };
365        let digest = body_digest("ship it");
366        assert_eq!(digest.len(), 64);
367        assert!(!digest.contains("ship"), "the words are not in what is sent to be confirmed");
368        assert!(!confirm_forward("m-confirm", "blk-confirm", &digest, 2), "nothing was sent yet");
369        vouch_for_forward(&f);
370        assert!(!confirm_forward("m-confirm", "blk-confirm", &body_digest("something else"), 2), "another body is not that forward");
371        assert!(!confirm_forward("m-confirm", "blk-confirm", &digest, 9), "another count is not that forward");
372        assert!(!confirm_forward("m-confirm", "blk-other", &digest, 2), "another block is not that forward");
373        assert!(confirm_forward("m-confirm", "blk-confirm", &digest, 2));
374        assert!(!confirm_forward("m-confirm", "blk-confirm", &digest, 2), "a confirmation is spent");
375    }
376
377    #[tokio::test]
378    async fn only_a_confirmed_forward_arrives_as_the_person() {
379        let state = crate::server::tests::test_state();
380        state.reactive_handler.register_agent("fwd-target", "blk-fwd-target", None).unwrap();
381        let (kind, _) = deliver_forward(&state, "blk-fwd-target", "hi", "m-2", 1, ForwardProof::NoInstanceConfirmed).await;
382        assert_eq!(kind, ForwardedAs::AgentMessage, "no instance vouched for it");
383        let (kind, _) = deliver_forward(&state, "blk-fwd-target", "hi", "m-2", 1, ForwardProof::AnsweredFromAgent("some-agent".into())).await;
384        assert_eq!(kind, ForwardedAs::AgentMessage, "an answer from inside an agent's tree does not count");
385        let (kind, _) = deliver_forward(&state, "blk-fwd-target", "hi", "m-2", 1, ForwardProof::ListenerNotIdentified).await;
386        assert_eq!(kind, ForwardedAs::AgentMessage, "a failed lookup falls back to an ordinary message");
387        let (kind, _) = deliver_forward(&state, "blk-fwd-target", "hi", "m-2", 1, ForwardProof::Confirmed).await;
388        assert_eq!(kind, ForwardedAs::Person);
389    }
390
391    #[test]
392    fn each_case_is_recorded_as_what_it_was() {
393        let hows: Vec<String> = [
394            ForwardProof::Confirmed,
395            ForwardProof::NoInstanceConfirmed,
396            ForwardProof::AnsweredFromAgent("some-agent".into()),
397            ForwardProof::ListenerNotIdentified,
398        ]
399        .iter()
400        .map(ForwardProof::how)
401        .collect();
402        for (i, a) in hows.iter().enumerate() {
403            for b in &hows[i + 1..] {
404                assert_ne!(a, b, "two cases are recorded the same way");
405            }
406        }
407        assert!(hows[2].contains("some-agent"), "the agent whose tree held the listener is named");
408    }
409
410    /// A listener that answers every confirmation "yes", and how many times it was asked.
411    async fn confirming_listener() -> (String, std::net::SocketAddr, std::sync::Arc<std::sync::atomic::AtomicUsize>) {
412        let asked = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
413        let count = asked.clone();
414        let app = axum::Router::new().route(
415            "/agentmux/agent/broadcast/confirm",
416            axum::routing::post(move || {
417                let count = count.clone();
418                async move {
419                    count.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
420                    axum::Json(serde_json::json!({ "confirmed": true }))
421                }
422            }),
423        );
424        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
425        let addr = listener.local_addr().unwrap();
426        tokio::spawn(async move {
427            axum::serve(listener, app).await.ok();
428        });
429        (format!("http://{addr}"), addr, asked)
430    }
431
432    #[tokio::test]
433    async fn an_answer_from_a_real_second_instance_counts() {
434        let state = crate::server::tests::test_state();
435        let (url, addr, asked) = confirming_listener().await;
436        hook::set(addr, Standing::Instance(Listeners::Held(vec![4242])));
437        assert_eq!(ask_instance(&state, &url, "", "blk", "hi", "m-3", 1).await, ForwardProof::Confirmed);
438        assert_eq!(asked.load(std::sync::atomic::Ordering::SeqCst), 1);
439    }
440
441    #[tokio::test]
442    async fn an_answer_from_a_listener_inside_an_agents_tree_does_not_count() {
443        let state = crate::server::tests::test_state();
444        let (url, addr, asked) = confirming_listener().await;
445        hook::set(addr, Standing::InsideAgent("some-agent".into()));
446        assert_eq!(ask_instance(&state, &url, "", "blk", "hi", "m-4", 1).await, ForwardProof::AnsweredFromAgent("some-agent".into()));
447        assert_eq!(asked.load(std::sync::atomic::Ordering::SeqCst), 0, "the question is not even sent to it");
448    }
449
450    #[tokio::test]
451    async fn a_failed_lookup_does_not_count_and_nothing_is_sent() {
452        let state = crate::server::tests::test_state();
453        let (url, addr, asked) = confirming_listener().await;
454        hook::set(addr, Standing::Unknown);
455        assert_eq!(ask_instance(&state, &url, "", "blk", "hi", "m-5", 1).await, ForwardProof::ListenerNotIdentified);
456        assert_eq!(asked.load(std::sync::atomic::Ordering::SeqCst), 0);
457    }
458
459    #[tokio::test]
460    async fn a_listener_that_changes_hands_during_the_question_does_not_count() {
461        let state = crate::server::tests::test_state();
462        let (url, addr, _) = confirming_listener().await;
463        hook::set_sequence(addr, vec![Standing::Instance(Listeners::Held(vec![1])), Standing::Instance(Listeners::Held(vec![2]))]);
464        assert_eq!(ask_instance(&state, &url, "", "blk", "hi", "m-6", 1).await, ForwardProof::ListenerNotIdentified);
465        hook::set_sequence(addr, vec![Standing::Instance(Listeners::Held(vec![1])), Standing::InsideAgent("some-agent".into())]);
466        assert_eq!(ask_instance(&state, &url, "", "blk", "hi", "m-6", 1).await, ForwardProof::AnsweredFromAgent("some-agent".into()));
467    }
468
469    fn record(channel: &str, url: &str, pid: u32) -> crate::backend::instance_registry::InstanceRecord {
470        crate::backend::instance_registry::InstanceRecord {
471            channel: channel.to_string(),
472            version: "0.0.0".to_string(),
473            pid,
474            local_url: url.to_string(),
475            auth_key: format!("key-{channel}"),
476            started_at: 1,
477            updated_at: 2,
478            agent_count: 0,
479        }
480    }
481
482    #[test]
483    fn a_channel_with_no_agent_registered_is_asked_through_its_instance_record() {
484        let agents = vec![("http://127.0.0.1:7001".to_string(), "agent-key".to_string())];
485        let instances = vec![record("with-agent", "http://127.0.0.1:7001", 11), record("no-agent", "http://127.0.0.1:7002", 12)];
486        let found = candidates_from(agents, instances, "http://127.0.0.1:7000", 10);
487        assert_eq!(
488            found,
489            vec![("http://127.0.0.1:7001".to_string(), "agent-key".to_string()), ("http://127.0.0.1:7002".to_string(), "key-no-agent".to_string())],
490            "the instance with no agent is asked, and an instance listed twice once"
491        );
492    }
493
494    #[test]
495    fn this_instance_and_addresses_off_this_machine_are_never_asked() {
496        let agents = vec![("http://203.0.113.9:7003".to_string(), "k".to_string()), ("http://127.0.0.1:7000".to_string(), "own".to_string())];
497        let instances = vec![record("self-by-pid", "http://127.0.0.1:7004", 10), record("self-by-url", "http://127.0.0.1:7000", 13)];
498        assert!(candidates_from(agents, instances, "http://127.0.0.1:7000", 10).is_empty());
499    }
500
501    fn nobody_holds(_: u32) -> Option<String> {
502        None
503    }
504
505    #[test]
506    fn a_listener_held_by_a_process_in_an_agents_tree_is_that_agents() {
507        let standing = standing_from(Listeners::Held(vec![10, 11]), |pid| (pid == 11).then(|| "some-agent".to_string()), Vec::new, |_| Descriptors::Readable);
508        assert_eq!(standing, Standing::InsideAgent("some-agent".into()));
509        let standing = standing_from(Listeners::Held(vec![10, 11]), nobody_holds, Vec::new, |_| Descriptors::Readable);
510        assert_eq!(standing, Standing::Instance(Listeners::Held(vec![10, 11])));
511    }
512
513    #[test]
514    fn a_hidden_listener_counts_only_when_nothing_in_an_agents_tree_is_hidden_too() {
515        let hidden = || Listeners::Hidden(vec![555]);
516        // A packaged srv hides its descriptors; the agents' processes can all be read: it is not inside any tree.
517        assert_eq!(standing_from(hidden(), nobody_holds, || vec![1, 2, 3], |_| Descriptors::Readable), Standing::Instance(hidden()));
518        // A process that is gone since the list was made does not make it uncertain.
519        assert_eq!(standing_from(hidden(), nobody_holds, || vec![1, 2], |pid| if pid == 2 { Descriptors::Gone } else { Descriptors::Readable }), Standing::Instance(hidden()));
520        // A process in an agent's tree that hides its descriptors could be the holder: it is not said to be an instance.
521        assert_eq!(standing_from(hidden(), nobody_holds, || vec![1, 2, 3], |pid| if pid == 2 { Descriptors::Hidden } else { Descriptors::Readable }), Standing::Unknown);
522        // The same listener is what is looked at twice: the sockets must be the same ones.
523        assert_ne!(Standing::Instance(Listeners::Hidden(vec![555])), Standing::Instance(Listeners::Hidden(vec![556])));
524    }
525
526    #[test]
527    fn the_question_goes_to_the_address_that_was_looked_up() {
528        assert_eq!(confirm_target("http://localhost:7380").as_deref(), Some("http://127.0.0.1:7380"), "localhost is not sent as a name");
529        assert_eq!(confirm_target("http://127.0.0.1:7380/").as_deref(), Some("http://127.0.0.1:7380"));
530        assert_eq!(confirm_target("http://[::1]:7380"), None, "an address that is not looked up is not asked");
531        assert_eq!(confirm_target("http://127.0.0.1.example.com:7380"), None, "a name that only starts like loopback is not asked");
532        assert_eq!(confirm_target("http://127.0.0.1@example.com:7380"), None, "an address in the user part is not the host");
533    }
534
535    #[tokio::test]
536    async fn a_localhost_entry_is_asked_at_the_looked_up_ipv4_address() {
537        let state = crate::server::tests::test_state();
538        let (_, addr, asked) = confirming_listener().await;
539        hook::set(addr, Standing::Instance(Listeners::Held(vec![4243])));
540        let url = format!("http://localhost:{}", addr.port());
541        assert_eq!(ask_instance(&state, &url, "", "blk", "hi", "m-7", 1).await, ForwardProof::Confirmed);
542        assert_eq!(asked.load(std::sync::atomic::Ordering::SeqCst), 1);
543    }
544
545    #[test]
546    fn only_an_ipv4_loopback_url_is_looked_up() {
547        assert_eq!(loopback_addr("http://127.0.0.1:7380"), Some("127.0.0.1:7380".parse().unwrap()));
548        assert_eq!(loopback_addr("http://localhost:7380"), Some("127.0.0.1:7380".parse().unwrap()));
549        assert_eq!(loopback_addr("http://[::1]:7380"), None);
550        assert_eq!(loopback_addr("http://203.0.113.9:7380"), None);
551        assert_eq!(loopback_addr("not a url"), None);
552    }
553}
554
555/// What a test makes the standing of a listener: no process lookup, no tracker.
556#[cfg(test)]
557mod hook {
558    use super::Standing;
559    use std::collections::{HashMap, VecDeque};
560    use std::net::SocketAddr;
561    use std::sync::Mutex;
562
563    static BY_ADDR: Mutex<Option<HashMap<SocketAddr, VecDeque<Standing>>>> = Mutex::new(None);
564
565    pub(super) fn set(addr: SocketAddr, standing: Standing) {
566        set_sequence(addr, vec![standing]);
567    }
568
569    /// The standing returned by each lookup in turn; the last one stays.
570    pub(super) fn set_sequence(addr: SocketAddr, standing: Vec<Standing>) {
571        BY_ADDR.lock().unwrap_or_else(|e| e.into_inner()).get_or_insert_with(Default::default).insert(addr, standing.into());
572    }
573
574    pub(super) fn standing_of(addr: SocketAddr) -> Option<Standing> {
575        let mut all = BY_ADDR.lock().unwrap_or_else(|e| e.into_inner());
576        let queue = all.as_mut()?.get_mut(&addr)?;
577        if queue.len() > 1 { queue.pop_front() } else { queue.front().cloned() }
578    }
579}