agentmux_srv/server/
confirm_peer.rs1use 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#[derive(Debug, Clone, Copy)]
21pub(crate) struct Conn {
22 pub peer: SocketAddr,
23 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
33pub(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
45pub(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
48pub(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
52pub(crate) fn refusal_text(how: &ConfirmHow) -> &'static str {
54 match how {
55 ConfirmHow::Refused(_) => REFUSED_TEXT,
56 _ => UNKNOWN_TEXT,
57 }
58}
59
60pub(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
65pub(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
92pub(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#[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}