Skip to main content

agentmux_srv_core/backend/lan/
firewall_setup.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Run the elevated firewall helper when the person asks for the setup (`docs/specs/SPEC_LAN_FIREWALL_SETUP_2026_10_01.md`
5//! 4.2, step 3). The helper is `agentmux.exe --configure-lan-firewall`, in the install folder above this program's own
6//! (`{app}\runtime\agentmux-srv-<version>.exe`, and the same in a portable folder). It reads the firewall without
7//! elevation and asks Windows for administrator permission itself, only when a change is needed, so this module never
8//! elevates anything. It is started by the person's click and never by itself: a cancel is final until the next click.
9
10use std::path::{Path, PathBuf};
11use std::time::{Duration, Instant};
12
13use agentmux_common::lan_firewall_rules::{CONFIGURE_FLAG, EXIT_CANCELLED, EXIT_MANAGED, EXIT_OK, EXIT_UNVERIFIED};
14
15use crate::backend::rpc_types::{LanFirewallSetupResult, SetupOutcome};
16
17/// How long the helper may take: Windows' own prompt waits for the person, and a prompt left alone is not waited on forever.
18/// The call's timeout in the window's stub (`lan:firewall:setup` in `generated-manifest.json`, 330 seconds) is longer than
19/// this, so the answer is never cut off by the default five seconds.
20const HELPER_WAIT: Duration = Duration::from_secs(300);
21
22/// The helper that goes with the program at `srv_exe`, if its folder has one.
23pub fn helper_exe(srv_exe: &Path) -> Option<PathBuf> {
24    let exe = srv_exe.parent()?.parent()?.join("agentmux.exe");
25    exe.is_file().then_some(exe)
26}
27
28/// What the person is told for how the helper ended. `code` is its exit code (`None`: it was ended by something else),
29/// `reason` the last line it wrote to stderr.
30pub fn result_for(code: Option<i32>, reason: &str) -> LanFirewallSetupResult {
31    let (outcome, message) = match code {
32        Some(EXIT_OK) => (SetupOutcome::Done, "Windows now lets other computers on your private networks reach AgentMux.".to_string()),
33        Some(EXIT_CANCELLED) => (SetupOutcome::Cancelled, "Windows asked for permission and it was not given, so nothing was changed.".to_string()),
34        Some(EXIT_MANAGED) => (
35            SetupOutcome::Managed,
36            "Your administrator manages this computer's firewall, so AgentMux cannot change it.".to_string(),
37        ),
38        Some(EXIT_UNVERIFIED) => (
39            SetupOutcome::Unverified,
40            "The rules were added, but some of Windows' other rules could not be read, so it cannot be said that none of them blocks AgentMux."
41                .to_string(),
42        ),
43        Some(_) | None => {
44            let reason = reason.trim();
45            let message = if reason.is_empty() {
46                "The setup did not finish.".to_string()
47            } else {
48                format!("The setup did not finish: {}", reason.chars().take(300).collect::<String>())
49            };
50            (SetupOutcome::Failed, message)
51        }
52    };
53    LanFirewallSetupResult { outcome, message }
54}
55
56/// Said when this copy has no helper to run.
57fn unavailable(why: &str) -> LanFirewallSetupResult {
58    LanFirewallSetupResult { outcome: SetupOutcome::Unavailable, message: why.to_string() }
59}
60
61/// Run the helper and say how it went. Blocks while Windows' prompt is open: call it from a blocking task.
62pub fn run_blocking() -> LanFirewallSetupResult {
63    if !cfg!(windows) {
64        return unavailable("Windows Defender Firewall setup is only for Windows.");
65    }
66    let Some(helper) = std::env::current_exe().ok().and_then(|exe| helper_exe(&exe)) else {
67        return unavailable(
68            "This copy of AgentMux has no setup program next to it. Run \"Allow LAN access\" from the installer, or `agentmux.exe --configure-lan-firewall` from an installed copy, once.",
69        );
70    };
71    run_helper(&helper)
72}
73
74fn run_helper(helper: &Path) -> LanFirewallSetupResult {
75    use agentmux_common::win32::NoWindow;
76    use std::io::Read;
77    let spawned = std::process::Command::new(helper)
78        .no_window()
79        .arg(CONFIGURE_FLAG)
80        .stdin(std::process::Stdio::null())
81        .stdout(std::process::Stdio::null())
82        .stderr(std::process::Stdio::piped())
83        .spawn();
84    let mut child = match spawned {
85        Ok(c) => c,
86        Err(e) => return result_for(None, &format!("could not start the setup program: {e}")),
87    };
88    // Read what it says in its own thread, so a full pipe never holds it up.
89    let stderr = child.stderr.take();
90    let reader = std::thread::spawn(move || {
91        let mut text = String::new();
92        if let Some(mut s) = stderr {
93            let _ = s.read_to_string(&mut text);
94        }
95        text
96    });
97    let until = Instant::now() + HELPER_WAIT;
98    let code = loop {
99        match child.try_wait() {
100            Ok(Some(status)) => break status.code(),
101            Ok(None) if Instant::now() < until => std::thread::sleep(Duration::from_millis(200)),
102            _ => {
103                let _ = child.kill();
104                let _ = child.wait();
105                let _ = reader.join();
106                return result_for(None, "no answer was given to Windows' prompt in time");
107            }
108        }
109    };
110    let text = reader.join().unwrap_or_default();
111    result_for(code, text.lines().rev().find(|l| !l.trim().is_empty()).unwrap_or(""))
112}
113
114#[cfg(test)]
115mod tests {
116    use super::*;
117    use agentmux_common::lan_firewall_rules::EXIT_FAILED;
118
119    #[test]
120    fn every_exit_code_of_the_helper_has_words_of_its_own() {
121        let words = |code| result_for(Some(code), "boom");
122        assert_eq!(words(EXIT_OK).outcome, SetupOutcome::Done);
123        assert_eq!(words(EXIT_CANCELLED).outcome, SetupOutcome::Cancelled);
124        assert_eq!(words(EXIT_MANAGED).outcome, SetupOutcome::Managed);
125        assert_eq!(words(EXIT_UNVERIFIED).outcome, SetupOutcome::Unverified);
126        assert_eq!(words(EXIT_FAILED).outcome, SetupOutcome::Failed);
127        assert_eq!(words(77).outcome, SetupOutcome::Failed, "an exit code nobody knows is a failure, never a success");
128        assert_eq!(result_for(None, "").outcome, SetupOutcome::Failed, "ended by something else");
129        let all: std::collections::HashSet<String> = [EXIT_OK, EXIT_CANCELLED, EXIT_MANAGED, EXIT_UNVERIFIED].iter().map(|c| words(*c).message).collect();
130        assert_eq!(all.len(), 4, "each outcome says its own thing");
131    }
132
133    #[test]
134    fn a_failure_carries_the_helpers_own_reason_but_only_so_much_of_it() {
135        let r = result_for(Some(EXIT_FAILED), "  asking Windows for permission: access denied  ");
136        assert_eq!(r.message, "The setup did not finish: asking Windows for permission: access denied");
137        assert_eq!(result_for(Some(EXIT_FAILED), "").message, "The setup did not finish.");
138        let long = result_for(Some(EXIT_FAILED), &"x".repeat(5000));
139        assert!(long.message.chars().count() < 400, "{}", long.message.chars().count());
140    }
141
142    #[test]
143    fn the_helper_is_the_launcher_above_the_runtime_folder() {
144        let dir = tempfile::tempdir().unwrap();
145        let runtime = dir.path().join("runtime");
146        std::fs::create_dir_all(&runtime).unwrap();
147        let srv = runtime.join("agentmux-srv-1.0.0-windows.x64.exe");
148        assert_eq!(helper_exe(&srv), None, "no launcher beside it: nothing to run");
149        std::fs::write(dir.path().join("agentmux.exe"), b"").unwrap();
150        assert_eq!(helper_exe(&srv), Some(dir.path().join("agentmux.exe")));
151        // A folder named like the launcher is not it.
152        let other = tempfile::tempdir().unwrap();
153        std::fs::create_dir_all(other.path().join("agentmux.exe")).unwrap();
154        assert_eq!(helper_exe(&other.path().join("runtime").join("srv.exe")), None);
155    }
156
157    #[cfg(not(windows))]
158    #[test]
159    fn off_windows_there_is_nothing_to_run() {
160        let r = run_blocking();
161        assert_eq!(r.outcome, SetupOutcome::Unavailable);
162    }
163}