Skip to main content

agentmux_srv/
headless.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Headless mode: srv started directly — a container entrypoint, a server, CI —
5//! with no launcher or desktop host. docs/specs/SPEC_SRV_HEADLESS_MODE_2026_09_26.md.
6//!
7//! Normally the launcher prepares srv's world before spawning it: the data-path
8//! env (`DataPaths::to_env_vars`), a per-launch auth key, and a stdin pipe and
9//! parent process whose end means "shut down". Headless srv does that itself:
10//!
11//! - resolves and exports the data-path env when it isn't already set;
12//! - takes srv's data-dir lock early (the same lock every srv takes), so no two
13//!   servers — headless or launcher-started — share a set of databases;
14//! - takes its auth key from `AGENTMUX_AUTH_KEY`, `--auth-key-file`, or
15//!   generates one and writes it to `<data dir>/srv-auth-key` (0600) — the key
16//!   is never printed, only the file's path;
17//! - keeps secrets in owner-only files under the shared dir instead of the OS
18//!   keychain, which a container usually doesn't have (`--secret-store
19//!   keychain` to use the keychain anyway);
20//! - joins the LAN and the cloud relay as the desktop app does, on the same settings and the same checks:
21//!   `network:lan_discovery` (off until the person turns it on) adds the LAN listeners and the mDNS advertisement,
22//!   and the relay connects once the channel has its own sign-in;
23//! - is not tied to stdin or a parent process (`main` skips those watchers);
24//!   SIGINT/SIGTERM still shut it down.
25//!
26//! Its startup listeners are loopback (`--web-port` / `--ws-port` fix the ports), and the web UI is
27//! served there only. Another AgentMux reaches it over the LAN or the relay the way it reaches a desktop
28//! one: through the LAN listeners the supervisor adds on those ports when `network:lan_discovery` is on,
29//! behind the LAN key and the pins. A browser on another machine is a reverse proxy's job, not srv's. For a
30//! client behind such a proxy, `--frontend-dir` serves the built frontend and
31//! `--allowed-origin` names the proxy's origin for CORS and the /ws check.
32
33use std::ffi::OsString;
34use std::path::{Path, PathBuf};
35use std::sync::OnceLock;
36
37use crate::config::{CliArgs, SecretStoreKind};
38
39
40/// Set once `prepare_env` succeeded: this process is the headless server.
41static ACTIVE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
42
43/// `--web-port` / `--ws-port`, held in-process (never in the env, so a
44/// launcher-spawned srv or an agent can't inherit them — ReAgent P1 on #3893).
45static PORTS: OnceLock<(Option<u16>, Option<u16>)> = OnceLock::new();
46
47/// `--frontend-dir` / `--allowed-origin`, held in-process like the ports.
48static WEB: OnceLock<WebOptions> = OnceLock::new();
49
50/// The directory srv keeps its databases in (`--wavedata`, else the resolved data dir), set once headless started.
51static DATA_DIR: OnceLock<PathBuf> = OnceLock::new();
52/// What the file of kept browser sessions is bound to: nothing for a key srv generated (new at every start), the key itself for one
53/// the person provided.
54static SESSION_BINDING: OnceLock<crate::server::local_session_file::KeyBinding> = OnceLock::new();
55
56/// The file the key was read from or written to, when it came from a file (not the environment).
57static KEY_FILE: OnceLock<PathBuf> = OnceLock::new();
58
59#[derive(Debug, Default)]
60struct WebOptions {
61    frontend_dir: Option<PathBuf>,
62    /// `--public-origin`, normalized: `http://127.0.0.1:<port>`.
63    public_origin: Option<String>,
64    /// Normalized by [`normalize_origin`].
65    allowed_origins: Vec<String>,
66}
67
68/// Which startup listener a bind address is for.
69#[derive(Clone, Copy)]
70pub enum Listener {
71    Web,
72    Ws,
73}
74
75/// The data directory this headless srv uses (the one its databases and key file are in), when headless.
76pub fn data_dir() -> Option<&'static Path> {
77    DATA_DIR.get().map(PathBuf::as_path)
78}
79
80/// Is this process running headless (after `prepare_env`)?
81pub fn active() -> bool {
82    ACTIVE.load(std::sync::atomic::Ordering::SeqCst)
83}
84
85/// File name of the generated auth key, beside the databases.
86pub const AUTH_KEY_FILE_NAME: &str = "srv-auth-key";
87
88/// Is this the headless server starting (`--headless` or `AGENTMUX_HEADLESS=1`)?
89/// Never for a subcommand such as `migrate`: it needs none of the headless
90/// setup, and its lock would refuse a `migrate --verify` run beside a running
91/// headless server (ReAgent P1 on #3893).
92pub fn requested() -> bool {
93    let args: Vec<OsString> = std::env::args_os().collect();
94    requested_from(&args, std::env::var("AGENTMUX_HEADLESS").ok().as_deref())
95}
96
97fn requested_from(args: &[OsString], env: Option<&str>) -> bool {
98    let asked = args.iter().any(|a| a == "--headless") || matches!(env, Some("1") | Some("true"));
99    // Parse with the same CliArgs `load_config` uses. A subcommand, or
100    // --help/--version (which clap reports as an Err), is not the server, so
101    // no setup and no lock (Codex P2 on #3893). Any other argv clap rejects is
102    // left for `load_config` to report.
103    use clap::error::ErrorKind;
104    let not_the_server = match <CliArgs as clap::Parser>::try_parse_from(args) {
105        Ok(a) => a.command.is_some(),
106        Err(e) => matches!(
107            e.kind(),
108            ErrorKind::DisplayHelp | ErrorKind::DisplayVersion | ErrorKind::DisplayHelpOnMissingArgumentOrSubcommand
109        ),
110    };
111    asked && !not_the_server
112}
113
114/// Prepare the environment the launcher would normally provide. Runs before
115/// logging is initialized, so problems are returned for `main` to print.
116/// Returns the path the auth key was written to, when it generated one.
117pub fn prepare_env() -> Result<Option<PathBuf>, String> {
118    // The same parser `load_config` uses, over `args_os`, so path flags that
119    // aren't valid UTF-8 arrive intact (Codex P2 on #3893).
120    let cli = <CliArgs as clap::Parser>::try_parse_from(std::env::args_os()).map_err(|e| e.to_string())?;
121    // Checked before anything is written, so a typo leaves no lock or key behind.
122    let origins = per_run_origin(&cli.allowed_origins, std::env::var(ALLOWED_ORIGIN_ENV).ok().as_deref())?;
123    let web = web_options(cli.frontend_dir.clone(), &origins, cli.public_origin.as_deref())?;
124    // The external host, if there is one, is registered here: once, before srv serves a connection or starts an agent.
125    if let Some(file) = &cli.external_host_key_file {
126        crate::server::external_host::register_from_file(file)?;
127    }
128    // A key srv did not generate is held to a floor when a browser can sign in: checked before anything is written.
129    let serves_ui = web.frontend_dir.is_some();
130    check_env_key(env_key().as_deref(), serves_ui)?;
131
132    let paths = match agentmux_common::DataPaths::from_env() {
133        Some(p) => p,
134        None => {
135            let mode = agentmux_common::RuntimeMode::from_env().unwrap_or(agentmux_common::RuntimeMode::Installed);
136            let p = agentmux_common::DataPaths::resolve(env!("CARGO_PKG_VERSION"), &mode)?;
137            p.ensure_dirs()?;
138            for (k, v) in p.to_env_vars() {
139                std::env::set_var(k, v);
140            }
141            p
142        }
143    };
144    // Every path is now explicit in the env, as the launcher leaves it. Drop the
145    // root override so srv resolves its stores the launcher's way — from the
146    // exported data dir — rather than at the override root, which would put
147    // every version's databases in one place (Codex P1 on #3893).
148    // Presence reads the variable too, to keep an isolated home off the account's list of computers: tell it first.
149    crate::muxbus::wan_presence::policy::note_isolated_home(std::env::var_os("AGENTMUX_HOME_OVERRIDE").as_deref());
150    std::env::remove_var("AGENTMUX_HOME_OVERRIDE");
151
152    // Lock the directory the databases actually live in — `--wavedata` when
153    // given (Config makes it the data home), else the resolved data dir — with
154    // the same lock every srv takes (`base::acquire_data_dir_lock`), and before
155    // writing anything there, so a second server can't clobber the first's key
156    // file (Codex P1/P2 on #3893).
157    let data_dir = effective_data_dir(cli.wavedata.as_deref(), &paths.data_dir);
158    std::fs::create_dir_all(&data_dir).map_err(|e| format!("cannot create {}: {e}", data_dir.display()))?;
159    let _ = DATA_DIR.set(data_dir.clone());
160    match crate::backend::base::acquire_data_dir_lock(&data_dir) {
161        Ok(()) => {}
162        Err(e @ crate::backend::base::DataDirLockError::Held { .. }) => {
163            // Another server (a desktop app, another launch) already uses this data folder. Exit with the
164            // same code the non-headless path uses, so the launcher shows its plain dialog and the CLI
165            // maps it to a line and exit 0 (a service must not restart-loop on a refusal that clears only
166            // when the other server closes). This is the headless path's only chance to say it: the lock
167            // is taken here, before bootstrap's own take (task #49109).
168            eprintln!("agentmux-srv: {e}");
169            std::process::exit(agentmux_common::srv_stderr::DATA_DIR_HELD_EXIT);
170        }
171        Err(e) => return Err(e.to_string()),
172    }
173
174    // Secrets: one store per machine, like the keychain, so under the shared
175    // dir rather than any one version's data dir.
176    if cli.secret_store.unwrap_or(SecretStoreKind::File) == SecretStoreKind::File {
177        crate::identity::secret_store::use_file_store(paths.shared_dir.join("secrets"))?;
178    }
179
180    let mut generated = None;
181    let mut binding = crate::server::local_session_file::KeyBinding::Generated;
182    if agentmux_common::secret_env::is_set("AGENTMUX_AUTH_KEY") {
183        if let Some(key) = env_key() {
184            binding = crate::server::local_session_file::KeyBinding::Provided(key.into_bytes());
185        }
186    } else {
187        let key_file = cli.auth_key_file.clone().or_else(|| std::env::var_os("AGENTMUX_AUTH_KEY_FILE").map(PathBuf::from));
188        let key = match key_file {
189            Some(file) => {
190                let key = read_provided_key_file(&file, serves_ui)?;
191                let _ = KEY_FILE.set(file);
192                binding = crate::server::local_session_file::KeyBinding::Provided(key.clone().into_bytes());
193                key
194            }
195            None => {
196                let (key, path) = write_generated_key(&data_dir)?;
197                let _ = KEY_FILE.set(path.clone());
198                generated = Some(path);
199                key
200            }
201        };
202        std::env::set_var("AGENTMUX_AUTH_KEY", key);
203    }
204
205    let _ = SESSION_BINDING.set(binding);
206    let _ = PORTS.set((cli.web_port, cli.ws_port));
207    let _ = WEB.set(web);
208
209    ACTIVE.store(true, std::sync::atomic::Ordering::SeqCst);
210    Ok(generated)
211}
212
213/// The directory srv will open its databases in: `--wavedata` if given (the
214/// same precedence `Config::from_env_and_args` applies), else `resolved`.
215fn effective_data_dir(wavedata: Option<&Path>, resolved: &Path) -> PathBuf {
216    wavedata
217        .filter(|p| !p.as_os_str().is_empty())
218        .unwrap_or(resolved)
219        .to_path_buf()
220}
221
222/// The environment variable a launcher that starts srv per run gives its one allowed origin in (a hosted
223/// workspace is served at a host of its own), as `--allowed-origin` would.
224pub const ALLOWED_ORIGIN_ENV: &str = "AGENTMUX_ALLOWED_ORIGIN";
225
226/// The origins to allow once `AGENTMUX_ALLOWED_ORIGIN` is taken into account. Unset or empty: `--allowed-origin`
227/// as given. Set: exactly that one origin, and nothing else (so a request from any other origin, including one
228/// an earlier launch allowed, is refused). It must be one `https` origin (a host, an optional port, no path,
229/// no wildcard, no list), and a `--allowed-origin` given too must name the same origin: srv refuses to start
230/// on a launch whose two forms disagree, rather than pick one.
231fn per_run_origin(cli: &[String], env: Option<&str>) -> Result<Vec<String>, String> {
232    let Some(raw) = env.map(str::trim).filter(|v| !v.is_empty()) else {
233        return Ok(cli.to_vec());
234    };
235    let name = ALLOWED_ORIGIN_ENV;
236    if raw.contains(['*', ',', ' ']) {
237        return Err(format!("{name} {raw:?}: one origin, with no wildcard or list"));
238    }
239    let origin = normalize_origin(raw).map_err(|e| format!("{name} {raw:?}: {e}"))?;
240    if !origin.starts_with("https://") {
241        return Err(format!("{name} {raw:?}: must be an https origin"));
242    }
243    for given in cli {
244        if normalize_origin(given).map_err(|e| format!("--allowed-origin {given:?}: {e}"))? != origin {
245            return Err(format!("--allowed-origin {given:?} and {name} {raw:?} name different origins"));
246        }
247    }
248    Ok(vec![origin])
249}
250
251fn web_options(frontend_dir: Option<PathBuf>, origins: &[String], public_origin: Option<&str>) -> Result<WebOptions, String> {
252    if let Some(dir) = &frontend_dir {
253        if !dir.join("index.html").is_file() {
254            return Err(format!("--frontend-dir {}: no index.html there", dir.display()));
255        }
256    }
257    let allowed_origins = origins
258        .iter()
259        .map(|o| normalize_origin(o).map_err(|e| format!("--allowed-origin {o:?}: {e}")))
260        .collect::<Result<_, _>>()?;
261    let public_origin = public_origin
262        .map(|o| {
263            if frontend_dir.is_none() {
264                return Err("--public-origin needs --frontend-dir".to_string());
265            }
266            normalize_public_origin(o).map_err(|e| format!("--public-origin {o:?}: {e}"))
267        })
268        .transpose()?;
269    Ok(WebOptions { frontend_dir, public_origin, allowed_origins })
270}
271
272/// The one origin a loopback sign-in accepts besides srv's own: `http://127.0.0.1:<port>`, the
273/// other end of a tunnel. Never a real host name, `localhost`, another address or `https`: a
274/// browser on a non-loopback origin needs a design of its own (SPEC_HEADLESS_SERVER_PACKAGE_AND_LOCAL_WEB_UI §3).
275pub(crate) fn normalize_public_origin(origin: &str) -> Result<String, String> {
276    let normalized = normalize_origin(origin)?;
277    let url = url::Url::parse(&normalized).map_err(|e| e.to_string())?;
278    let loopback = url.scheme() == "http" && url.host_str() == Some("127.0.0.1") && url.port().is_some();
279    if loopback { Ok(normalized) } else { Err("must be http://127.0.0.1:<port>".into()) }
280}
281
282/// Does this headless srv serve its own UI, so a browser signs in to it? (`--frontend-dir`.)
283pub fn local_sign_in() -> bool {
284    active() && frontend_dir().is_some()
285}
286
287/// `--public-origin`, when given.
288pub fn public_origin() -> Option<&'static str> {
289    WEB.get().and_then(|w| w.public_origin.as_deref())
290}
291
292/// The directory `--frontend-dir` named, when headless and given.
293pub fn frontend_dir() -> Option<&'static Path> {
294    WEB.get().and_then(|w| w.frontend_dir.as_deref())
295}
296
297/// Is `origin` one `--allowed-origin` named? Always false for a srv that
298/// isn't headless.
299pub fn is_extra_allowed_origin(origin: &str) -> bool {
300    WEB.get().is_some_and(|w| origin_in(origin, &w.allowed_origins))
301}
302
303fn origin_in(origin: &str, allowed: &[String]) -> bool {
304    normalize_origin(origin).is_ok_and(|o| allowed.contains(&o))
305}
306
307/// An origin as browsers send it, via the WHATWG URL parser browsers use:
308/// http or https, a host, an optional port — no path, user, query or
309/// fragment. Serialized the way `Origin` is: lowercase, IDNA hosts in
310/// punycode, canonical IPv4/IPv6, and no default port, so every spelling of
311/// one origin compares equal (Codex P2s on #3900). A trailing `/` is fine.
312fn normalize_origin(origin: &str) -> Result<String, String> {
313    const SHAPE: &str = "expected scheme://host[:port], with no path, user or query";
314    let url = url::Url::parse(origin.trim()).map_err(|e| format!("{SHAPE} ({e})"))?;
315    if !matches!(url.scheme(), "http" | "https") {
316        return Err("scheme must be http or https".into());
317    }
318    let only_origin = url.host().is_some()
319        && url.username().is_empty()
320        && url.password().is_none()
321        && url.path() == "/"
322        && url.query().is_none()
323        && url.fragment().is_none();
324    // `Url` drops an empty `?` / `#`; refuse them too.
325    if !only_origin || origin.contains(['?', '#', '@']) {
326        return Err(SHAPE.into());
327    }
328    agentmux_common::url_guard::origin_string(&url).ok_or_else(|| SHAPE.to_string())
329}
330
331/// Where this user's headless srv keeps its generated key: `<data dir>/srv-auth-key`, with the
332/// data dir resolved the way `prepare_env` does.
333pub fn key_file_path(wavedata: Option<&Path>) -> Result<PathBuf, String> {
334    if let Some(file) = std::env::var_os("AGENTMUX_AUTH_KEY_FILE").filter(|f| !f.is_empty()) {
335        return Ok(PathBuf::from(file));
336    }
337    let paths = match agentmux_common::DataPaths::from_env() {
338        Some(p) => p,
339        None => {
340            let mode = agentmux_common::RuntimeMode::from_env().unwrap_or(agentmux_common::RuntimeMode::Installed);
341            agentmux_common::DataPaths::resolve(env!("CARGO_PKG_VERSION"), &mode)?
342        }
343    };
344    Ok(effective_data_dir(wavedata, &paths.data_dir).join(AUTH_KEY_FILE_NAME))
345}
346
347/// The file that holds a headless srv's web port, beside its key file: `<key file>.port`. One name per
348/// key file, so the port is read for the server that key belongs to.
349pub(crate) fn port_file_path(key_file: &Path) -> PathBuf {
350    let mut name = key_file.file_name().unwrap_or_default().to_os_string();
351    name.push(".port");
352    key_file.with_file_name(name)
353}
354
355/// Write the web port beside the key file (owner-only), so `agentmux-srv open` finds this server
356/// without being told the port. Only a headless srv that serves its own UI and whose key came from a
357/// file. The file is replaced at every start and removed at a clean exit; after a crash it can name a
358/// port nobody listens on, or one another program now holds, which `open` meets with its proof of the
359/// key and refuses.
360pub(crate) fn publish_port(port: u16) {
361    let Some(key_file) = KEY_FILE.get().filter(|_| local_sign_in()) else { return };
362    let path = port_file_path(key_file);
363    let _ = std::fs::remove_file(&path);
364    let mut opts = std::fs::OpenOptions::new();
365    opts.write(true).create_new(true);
366    #[cfg(unix)]
367    {
368        use std::os::unix::fs::OpenOptionsExt;
369        opts.mode(0o600);
370    }
371    use std::io::Write;
372    if let Err(e) = opts.open(&path).and_then(|mut f| f.write_all(format!("{port}\n").as_bytes())) {
373        tracing::warn!(file = %path.display(), error = %e, "could not write the web port file; `agentmux-srv open` needs --port");
374        return;
375    }
376    // As a Windows service, the person who installed it reads the port as well as the key (`agentmux open` finds the server by it).
377    #[cfg(windows)]
378    {
379        let readers = agentmux_common::owner_only::key_readers();
380        if !readers.is_empty() {
381            if let Err(e) = agentmux_common::owner_only::restrict_to_user_and_readers(&path, &readers) {
382                tracing::warn!(file = %path.display(), error = %e, "could not let the person who installed the service read the web port file; `agentmux open` needs --port");
383            }
384        }
385    }
386}
387
388/// Where the browser sessions are kept across a restart (the data root's `sessions.bin`) and what the file is bound to. Only a
389/// headless srv that serves its own UI.
390pub(crate) fn session_file() -> Option<(PathBuf, crate::server::local_session_file::KeyBinding)> {
391    if !local_sign_in() {
392        return None;
393    }
394    Some((DATA_DIR.get()?.join(crate::server::local_session_file::FILE_NAME), SESSION_BINDING.get()?.clone()))
395}
396
397/// Remove the port file at a clean exit.
398pub(crate) fn withdraw_port_file() {
399    if let Some(key_file) = KEY_FILE.get().filter(|_| local_sign_in()) {
400        let _ = std::fs::remove_file(port_file_path(key_file));
401    }
402}
403
404/// The web port the server that owns `key_file` wrote beside it.
405pub(crate) fn read_port_file(key_file: &Path) -> Result<u16, String> {
406    let path = port_file_path(key_file);
407    let text = std::fs::read_to_string(&path).map_err(|_| format!("no {} (is the server running with its own UI? or pass --port)", path.display()))?;
408    text.trim().parse::<u16>().ok().filter(|p| *p != 0).ok_or_else(|| format!("{} does not hold a port (pass --port)", path.display()))
409}
410
411/// The fewest characters a key srv did not generate may have when srv serves its own UI. The
412/// sign-in's proof (`/auth/hello`) is a MAC under the key over values anyone can send, so a short
413/// key could be guessed offline from it; a generated key is 64 characters.
414pub(crate) const MIN_PROVIDED_KEY_CHARS: usize = 32;
415
416/// `AGENTMUX_AUTH_KEY`, as the launcher or the operator gave it (stashed at start, or still in the environment).
417fn env_key() -> Option<String> {
418    const NAME: &str = "AGENTMUX_AUTH_KEY";
419    agentmux_common::secret_env::stashed()
420        .into_iter()
421        .find(|(k, _)| k == NAME)
422        .map(|(_, v)| v)
423        .or_else(|| std::env::var(NAME).ok())
424        .filter(|v| !v.is_empty())
425}
426
427fn check_key_floor(key: &str, source: &str, serves_ui: bool) -> Result<(), String> {
428    if serves_ui && key.chars().count() < MIN_PROVIDED_KEY_CHARS {
429        return Err(format!(
430            "{source}: with --frontend-dir the key must be at least {MIN_PROVIDED_KEY_CHARS} characters; leave the key file out and srv generates one"
431        ));
432    }
433    Ok(())
434}
435
436/// The key from the environment, when there is one, held to the floor.
437fn check_env_key(key: Option<&str>, serves_ui: bool) -> Result<(), String> {
438    key.map_or(Ok(()), |k| check_key_floor(k, "AGENTMUX_AUTH_KEY", serves_ui))
439}
440
441/// A key file the operator provided, held to the floor.
442fn read_provided_key_file(path: &Path, serves_ui: bool) -> Result<String, String> {
443    let key = read_key_file(path)?;
444    check_key_floor(&key, &format!("--auth-key-file {}", path.display()), serves_ui)?;
445    Ok(key)
446}
447
448/// Read a key from a file the operator provided; surrounding whitespace is ignored.
449pub(crate) fn read_key_file(path: &Path) -> Result<String, String> {
450    let key = std::fs::read_to_string(path)
451        .map_err(|e| format!("--auth-key-file {}: {e}", path.display()))?
452        .trim()
453        .to_string();
454    if key.is_empty() {
455        return Err(format!("--auth-key-file {}: empty", path.display()));
456    }
457    Ok(key)
458}
459
460/// Generate a fresh key and write it to `<dir>/srv-auth-key`, readable by the
461/// owner only. A new key every start, like a launcher-spawned srv.
462fn write_generated_key(dir: &Path) -> Result<(String, PathBuf), String> {
463    let key = format!("{}{}", uuid::Uuid::new_v4().simple(), uuid::Uuid::new_v4().simple());
464    let path = dir.join(AUTH_KEY_FILE_NAME);
465    let _ = std::fs::remove_file(&path);
466    let mut opts = std::fs::OpenOptions::new();
467    opts.write(true).create_new(true);
468    #[cfg(unix)]
469    {
470        use std::os::unix::fs::OpenOptionsExt;
471        opts.mode(0o600);
472    }
473    use std::io::Write;
474    opts.open(&path)
475        .and_then(|mut f| f.write_all(key.as_bytes()))
476        .map_err(|e| format!("cannot write the auth key to {}: {e}", path.display()))?;
477    // Windows has no mode bits: the file's own access list gives it to the user and the system only, whatever the
478    // folder it is in lets others do.
479    #[cfg(windows)]
480    agentmux_common::owner_only::restrict_to_user_and_readers(&path, &agentmux_common::owner_only::key_readers())
481        .map_err(|e| format!("the auth key at {} could not be limited to you: {e}", path.display()))?;
482    Ok((key, path))
483}
484
485/// Bind a listener for this server's own use of its address. Windows lets programs share an address when they ask to
486/// (`SO_REUSEADDR`), and a program that did could then receive connections meant for this server, the sign-in among them;
487/// with `SO_EXCLUSIVEADDRUSE` the address is this server's alone and any other bind of it is refused, whatever it asks for.
488/// Elsewhere the system already refuses a second bind.
489pub(crate) async fn bind_exclusive(addr: &str) -> std::io::Result<tokio::net::TcpListener> {
490    let listener = bind_exclusive_to(addr).await?;
491    // A page in the streamed browser may never connect to a port this server listens on.
492    if let Ok(local) = listener.local_addr() {
493        crate::server::streamed_browser::note_own_port(local.port());
494    }
495    Ok(listener)
496}
497
498async fn bind_exclusive_to(addr: &str) -> std::io::Result<tokio::net::TcpListener> {
499    #[cfg(windows)]
500    {
501        use std::os::windows::io::AsRawSocket;
502        use windows_sys::Win32::Networking::WinSock::{setsockopt, SOCKET_ERROR, SOL_SOCKET, SO_EXCLUSIVEADDRUSE};
503        let wanted: std::net::SocketAddr = addr.parse().map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidInput, format!("{addr}: {e}")))?;
504        let socket = if wanted.is_ipv4() { tokio::net::TcpSocket::new_v4()? } else { tokio::net::TcpSocket::new_v6()? };
505        let on: i32 = 1;
506        // SAFETY: a socket this function owns, and a value that outlives the call.
507        let set = unsafe { setsockopt(socket.as_raw_socket() as usize, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (&on as *const i32).cast(), std::mem::size_of::<i32>() as i32) };
508        if set == SOCKET_ERROR {
509            return Err(std::io::Error::last_os_error());
510        }
511        socket.bind(wanted)?;
512        socket.listen(1024)
513    }
514    #[cfg(not(windows))]
515    {
516        tokio::net::TcpListener::bind(addr).await
517    }
518}
519
520/// The address a startup listener binds: `STARTUP_BIND_ADDR` (loopback,
521/// OS-chosen port) — or, headless only, the same loopback host with the port
522/// `--web-port` / `--ws-port` gave. A non-headless srv always gets the default.
523pub fn startup_bind_addr(listener: Listener) -> String {
524    let fixed = PORTS.get().and_then(|(web, ws)| match listener {
525        Listener::Web => *web,
526        Listener::Ws => *ws,
527    });
528    bind_addr_with(fixed)
529}
530
531fn bind_addr_with(port: Option<u16>) -> String {
532    let default = crate::backend::lan::listeners::STARTUP_BIND_ADDR;
533    match port {
534        Some(port) => {
535            let host = default.rsplit_once(':').map(|(h, _)| h).unwrap_or(default);
536            format!("{host}:{port}")
537        }
538        None => default.to_string(),
539    }
540}
541
542#[cfg(test)]
543mod tests {
544    use super::*;
545
546    fn args(v: &[&str]) -> Vec<OsString> {
547        v.iter().map(OsString::from).collect()
548    }
549
550    fn cli(v: &[&str]) -> CliArgs {
551        <CliArgs as clap::Parser>::try_parse_from(args(v)).unwrap()
552    }
553
554    /// A second bind of an address the server holds is refused, even by a program that asks to share it.
555    #[tokio::test]
556    async fn the_address_the_server_holds_is_not_given_to_a_second_binder() {
557        let held = bind_exclusive("127.0.0.1:0").await.unwrap();
558        let addr = held.local_addr().unwrap();
559        assert!(bind_exclusive(&addr.to_string()).await.is_err(), "a second exclusive bind");
560        let sharing = tokio::net::TcpSocket::new_v4().unwrap();
561        sharing.set_reuseaddr(true).unwrap();
562        let got = sharing.bind(addr).and_then(|()| sharing.listen(16).map(|_| ()));
563        assert!(got.is_err(), "a bind that asks to share the address must not get it");
564        // The holder still answers.
565        let client = tokio::net::TcpStream::connect(addr).await.unwrap();
566        let (_server_side, _) = held.accept().await.unwrap();
567        drop(client);
568    }
569
570    #[test]
571    fn an_origin_must_be_a_plain_http_or_https_one() {
572        assert_eq!(normalize_origin("HTTPS://Example.com:443/").unwrap(), "https://example.com");
573        let deep = format!("{}https://example.com/", "blob:".repeat(50_000));
574        for bad in ["blob:https://example.com/", "blob:blob:https://example.com/", deep.as_str()] {
575            assert!(normalize_origin(bad).is_err(), "{}", &bad[..bad.len().min(40)]);
576        }
577    }
578
579    #[test]
580    fn headless_is_requested_by_flag_or_env() {
581        assert!(requested_from(&args(&["srv", "--headless"]), None));
582        assert!(requested_from(&args(&["srv"]), Some("1")));
583        assert!(!requested_from(&args(&["srv", "--wavedata", "x"]), None));
584        assert!(!requested_from(&args(&["srv"]), Some("0")));
585    }
586
587    /// A subcommand, --help or --version never runs the headless setup (or
588    /// takes its lock), even with AGENTMUX_HEADLESS=1 set for the whole env.
589    #[test]
590    fn a_subcommand_or_help_is_never_headless() {
591        assert!(!requested_from(&args(&["srv", "migrate", "--verify"]), Some("1")));
592        assert!(!requested_from(&args(&["srv", "--headless", "migrate", "--list"]), None));
593        assert!(!requested_from(&args(&["srv", "--headless", "--help"]), None));
594        assert!(!requested_from(&args(&["srv", "--help"]), Some("1")));
595    }
596
597    /// The lock goes where the databases go: --wavedata wins, as in Config.
598    #[test]
599    fn the_lock_follows_wavedata() {
600        let resolved = Path::new("/home/u/.agentmux/channels/stable/versions/1/data");
601        let dir = |v: &[&str]| effective_data_dir(cli(v).wavedata.as_deref(), resolved);
602        assert_eq!(dir(&["srv", "--headless"]), resolved);
603        assert_eq!(dir(&["srv", "--headless", "--wavedata", "/shared"]), Path::new("/shared"));
604        assert_eq!(dir(&["srv", "--wavedata=/shared"]), Path::new("/shared"));
605        // An empty --wavedata is a parse error (clap's PathBuf parser), so
606        // prepare_env exits before taking any lock; Config also treats an
607        // empty value as absent (Codex P2 on #3893).
608        assert!(<CliArgs as clap::Parser>::try_parse_from(args(&["srv", "--headless", "--wavedata", ""])).is_err());
609        assert!(<CliArgs as clap::Parser>::try_parse_from(args(&["srv", "--headless", "--wavedata="])).is_err());
610        assert!(requested_from(&args(&["srv", "--headless", "--wavedata", ""]), None));
611        assert_eq!(effective_data_dir(Some(Path::new("")), resolved), resolved);
612    }
613
614    /// A `--wavedata` that isn't valid UTF-8 is locked byte for byte, the same
615    /// directory Config then opens the stores in.
616    #[cfg(unix)]
617    #[test]
618    fn a_non_utf8_wavedata_is_kept() {
619        use std::ffi::OsStr;
620        use std::os::unix::ffi::OsStrExt;
621        let raw = OsStr::from_bytes(b"/data/caf\xe9");
622        let a = vec![OsString::from("srv"), OsString::from("--headless"), OsString::from("--wavedata"), raw.to_os_string()];
623        assert!(requested_from(&a, None));
624        let parsed = <CliArgs as clap::Parser>::try_parse_from(a).unwrap();
625        assert_eq!(effective_data_dir(parsed.wavedata.as_deref(), Path::new("/x")).as_os_str(), raw);
626    }
627
628    #[test]
629    fn secret_store_flag_parses() {
630        assert_eq!(cli(&["srv", "--headless"]).secret_store, None);
631        assert_eq!(cli(&["srv", "--headless", "--secret-store", "keychain"]).secret_store, Some(SecretStoreKind::Keychain));
632        assert_eq!(cli(&["srv", "--headless", "--secret-store=file"]).secret_store, Some(SecretStoreKind::File));
633        assert!(<CliArgs as clap::Parser>::try_parse_from(args(&["srv", "--secret-store", "vault"])).is_err());
634    }
635
636    #[test]
637    fn flags_parse_in_both_forms() {
638        let c = cli(&["srv", "--headless", "--web-port", "8190", "--ws-port=8191"]);
639        assert_eq!((c.web_port, c.ws_port), (Some(8190), Some(8191)));
640        assert_eq!(c.auth_key_file, None);
641        assert!(<CliArgs as clap::Parser>::try_parse_from(args(&["srv", "--web-port", "x"])).is_err());
642    }
643
644    #[test]
645    fn origins_normalize_the_way_browsers_send_them() {
646        let n = |o: &str| normalize_origin(o);
647        assert_eq!(n("https://App.Example.com").unwrap(), "https://app.example.com");
648        assert_eq!(n("https://app.example.com/").unwrap(), "https://app.example.com");
649        assert_eq!(n("https://app.example.com:443").unwrap(), "https://app.example.com");
650        assert_eq!(n("http://app.example.com:80").unwrap(), "http://app.example.com");
651        assert_eq!(n("https://app.example.com:8443").unwrap(), "https://app.example.com:8443");
652        assert_eq!(n("http://[::1]:8190").unwrap(), "http://[::1]:8190");
653        assert_eq!(n("https://app.example.com:0443").unwrap(), "https://app.example.com");
654        assert_eq!(n("https://app.example.com:08443").unwrap(), "https://app.example.com:8443");
655        assert_eq!(n("http://[0:0:0:0:0:0:0:1]:8190").unwrap(), "http://[::1]:8190");
656        assert_eq!(n("http://127.1:8190").unwrap(), "http://127.0.0.1:8190");
657        // An empty port is the default one, as browsers parse it.
658        assert_eq!(n("https://app.example.com:").unwrap(), "https://app.example.com");
659        assert_eq!(n("https://bücher.example").unwrap(), "https://xn--bcher-kva.example");
660        for bad in [
661            "app.example.com",
662            "ftp://app.example.com",
663            "https://",
664            "https://app.example.com/path",
665            "https://user@app.example.com",
666            "https://app.example.com?x=1",
667            "https://app.example.com?",
668            "https://app.example.com#",
669            "https://user:pw@app.example.com",
670            "https://app.example.com:99999",
671            "http://[evil/x]",
672            "*",
673            "null",
674        ] {
675            assert!(n(bad).is_err(), "{bad} should be rejected");
676        }
677    }
678
679    #[test]
680    fn only_the_named_origins_are_added() {
681        let allowed = vec![normalize_origin("https://app.example.com").unwrap()];
682        assert!(origin_in("https://app.example.com", &allowed));
683        assert!(origin_in("https://APP.example.com:443", &allowed));
684        assert!(!origin_in("http://app.example.com", &allowed));
685        assert!(!origin_in("https://app.example.com.evil.test", &allowed));
686        assert!(!origin_in("https://evil.test", &allowed));
687        assert!(!origin_in("null", &allowed));
688        assert!(!origin_in("https://app.example.com", &[]));
689    }
690
691    #[test]
692    fn frontend_dir_needs_an_index_and_origins_must_parse() {
693        let dir = tempfile::tempdir().unwrap();
694        assert!(web_options(Some(dir.path().to_path_buf()), &[], None).is_err());
695        std::fs::write(dir.path().join("index.html"), "<!doctype html>").unwrap();
696        let w = web_options(Some(dir.path().to_path_buf()), &["https://App.example.com/".into()], None).unwrap();
697        assert_eq!(w.allowed_origins, vec!["https://app.example.com".to_string()]);
698        assert!(web_options(None, &["https://app.example.com/ui".into()], None).is_err());
699        let c = cli(&["srv", "--headless", "--allowed-origin", "https://a.test", "--allowed-origin=https://b.test"]);
700        assert_eq!(c.allowed_origins, vec!["https://a.test", "https://b.test"]);
701    }
702
703    /// The declared origin only moves the port: loopback address, http, a port. Nothing else starts.
704    #[test]
705    fn the_public_origin_is_loopback_http_with_a_port() {
706        let dir = tempfile::tempdir().unwrap();
707        std::fs::write(dir.path().join("index.html"), "<!doctype html>").unwrap();
708        let web = |o: &str| web_options(Some(dir.path().to_path_buf()), &[], Some(o));
709        assert_eq!(web("http://127.0.0.1:8080").unwrap().public_origin.as_deref(), Some("http://127.0.0.1:8080"));
710        assert_eq!(web("http://127.1:8080/").unwrap().public_origin.as_deref(), Some("http://127.0.0.1:8080"));
711        for bad in [
712            "http://localhost:8080",
713            "http://127.0.0.1",
714            "https://127.0.0.1:8080",
715            "http://[::1]:8080",
716            "http://203.0.113.7:8080",
717            "http://app.example.com:8080",
718            "https://app.example.com",
719            "http://127.0.0.1:8080/ui",
720            "*",
721        ] {
722            assert!(web(bad).is_err(), "{bad} should be refused");
723        }
724        assert!(web_options(None, &[], Some("http://127.0.0.1:8080")).is_err(), "it names a UI to sign in to");
725        assert_eq!(cli(&["srv", "--headless", "--public-origin", "http://127.0.0.1:8080"]).public_origin.as_deref(), Some("http://127.0.0.1:8080"));
726    }
727
728    /// A srv that isn't headless never set WEB: no extra origins, no frontend.
729    #[test]
730    fn a_non_headless_srv_adds_nothing() {
731        assert!(!is_extra_allowed_origin("https://app.example.com"));
732        assert!(frontend_dir().is_none());
733        assert!(!local_sign_in());
734        assert!(public_origin().is_none());
735    }
736
737    #[test]
738    fn generated_key_is_written_owner_only_and_fresh_each_time() {
739        let dir = tempfile::tempdir().unwrap();
740        let (k1, p1) = write_generated_key(dir.path()).unwrap();
741        assert_eq!(std::fs::read_to_string(&p1).unwrap(), k1);
742        assert_eq!(k1.len(), 64);
743        #[cfg(unix)]
744        {
745            use std::os::unix::fs::PermissionsExt;
746            let mode = std::fs::metadata(&p1).unwrap().permissions().mode() & 0o777;
747            assert_eq!(mode, 0o600);
748        }
749        let (k2, _) = write_generated_key(dir.path()).unwrap();
750        assert_ne!(k1, k2);
751        assert_eq!(std::fs::read_to_string(&p1).unwrap(), k2);
752    }
753
754    #[test]
755    fn key_file_is_trimmed_and_must_not_be_empty() {
756        let dir = tempfile::tempdir().unwrap();
757        let p = dir.path().join("k");
758        std::fs::write(&p, "  secret-key\n").unwrap();
759        assert_eq!(read_key_file(&p).unwrap(), "secret-key");
760        std::fs::write(&p, "\n").unwrap();
761        assert!(read_key_file(&p).is_err());
762        assert!(read_key_file(&dir.path().join("missing")).is_err());
763    }
764
765    /// With a UI served, a key srv did not generate needs a floor, from a file and from the environment alike.
766    #[test]
767    fn a_provided_key_has_a_floor_when_srv_serves_its_own_ui() {
768        let dir = tempfile::tempdir().unwrap();
769        let p = dir.path().join("k");
770        let long = "k".repeat(MIN_PROVIDED_KEY_CHARS);
771        let short = "k".repeat(MIN_PROVIDED_KEY_CHARS - 1);
772
773        std::fs::write(&p, &short).unwrap();
774        let err = read_provided_key_file(&p, true).unwrap_err();
775        assert!(err.contains("at least 32") && err.contains("leave the key file out") && err.contains("--auth-key-file"), "{err}");
776        assert_eq!(read_provided_key_file(&p, false).unwrap(), short, "no UI served: no floor");
777        std::fs::write(&p, format!("{long}\n")).unwrap();
778        assert_eq!(read_provided_key_file(&p, true).unwrap(), long);
779
780        let err = check_env_key(Some(&short), true).unwrap_err();
781        assert!(err.contains("AGENTMUX_AUTH_KEY") && err.contains("at least 32"), "{err}");
782        assert!(check_env_key(Some(&short), false).is_ok());
783        assert!(check_env_key(Some(&long), true).is_ok());
784        assert!(check_env_key(None, true).is_ok(), "no environment key: srv generates one");
785        // Characters, not bytes.
786        assert!(check_key_floor(&"é".repeat(MIN_PROVIDED_KEY_CHARS), "x", true).is_ok());
787        assert!(check_key_floor(&"é".repeat(MIN_PROVIDED_KEY_CHARS - 1), "x", true).is_err());
788        // What srv generates itself passes.
789        assert!(format!("{}{}", uuid::Uuid::new_v4().simple(), uuid::Uuid::new_v4().simple()).chars().count() >= MIN_PROVIDED_KEY_CHARS);
790    }
791
792    #[test]
793    fn bind_addr_is_the_startup_address_or_its_host_with_a_fixed_port() {
794        let default = crate::backend::lan::listeners::STARTUP_BIND_ADDR;
795        assert_eq!(bind_addr_with(None), default);
796        assert_eq!(bind_addr_with(Some(8190)), "127.0.0.1:8190");
797    }
798
799    /// Only `prepare_env` sets the fixed ports, and only in-process: a srv
800    /// that isn't headless binds the default whatever its env says.
801    #[test]
802    fn a_non_headless_srv_ignores_port_env() {
803        std::env::set_var("AGENTMUX_SRV_WEB_PORT", "8190");
804        assert_eq!(
805            startup_bind_addr(Listener::Web),
806            crate::backend::lan::listeners::STARTUP_BIND_ADDR
807        );
808        std::env::remove_var("AGENTMUX_SRV_WEB_PORT");
809    }
810
811    #[test]
812    fn the_data_dir_lock_is_reentrant_here_and_exclusive_otherwise() {
813        use crate::backend::base::{acquire_data_dir_lock, MuxLock, MuxLockError, SRV_DATA_LOCK_FILE};
814        let dir = tempfile::tempdir().unwrap();
815        acquire_data_dir_lock(dir.path()).unwrap();
816        // Headless takes it early, bootstrap again later: fine in one process.
817        acquire_data_dir_lock(dir.path()).unwrap();
818        // Anyone else is refused while it's held, on every platform (a second handle in this same
819        // process counts as anyone else). This is the guard that keeps a desktop app and a headless
820        // server from sharing one data folder; on Windows it was a no-op before task #49109.
821        let err = MuxLock::acquire_at(&dir.path().join(SRV_DATA_LOCK_FILE)).err().expect("the lock is held");
822        assert_eq!(err, MuxLockError::Held);
823    }
824}
825
826#[cfg(test)]
827mod per_run_origin_tests {
828    use super::*;
829
830    fn v(items: &[&str]) -> Vec<String> {
831        items.iter().map(|s| s.to_string()).collect()
832    }
833
834    #[test]
835    fn without_the_variable_the_flag_is_as_given() {
836        assert_eq!(per_run_origin(&v(&["https://a.example"]), None), Ok(v(&["https://a.example"])));
837        assert_eq!(per_run_origin(&v(&["https://a.example"]), Some("  ")), Ok(v(&["https://a.example"])));
838        assert_eq!(per_run_origin(&[], None), Ok(vec![]));
839    }
840
841    #[test]
842    fn the_variable_alone_allows_that_origin_and_a_request_from_the_old_shared_one_is_refused() {
843        let allowed = per_run_origin(&[], Some("https://w1.web.example")).unwrap();
844        assert_eq!(allowed, v(&["https://w1.web.example"]));
845        assert!(origin_in("https://w1.web.example", &allowed));
846        assert!(origin_in("HTTPS://W1.web.example/", &allowed), "every spelling of the same origin");
847        assert!(!origin_in("https://app.example", &allowed), "the old shared origin");
848        assert!(!origin_in("https://w2.web.example", &allowed), "another workspace's");
849    }
850
851    #[test]
852    fn the_flag_and_the_variable_must_agree_or_srv_does_not_start() {
853        assert_eq!(per_run_origin(&v(&["https://w1.web.example/"]), Some("https://W1.web.example")), Ok(v(&["https://w1.web.example"])));
854        let e = per_run_origin(&v(&["https://app.example"]), Some("https://w1.web.example")).unwrap_err();
855        assert!(e.contains("different origins"), "{e}");
856        assert!(per_run_origin(&v(&["https://w1.web.example", "https://app.example"]), Some("https://w1.web.example")).is_err());
857    }
858
859    #[test]
860    fn the_variable_is_one_https_origin_and_nothing_looser() {
861        for bad in [
862            "http://w1.web.example",
863            "https://*.web.example",
864            "https://w1.web.example,https://w2.web.example",
865            "https://w1.web.example https://w2.web.example",
866            "https://w1.web.example/path",
867            "https://user@w1.web.example",
868            "w1.web.example",
869            "https://",
870        ] {
871            assert!(per_run_origin(&[], Some(bad)).is_err(), "{bad}");
872        }
873    }
874}