Skip to main content

agentmux_srv/server/
confirm_peer.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Where the process that sends a headless sign-in's confirm stands. The confirm is the person's own answer, so it is taken
5//! only from a process that is found and is outside every agent's process tree. One from inside an agent's tree, one whose
6//! process cannot be found (the lookup failed, or the peer is not on IPv4 loopback) and one that came through a proxy or a
7//! tunnel (it carries forwarding headers) are refused, and the refusal says what works. Every confirm is recorded by
8//! [`super::local_session`].
9
10use std::net::SocketAddr;
11
12use axum::extract::connect_info::{ConnectInfo, Connected};
13use axum::serve::IncomingStream;
14
15use super::local_session::ConfirmHow;
16use super::AppState;
17
18/// Both ends of a connection as the listener accepted it. The peer alone is not enough to find who holds the other end: the
19/// server's own end is whichever listener took the connection, not always the web port.
20#[derive(Debug, Clone, Copy)]
21pub(crate) struct Conn {
22    pub peer: SocketAddr,
23    /// The listener's address for this connection; `None` when the system did not say.
24    pub local: Option<SocketAddr>,
25}
26
27impl Connected<IncomingStream<'_>> for Conn {
28    fn connect_info(stream: IncomingStream<'_>) -> Self {
29        Conn { peer: stream.remote_addr(), local: stream.local_addr().ok() }
30    }
31}
32
33/// Make the plain peer address (`ConnectInfo<SocketAddr>`, which the other routes read) available beside [`Conn`].
34pub(crate) fn with_plain_peer(router: axum::Router) -> axum::Router {
35    router.layer(axum::middleware::from_fn(plain_peer))
36}
37
38async fn plain_peer(mut req: axum::extract::Request, next: axum::middleware::Next) -> axum::response::Response {
39    if let Some(ConnectInfo(conn)) = req.extensions().get::<ConnectInfo<Conn>>().copied() {
40        req.extensions_mut().insert(ConnectInfo(conn.peer));
41    }
42    next.run(req).await
43}
44
45/// What an agent that sent a confirm is told.
46pub(crate) const REFUSED_TEXT: &str = "this confirm is the person's own answer to their sign-in: ask the person to answer it in their terminal";
47
48/// What is told when the confirm's sender could not be found, or came through a proxy: it was not taken, and the person's own
49/// terminal on this machine, or their own browser on the printed address and code, still works.
50pub(crate) const UNKNOWN_TEXT: &str = "this confirm could not be tied to the person's own terminal on this machine, so it was not taken: the person runs `agentmux-srv open` in their own terminal here, or opens the printed address and code in their own browser";
51
52/// The text of a confirm that was not taken.
53pub(crate) fn refusal_text(how: &ConfirmHow) -> &'static str {
54    match how {
55        ConfirmHow::Refused(_) => REFUSED_TEXT,
56        _ => UNKNOWN_TEXT,
57    }
58}
59
60/// Whether the request came through a proxy or a tunnel, by the headers one adds. The real client sends none of them.
61pub(crate) fn is_forwarded(headers: &axum::http::HeaderMap) -> bool {
62    ["forwarded", "x-forwarded-for", "x-forwarded-host", "x-forwarded-proto", "x-real-ip", "via"].iter().any(|h| headers.contains_key(*h))
63}
64
65/// How the confirm that arrived on `conn` was sent. It reads the process table, so it runs off the async threads.
66pub(crate) async fn classify(state: &AppState, conn: Conn, forwarded: bool) -> ConfirmHow {
67    if forwarded {
68        return ConfirmHow::Forwarded;
69    }
70    let state = state.clone();
71    tokio::task::spawn_blocking(move || classify_now(&state, conn)).await.unwrap_or(ConfirmHow::Unknown)
72}
73
74fn classify_now(state: &AppState, conn: Conn) -> ConfirmHow {
75    #[cfg(test)]
76    if let Some(how) = hook::take() {
77        return how;
78    }
79    let Some(server) = conn.local else { return ConfirmHow::Unknown };
80    let Some(pid) = super::peer_process::owner_of(conn.peer, server) else { return ConfirmHow::Unknown };
81    let Some(registry) = crate::backend::process_tracker::registry::global() else { return ConfirmHow::Unknown };
82    let chain = with_ancestors(pid);
83    match registry.agent_block_holding(&chain) {
84        None => ConfirmHow::Outside,
85        Some(block) => {
86            let agent = crate::identity::resolver::block_agent_id(&state.mstore, &block).unwrap_or(block);
87            ConfirmHow::Refused(format!("agent:{agent}"))
88        }
89    }
90}
91
92/// `pid` and its parents, nearest first, as the process table records them (a parent that started after its child is a
93/// reused id and ends the chain).
94pub(crate) fn with_ancestors(pid: u32) -> Vec<u32> {
95    let mut chain = vec![pid];
96    let Ok(all) = agentmux_procstats::snapshot() else { return chain };
97    let mut current = all.iter().find(|p| p.pid == pid);
98    while let Some(p) = current {
99        let Some(parent) = p.ppid.and_then(|pp| all.iter().find(|q| q.pid == pp)) else { break };
100        if !p.is_child_of(parent) || chain.contains(&parent.pid) || chain.len() >= 64 {
101            break;
102        }
103        chain.push(parent.pid);
104        current = Some(parent);
105    }
106    chain
107}
108
109/// What a test makes the next confirm's classification: no process lookup, no tracker.
110#[cfg(test)]
111pub(crate) mod hook {
112    use super::ConfirmHow;
113    use std::sync::Mutex;
114
115    static NEXT: Mutex<Option<ConfirmHow>> = Mutex::new(None);
116
117    pub(crate) fn set(how: ConfirmHow) {
118        *NEXT.lock().unwrap_or_else(|e| e.into_inner()) = Some(how);
119    }
120
121    pub(super) fn take() -> Option<ConfirmHow> {
122        NEXT.lock().unwrap_or_else(|e| e.into_inner()).take()
123    }
124}