Skip to main content

lean_ctx/
proxy_autostart.rs

1#[cfg(any(target_os = "macos", target_os = "linux"))]
2use std::net::{IpAddr, Ipv4Addr, SocketAddr, TcpStream};
3#[cfg(any(target_os = "macos", target_os = "linux"))]
4use std::path::PathBuf;
5#[cfg(any(target_os = "macos", target_os = "linux"))]
6use std::time::{Duration, Instant};
7
8#[cfg(target_os = "macos")]
9const PLIST_LABEL: &str = "com.leanctx.proxy";
10#[cfg(target_os = "linux")]
11const SYSTEMD_SERVICE: &str = "lean-ctx-proxy";
12
13/// PID the proxy on this instance's configured port reports in `/health`,
14/// on every platform. Used by the lifecycle commands to stop the proxy this
15/// instance owns — never by process name (#2176). The caller still gates the
16/// PID by command line and process identity before signalling it.
17pub(crate) fn recorded_proxy_pid() -> Option<u32> {
18    let port = crate::core::proxy_endpoint::default_port();
19    // The account's default port belongs to the default install. Another
20    // instance (directory override, sandbox HOME) owns a proxy only on a port
21    // it configured itself; otherwise `stop` from a scratch data dir stopped
22    // the user's real proxy (5 Nov 2026).
23    if !crate::daemon_autostart::controls_user_services()
24        && port == crate::core::proxy_endpoint::uid_based_port()
25    {
26        return None;
27    }
28    health_proxy_pid(port)
29}
30
31/// PID a lean-ctx proxy on `port` reports in `/health`. Only an answer that
32/// identifies itself as the lean-ctx proxy counts (#2176 review #5); the PID
33/// is still only a candidate — `ipc::process` gates it by command line,
34/// executable and user (the caller's uid / token SID) before any signal.
35#[must_use]
36pub fn health_proxy_pid(port: u16) -> Option<u32> {
37    let response = ureq::get(&format!("http://127.0.0.1:{port}/health"))
38        .config()
39        .timeout_global(Some(std::time::Duration::from_millis(500)))
40        .build()
41        .call()
42        .ok()?;
43    let body = response.into_body().read_to_string().ok()?;
44    proxy_pid_from_health(&body)
45}
46
47fn proxy_pid_from_health(body: &str) -> Option<u32> {
48    let health: serde_json::Value = serde_json::from_str(body).ok()?;
49    if health.get("status").and_then(serde_json::Value::as_str) != Some("ok")
50        || !health_identifies_lean_ctx_proxy(body)
51    {
52        return None;
53    }
54    let pid = u32::try_from(health.get("pid")?.as_u64()?).ok()?;
55    (pid > 0).then_some(pid)
56}
57
58fn health_identifies_lean_ctx_proxy(body: &str) -> bool {
59    serde_json::from_str::<serde_json::Value>(body)
60        .ok()
61        .and_then(|health| health.get("service")?.as_str().map(str::to_owned))
62        .is_some_and(|service| service == "lean-ctx-proxy")
63}
64
65/// The lean-ctx proxy of this user listening on `port`, gated like every
66/// other lifecycle target: `/health` names it, and the PID passes the
67/// command-line, executable, user and identity checks.
68#[must_use]
69pub fn proxy_on_port(port: u16) -> Option<crate::ipc::process::ServiceProcess> {
70    use crate::ipc::process::{RecordedPid, ServiceKind, ServiceSweep, find_service_processes};
71    let pid = health_proxy_pid(port)?;
72    find_service_processes(
73        &[RecordedPid::bare(pid)],
74        ServiceSweep::Only(ServiceKind::Proxy),
75    )
76    .into_iter()
77    .next()
78}
79
80#[cfg(any(target_os = "macos", target_os = "linux"))]
81fn port_is_open(port: u16) -> bool {
82    let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), port);
83    TcpStream::connect_timeout(&addr, Duration::from_millis(150)).is_ok()
84}
85
86/// Stop a proxy already owning `port` before a managed service is started.
87///
88/// Returns `false` when the listener cannot be positively identified as a
89/// lean-ctx proxy or when it does not release the port. Managed startup must
90/// fail closed in either case; otherwise launchd/systemd would enter a restart
91/// loop on `EADDRINUSE`.
92#[cfg(any(target_os = "macos", target_os = "linux"))]
93fn release_proxy_port(port: u16, quiet: bool) -> bool {
94    if !port_is_open(port) {
95        return true;
96    }
97
98    // The account's default port belongs to the default install: another
99    // instance never signals the proxy listening there, whatever `/health`
100    // reports (the same rule as `recorded_proxy_pid`, 6 Nov 2026).
101    if !crate::daemon_autostart::controls_user_services()
102        && port == crate::core::proxy_endpoint::uid_based_port()
103    {
104        if !quiet {
105            eprintln!(
106                "  Refusing managed proxy startup: port {port} belongs to the default install."
107            );
108        }
109        return false;
110    }
111
112    // #2176 review: the `/health` PID is signalled only while it is this
113    // user's lean-ctx proxy (command line, executable, identity); never this
114    // process or its ancestors. Anything else fails closed.
115    let Some(proxy) = proxy_on_port(port) else {
116        if !quiet {
117            eprintln!(
118                "  Refusing managed proxy startup: port {port} is occupied by an unidentified service."
119            );
120        }
121        return false;
122    };
123    let pid = proxy.pid;
124
125    proxy.signal(crate::ipc::process::StopSignal::Terminate);
126    let graceful_deadline = Instant::now() + Duration::from_secs(2);
127    while Instant::now() < graceful_deadline {
128        if !proxy.is_running() && !port_is_open(port) {
129            if !quiet {
130                eprintln!(
131                    "  Handed port {port} from standalone proxy PID {pid} to managed service."
132                );
133            }
134            return true;
135        }
136        std::thread::sleep(Duration::from_millis(50));
137    }
138
139    if proxy.is_running() {
140        proxy.signal(crate::ipc::process::StopSignal::Kill);
141    }
142    let force_deadline = Instant::now() + Duration::from_secs(1);
143    while Instant::now() < force_deadline {
144        if !port_is_open(port) {
145            if !quiet {
146                eprintln!(
147                    "  Handed port {port} from standalone proxy PID {pid} to managed service."
148                );
149            }
150            return true;
151        }
152        std::thread::sleep(Duration::from_millis(50));
153    }
154
155    if !quiet {
156        eprintln!("  Refusing managed proxy startup: port {port} was not released by PID {pid}.");
157    }
158    false
159}
160
161pub fn install(port: u16, quiet: bool) -> bool {
162    let binary = find_binary();
163    install_with_binary(&binary, port, quiet)
164}
165
166/// Install (or rewrite) and start the proxy autostart service. Refused for
167/// another instance (a directory override or a sandbox HOME): the service
168/// manager addresses the unit by name, so the stop, port hand-off, unit
169/// rewrite and `enable --now` would act on the default install's proxy
170/// (6 Nov 2026, see [`crate::daemon_autostart::controls_user_services`]).
171pub fn install_with_binary(binary: &str, port: u16, quiet: bool) -> bool {
172    if !crate::daemon_autostart::controls_user_services() {
173        if !quiet {
174            eprintln!("  {}", crate::daemon_autostart::not_this_instance_message());
175        }
176        return false;
177    }
178    if binary.is_empty() {
179        if !quiet {
180            tracing::error!("Cannot find lean-ctx binary for autostart");
181        }
182        return false;
183    }
184
185    #[cfg(target_os = "macos")]
186    {
187        install_launchagent(binary, port, quiet)
188    }
189
190    #[cfg(target_os = "linux")]
191    {
192        install_systemd(binary, port, quiet)
193    }
194
195    #[cfg(not(any(target_os = "macos", target_os = "linux")))]
196    {
197        let _ = (binary, quiet);
198        println!("  Autostart not supported on this platform");
199        println!("  Run manually: lean-ctx proxy start --port={port}");
200        false
201    }
202}
203
204/// Stop the proxy's autostart service. A no-op for another instance (a
205/// directory override or a sandbox HOME): the service manager addresses the
206/// unit by name, and it belongs to the default install (5 Nov 2026, see
207/// [`crate::daemon_autostart::controls_user_services`]).
208pub fn stop() {
209    if !crate::daemon_autostart::controls_user_services() {
210        return;
211    }
212    #[cfg(target_os = "macos")]
213    {
214        let plist_path = launchagent_path();
215        if plist_path.exists() {
216            crate::core::launchd::bootout(PLIST_LABEL, &plist_path);
217        }
218    }
219
220    #[cfg(target_os = "linux")]
221    {
222        let _ = std::process::Command::new("systemctl")
223            .args(["--user", "stop", SYSTEMD_SERVICE])
224            .output();
225    }
226}
227
228pub fn start() -> bool {
229    start_on_port(crate::core::proxy_endpoint::default_port())
230}
231
232/// Start the installed manager after atomically taking ownership of `port`.
233/// This also handles the case where an IDE/dashboard spawned a standalone
234/// proxy while the manager was temporarily unloaded.
235pub fn start_on_port(port: u16) -> bool {
236    if !crate::daemon_autostart::controls_user_services() {
237        return false;
238    }
239    #[cfg(target_os = "macos")]
240    {
241        let plist_path = launchagent_path();
242        if plist_path.exists() {
243            crate::core::launchd::bootout(PLIST_LABEL, &plist_path);
244            if !release_proxy_port(port, false) {
245                return false;
246            }
247            // Same layout as the CLI that (re)starts it, not the one that
248            // installed it: a stale `LEAN_CTX_*_DIR` pin is replaced.
249            crate::daemon_autostart::repin_launchagent(&plist_path);
250            return crate::core::launchd::bootstrap(PLIST_LABEL, &plist_path);
251        }
252        false
253    }
254
255    #[cfg(target_os = "linux")]
256    {
257        let _ = std::process::Command::new("systemctl")
258            .args(["--user", "stop", SYSTEMD_SERVICE])
259            .output();
260        if release_proxy_port(port, false) {
261            std::process::Command::new("systemctl")
262                .args(["--user", "start", SYSTEMD_SERVICE])
263                .status()
264                .is_ok_and(|status| status.success())
265        } else {
266            false
267        }
268    }
269
270    #[cfg(not(any(target_os = "macos", target_os = "linux")))]
271    {
272        let _ = port;
273        false
274    }
275}
276
277/// Stop, disable and remove the proxy autostart service. A no-op for another
278/// instance, like [`install_with_binary`].
279pub fn uninstall(quiet: bool) {
280    if !crate::daemon_autostart::controls_user_services() {
281        if !quiet {
282            println!("  {}", crate::daemon_autostart::not_this_instance_message());
283        }
284        return;
285    }
286    #[cfg(target_os = "macos")]
287    uninstall_launchagent(quiet);
288
289    #[cfg(target_os = "linux")]
290    uninstall_systemd(quiet);
291}
292
293/// Whether this platform has a proxy-autostart backend (LaunchAgent on macOS,
294/// systemd user service on Linux). Windows and other targets have none, so a
295/// missing autostart there must not be treated as a failure by `doctor` (#416).
296pub fn is_supported() -> bool {
297    cfg!(any(target_os = "macos", target_os = "linux"))
298}
299
300/// Returns true if the proxy autostart is installed (plist/systemd service file exists).
301/// Always false for another instance: the service is not its own.
302pub fn is_installed() -> bool {
303    if !crate::daemon_autostart::controls_user_services() {
304        return false;
305    }
306    #[cfg(target_os = "macos")]
307    {
308        launchagent_path().exists()
309    }
310    #[cfg(target_os = "linux")]
311    {
312        systemd_path().exists()
313    }
314    #[cfg(not(any(target_os = "macos", target_os = "linux")))]
315    {
316        false
317    }
318}
319
320/// Returns true when the installed manager is actively responsible for the proxy.
321/// Callers must not spawn a second foreground proxy while this is true.
322/// Always false for another instance (no `systemctl`/`launchctl` query).
323pub fn is_loaded() -> bool {
324    if !crate::daemon_autostart::controls_user_services() {
325        return false;
326    }
327    #[cfg(target_os = "macos")]
328    {
329        is_installed() && crate::core::launchd::is_loaded(PLIST_LABEL)
330    }
331    #[cfg(target_os = "linux")]
332    {
333        is_installed()
334            && std::process::Command::new("systemctl")
335                .args(["--user", "is-active", "--quiet", SYSTEMD_SERVICE])
336                .status()
337                .is_ok_and(|status| status.success())
338    }
339    #[cfg(not(any(target_os = "macos", target_os = "linux")))]
340    {
341        false
342    }
343}
344
345pub fn status() {
346    if !crate::daemon_autostart::controls_user_services() {
347        println!("  {}", crate::daemon_autostart::not_this_instance_message());
348        return;
349    }
350    #[cfg(target_os = "macos")]
351    {
352        let plist_path = launchagent_path();
353        if plist_path.exists() {
354            println!("  LaunchAgent: installed at {}", plist_path.display());
355            if crate::core::launchd::is_loaded(PLIST_LABEL) {
356                println!("  Status: loaded");
357            } else {
358                println!("  Status: not loaded (run: lean-ctx proxy start)");
359            }
360        } else {
361            println!("  LaunchAgent: not installed");
362        }
363    }
364
365    #[cfg(target_os = "linux")]
366    {
367        let service_path = systemd_path();
368        if service_path.exists() {
369            println!("  systemd user service: installed");
370            let output = std::process::Command::new("systemctl")
371                .args(["--user", "is-active", SYSTEMD_SERVICE])
372                .output();
373            match output {
374                Ok(o) => {
375                    let state = String::from_utf8_lossy(&o.stdout).trim().to_string();
376                    println!("  Status: {state}");
377                }
378                Err(_) => println!("  Status: unknown"),
379            }
380        } else {
381            println!("  systemd service: not installed");
382        }
383    }
384
385    #[cfg(not(any(target_os = "macos", target_os = "linux")))]
386    {
387        println!("  Autostart not available on this platform");
388    }
389}
390
391#[cfg(target_os = "macos")]
392fn launchagent_path() -> PathBuf {
393    dirs::home_dir()
394        .unwrap_or_else(|| PathBuf::from("/tmp"))
395        .join("Library/LaunchAgents")
396        .join(format!("{PLIST_LABEL}.plist"))
397}
398
399#[cfg(target_os = "macos")]
400fn install_launchagent(binary: &str, port: u16, quiet: bool) -> bool {
401    let plist_dir = dirs::home_dir()
402        .unwrap_or_else(|| PathBuf::from("/tmp"))
403        .join("Library/LaunchAgents");
404    let _ = std::fs::create_dir_all(&plist_dir);
405
406    let plist_path = plist_dir.join(format!("{PLIST_LABEL}.plist"));
407    // Stop the registered job first, then take over any standalone proxy an
408    // IDE/dashboard may have spawned while launchd was unloaded. Starting the
409    // new job with an occupied port causes an unconditional KeepAlive loop.
410    crate::core::launchd::bootout(PLIST_LABEL, &plist_path);
411    if !release_proxy_port(port, quiet) {
412        return false;
413    }
414    // GH #439: proxy logs are STATE — resolve through the typed dir so a
415    // post-split install writes to $XDG_STATE_HOME/lean-ctx/logs instead of a
416    // re-created ~/.lean-ctx. Legacy single-dir installs still resolve here.
417    let log_dir = crate::core::paths::state_dir()
418        .unwrap_or_else(|_| std::env::temp_dir().join("lean-ctx"))
419        .join("logs");
420    let _ = std::fs::create_dir_all(&log_dir);
421
422    // rc2-2: the binary itself is ProgramArguments[0], so Login Items name
423    // LeanCTX, not sandbox-exec. The proxy applies the #356 deny-~/Documents
424    // seatbelt to itself at start-up (`reexec_under_seatbelt_if_needed`).
425    let port_arg = format!("--port={port}");
426    let program_args = crate::core::tcc_guard_sandbox::program_args_xml(
427        &crate::core::tcc_guard_sandbox::launchd_program_args(
428            binary,
429            &["proxy", "start", &port_arg],
430        ),
431        "        ",
432    );
433    let bundle_ids = crate::core::tcc_guard_sandbox::associated_bundle_ids_xml("    ");
434
435    // #449: pin the directory layout. A launchd-spawned proxy inherits only
436    // launchd's minimal environment (no HOME, no XDG vars), so it resolves a
437    // *different* config/data dir than the CLI that installed it — it never sees
438    // the user's config.toml edits (live-upstream reload reads nothing) and
439    // derives a mismatched session token. Bake the exact dirs this CLI resolves
440    // into the plist so the managed proxy always agrees with the CLI.
441    let env_vars = crate::core::tcc_guard_sandbox::pinned_layout_env_xml();
442
443    let plist = format!(
444        r#"<?xml version="1.0" encoding="UTF-8"?>
445<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
446<plist version="1.0">
447<dict>
448    <key>Label</key>
449    <string>{PLIST_LABEL}</string>
450    <key>ProgramArguments</key>
451    <array>
452{program_args}
453    </array>
454{bundle_ids}{env_vars}    <key>RunAtLoad</key>
455    <true/>
456    <key>KeepAlive</key>
457    <true/>
458    <key>StandardOutPath</key>
459    <string>{stdout}</string>
460    <key>StandardErrorPath</key>
461    <string>{stderr}</string>
462</dict>
463</plist>"#,
464        stdout = log_dir.join("proxy.stdout.log").display(),
465        stderr = log_dir.join("proxy.stderr.log").display(),
466    );
467
468    let _ = std::fs::write(&plist_path, &plist);
469
470    let ok = crate::core::launchd::bootstrap(PLIST_LABEL, &plist_path);
471
472    if !quiet {
473        if ok {
474            println!("  Installed LaunchAgent: {}", plist_path.display());
475            println!("  Proxy will start on login and restart if stopped");
476        } else {
477            println!("  Created LaunchAgent at {}", plist_path.display());
478            println!("  Load reported a problem; check: launchctl print {PLIST_LABEL}");
479        }
480    }
481    ok
482}
483
484#[cfg(target_os = "macos")]
485fn uninstall_launchagent(quiet: bool) {
486    let plist_path = launchagent_path();
487    if !plist_path.exists() {
488        if !quiet {
489            println!("  LaunchAgent not installed, nothing to remove");
490        }
491        return;
492    }
493
494    crate::core::launchd::bootout(PLIST_LABEL, &plist_path);
495
496    let _ = std::fs::remove_file(&plist_path);
497    if !quiet {
498        println!("  Removed LaunchAgent: {}", plist_path.display());
499    }
500}
501
502#[cfg(target_os = "linux")]
503fn systemd_path() -> PathBuf {
504    dirs::home_dir()
505        .unwrap_or_else(|| PathBuf::from("/tmp"))
506        .join(".config/systemd/user")
507        .join(format!("{SYSTEMD_SERVICE}.service"))
508}
509
510#[cfg(target_os = "linux")]
511fn install_systemd(binary: &str, port: u16, quiet: bool) -> bool {
512    let service_dir = dirs::home_dir()
513        .unwrap_or_else(|| PathBuf::from("/tmp"))
514        .join(".config/systemd/user");
515    let _ = std::fs::create_dir_all(&service_dir);
516
517    let service_path = service_dir.join(format!("{SYSTEMD_SERVICE}.service"));
518
519    let _ = std::process::Command::new("systemctl")
520        .args(["--user", "stop", SYSTEMD_SERVICE])
521        .output();
522    if !release_proxy_port(port, quiet) {
523        return false;
524    }
525
526    let unit = format!(
527        r"[Unit]
528Description=lean-ctx API Proxy
529After=network.target
530StartLimitIntervalSec=300
531StartLimitBurst=5
532
533[Service]
534Type=simple
535ExecStart={binary} proxy start --port={port}
536Restart=on-failure
537RestartSec=5
538StandardOutput=journal
539StandardError=journal
540Environment=RUST_LOG=info
541
542[Install]
543WantedBy=default.target
544"
545    );
546
547    let _ = std::fs::write(&service_path, &unit);
548
549    let _ = std::process::Command::new("systemctl")
550        .args(["--user", "daemon-reload"])
551        .output();
552
553    let result = std::process::Command::new("systemctl")
554        .args(["--user", "enable", "--now", SYSTEMD_SERVICE])
555        .output();
556
557    if !quiet {
558        match &result {
559            Ok(o) if o.status.success() => {
560                println!("  Installed systemd user service: {SYSTEMD_SERVICE}");
561                println!("  Proxy will start on login and restart if stopped");
562            }
563            Ok(o) => {
564                let err = String::from_utf8_lossy(&o.stderr);
565                println!("  Created service file but enable failed: {err}");
566            }
567            Err(e) => {
568                println!("  Created service file at {}", service_path.display());
569                println!("  Could not enable: {e}");
570            }
571        }
572    }
573    result.is_ok_and(|output| output.status.success())
574}
575
576#[cfg(target_os = "linux")]
577fn uninstall_systemd(quiet: bool) {
578    let service_path = systemd_path();
579    if !service_path.exists() {
580        if !quiet {
581            println!("  systemd service not installed, nothing to remove");
582        }
583        return;
584    }
585
586    let _ = std::process::Command::new("systemctl")
587        .args(["--user", "stop", SYSTEMD_SERVICE])
588        .output();
589    let _ = std::process::Command::new("systemctl")
590        .args(["--user", "disable", SYSTEMD_SERVICE])
591        .output();
592    let _ = std::fs::remove_file(&service_path);
593    let _ = std::process::Command::new("systemctl")
594        .args(["--user", "daemon-reload"])
595        .output();
596
597    if !quiet {
598        println!("  Removed systemd service: {SYSTEMD_SERVICE}");
599    }
600}
601
602pub fn find_binary() -> String {
603    crate::core::portable_binary::resolve_portable_binary()
604}
605
606#[cfg(test)]
607mod tests {
608    use super::{health_identifies_lean_ctx_proxy, proxy_pid_from_health};
609    #[cfg(any(target_os = "macos", target_os = "linux"))]
610    use super::{port_is_open, release_proxy_port};
611    #[cfg(any(target_os = "macos", target_os = "linux"))]
612    use std::io::{Read, Write};
613    #[cfg(any(target_os = "macos", target_os = "linux"))]
614    use std::net::TcpListener;
615
616    #[test]
617    fn health_pid_parser_accepts_only_well_formed_health() {
618        assert_eq!(
619            proxy_pid_from_health(r#"{"status":"ok","service":"lean-ctx-proxy","pid":4242}"#),
620            Some(4242)
621        );
622        // #2176 review #5: an answer that does not identify the lean-ctx
623        // proxy names no candidate.
624        assert_eq!(proxy_pid_from_health(r#"{"status":"ok","pid":4242}"#), None);
625        assert_eq!(
626            proxy_pid_from_health(r#"{"status":"ok","service":"other","pid":4242}"#),
627            None
628        );
629        assert_eq!(
630            proxy_pid_from_health(r#"{"status":"busy","service":"lean-ctx-proxy","pid":4242}"#),
631            None
632        );
633        assert_eq!(
634            proxy_pid_from_health(r#"{"status":"ok","service":"lean-ctx-proxy","pid":0}"#),
635            None
636        );
637        assert_eq!(proxy_pid_from_health(r#"{"status":"ok"}"#), None);
638        assert_eq!(proxy_pid_from_health("not json"), None);
639        assert!(health_identifies_lean_ctx_proxy(
640            r#"{"status":"ok","service":"lean-ctx-proxy","pid":4242}"#
641        ));
642        assert!(!health_identifies_lean_ctx_proxy(
643            r#"{"status":"ok","pid":4242}"#
644        ));
645    }
646
647    #[test]
648    #[cfg(any(target_os = "macos", target_os = "linux"))]
649    fn managed_handoff_fails_closed_for_unidentified_listener() {
650        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
651        let port = listener.local_addr().unwrap().port();
652        let server = std::thread::spawn(move || {
653            for _ in 0..2 {
654                let (mut stream, _) = listener.accept().unwrap();
655                stream
656                    .set_read_timeout(Some(std::time::Duration::from_secs(1)))
657                    .unwrap();
658                let mut request = [0_u8; 512];
659                if stream.read(&mut request).unwrap_or(0) > 0 {
660                    let body = r#"{"status":"ok"}"#;
661                    write!(
662                        stream,
663                        "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
664                        body.len()
665                    )
666                    .unwrap();
667                }
668            }
669        });
670
671        assert!(!release_proxy_port(port, true));
672        server.join().unwrap();
673    }
674
675    #[cfg(unix)]
676    struct ChildGuard(std::process::Child);
677
678    #[cfg(unix)]
679    impl Drop for ChildGuard {
680        fn drop(&mut self) {
681            let _ = self.0.kill();
682            let _ = self.0.wait();
683        }
684    }
685
686    /// #2176 review: a listener that claims to be the lean-ctx proxy in
687    /// `/health` but is not a lean-ctx `proxy start` process (here the test
688    /// binary) is never signalled; the hand-off fails closed.
689    #[test]
690    #[cfg(unix)]
691    fn managed_handoff_never_signals_an_unverified_health_pid() {
692        let reservation = TcpListener::bind("127.0.0.1:0").unwrap();
693        let port = reservation.local_addr().unwrap().port();
694        drop(reservation);
695
696        let child = std::process::Command::new(std::env::current_exe().unwrap())
697            .args([
698                "--ignored",
699                "--exact",
700                "proxy_autostart::tests::managed_handoff_test_child",
701                "--nocapture",
702            ])
703            .env("LEAN_CTX_HANDOFF_TEST_PORT", port.to_string())
704            .spawn()
705            .unwrap();
706        let mut child = ChildGuard(child);
707
708        let ready_deadline = std::time::Instant::now() + std::time::Duration::from_secs(3);
709        while !port_is_open(port) && std::time::Instant::now() < ready_deadline {
710            std::thread::sleep(std::time::Duration::from_millis(25));
711        }
712        assert!(port_is_open(port), "test proxy did not bind port {port}");
713        assert!(!release_proxy_port(port, true));
714        assert!(
715            child.0.try_wait().unwrap().is_none(),
716            "an unverified /health PID must never be signalled"
717        );
718        assert!(port_is_open(port));
719    }
720
721    #[test]
722    #[ignore = "helper process for managed_handoff_never_signals_an_unverified_health_pid"]
723    #[cfg(unix)]
724    fn managed_handoff_test_child() {
725        let port: u16 = std::env::var("LEAN_CTX_HANDOFF_TEST_PORT")
726            .unwrap()
727            .parse()
728            .unwrap();
729        let listener = TcpListener::bind(("127.0.0.1", port)).unwrap();
730        loop {
731            let (mut stream, _) = listener.accept().unwrap();
732            stream
733                .set_read_timeout(Some(std::time::Duration::from_secs(1)))
734                .unwrap();
735            let mut request = [0_u8; 512];
736            if stream.read(&mut request).unwrap_or(0) > 0 {
737                let body = format!(
738                    r#"{{"status":"ok","service":"lean-ctx-proxy","pid":{}}}"#,
739                    std::process::id()
740                );
741                write!(
742                    stream,
743                    "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
744                    body.len()
745                )
746                .unwrap();
747            }
748        }
749    }
750}