Skip to main content

subc_client_rs/
operator_app.rs

1//! Installed-daemon discovery from OS facts: Unix account and runtime locations,
2//! or the profile folder Windows records for the account, without environment input.
3
4use std::{error::Error, fmt, path::PathBuf};
5
6/// The installed daemon's path could not be resolved without environment input.
7#[derive(Debug, Clone, PartialEq, Eq)]
8pub struct OperatorAppPathError {
9    pub os: &'static str,
10    pub reason: String,
11}
12
13impl fmt::Display for OperatorAppPathError {
14    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
15        write!(
16            f,
17            "cannot resolve installed daemon path on {}: {}",
18            self.os, self.reason
19        )
20    }
21}
22
23impl Error for OperatorAppPathError {}
24
25fn path_error(reason: impl Into<String>) -> OperatorAppPathError {
26    OperatorAppPathError {
27        os: std::env::consts::OS,
28        reason: reason.into(),
29    }
30}
31
32/// Resolve the installed daemon's connection-file candidates using OS facts only.
33///
34/// This is its own discovery policy, separate from
35/// [`subc_transport::connection_file::discovery_candidates`]: it builds
36/// candidates from account information and OS APIs and reads no environment
37/// variable, so custom daemon locations set through the environment aren't
38/// searched.
39///
40/// - macOS: the home directory from the password database, joined with
41///   `.local/share/cortexkit/run/subc-connection.json`, then Darwin's per-user
42///   temporary directory's `subc-<uid>.connection.json`.
43/// - Linux: `/run/user/<uid>/subc-connection.json`, then the same
44///   password-database home path.
45/// - Windows: only `<profile>\AppData\Local\cortexkit\run\subc-connection.json`,
46///   where `<profile>` is the profile folder Windows records for the account
47///   (`subc_os::profile_dir`). The daemon attempts to publish that file when
48///   its connection file falls back to the temporary directory.
49///
50/// A failed OS lookup returns a typed error. No connection files are read.
51pub fn operator_app_candidates() -> Result<Vec<PathBuf>, OperatorAppPathError> {
52    platform_candidates()
53}
54
55/// Resolve the first existing installed-daemon connection-file candidate, or
56/// the first candidate if none exists, without reading environment variables.
57///
58/// Uses [`operator_app_candidates`] in order. This only checks existence, not
59/// ownership or file contents; [`crate::SubcConsumer::connect_operator_app`]
60/// checks ownership on every connection attempt before reading the file.
61pub fn operator_app_path() -> Result<PathBuf, OperatorAppPathError> {
62    let candidates = operator_app_candidates()?;
63    Ok(first_existing_candidate(&candidates).to_path_buf())
64}
65
66fn first_existing_candidate(candidates: &[PathBuf]) -> &std::path::Path {
67    candidates
68        .iter()
69        .find(|path| path.exists())
70        .unwrap_or(&candidates[0])
71}
72
73pub(crate) fn owned_candidate(candidates: &[PathBuf]) -> &std::path::Path {
74    #[cfg(unix)]
75    {
76        use std::os::unix::fs::MetadataExt;
77        let uid = subc_os::effective_uid();
78        owned_candidate_with(candidates, |_, meta| meta.uid() == uid)
79    }
80    #[cfg(not(unix))]
81    {
82        &candidates[0]
83    }
84}
85
86#[cfg(unix)]
87fn owned_candidate_with(
88    candidates: &[PathBuf],
89    is_owner: impl Fn(&std::path::Path, &std::fs::Metadata) -> bool,
90) -> &std::path::Path {
91    use std::os::unix::fs::PermissionsExt;
92    // This preselection only skips missing or untrusted candidates. Transport
93    // rechecks the opened inode before reading, so a path replacement cannot
94    // bypass its owner check. Once selected, parse or dial errors must not fall
95    // through to a different daemon.
96    candidates
97        .iter()
98        .find(|path| {
99            std::fs::metadata(path)
100                .is_ok_and(|meta| is_owner(path, &meta) && meta.permissions().mode() & 0o077 == 0)
101        })
102        .unwrap_or(&candidates[0])
103}
104
105#[cfg(target_os = "macos")]
106fn platform_candidates() -> Result<Vec<PathBuf>, OperatorAppPathError> {
107    let home = subc_os::real_user_home_dir().map_err(|error| path_error(error.to_string()))?;
108    let temp = subc_os::darwin_user_temp_dir().map_err(|error| path_error(error.to_string()))?;
109    Ok(macos_candidates(
110        &home,
111        &temp,
112        &subc_transport::connection_file::user_connection_token(),
113    ))
114}
115
116#[cfg(target_os = "linux")]
117fn platform_candidates() -> Result<Vec<PathBuf>, OperatorAppPathError> {
118    let home = subc_os::real_user_home_dir().map_err(|error| path_error(error.to_string()))?;
119    Ok(linux_candidates(
120        &home,
121        &subc_transport::connection_file::user_connection_token(),
122    ))
123}
124
125#[cfg(any(target_os = "macos", test))]
126pub(crate) fn macos_candidates(
127    home: &std::path::Path,
128    temp: &std::path::Path,
129    uid: &str,
130) -> Vec<PathBuf> {
131    vec![
132        home.join(".local/share/cortexkit/run/subc-connection.json"),
133        temp.join(format!("subc-{uid}.connection.json")),
134    ]
135}
136
137#[cfg(any(target_os = "linux", test))]
138fn linux_candidates(home: &std::path::Path, uid: &str) -> Vec<PathBuf> {
139    vec![
140        PathBuf::from(format!("/run/user/{uid}/subc-connection.json")),
141        home.join(".local/share/cortexkit/run/subc-connection.json"),
142    ]
143}
144
145#[cfg(target_os = "windows")]
146fn platform_candidates() -> Result<Vec<PathBuf>, OperatorAppPathError> {
147    // Resolve the account's recorded profile directly, never through a shell
148    // folder value that expands the environment, then append the fixed suffix.
149    // Never guess the daemon's environment-derived temporary filename.
150    let base = subc_os::profile_dir().map_err(|error| path_error(error.to_string()))?;
151    Ok(windows_candidates(&base))
152}
153
154#[cfg(any(windows, test))]
155fn windows_candidates(base: &std::path::Path) -> Vec<PathBuf> {
156    vec![base
157        .join("AppData")
158        .join("Local")
159        .join("cortexkit")
160        .join("run")
161        .join("subc-connection.json")]
162}
163
164#[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))]
165fn platform_candidates() -> Result<Vec<PathBuf>, OperatorAppPathError> {
166    Err(path_error(
167        "no environment-free installed daemon location is defined for this OS",
168    ))
169}
170
171#[cfg(test)]
172mod tests {
173    use super::*;
174    use std::process::Command;
175
176    #[test]
177    fn macos_candidate_order_from_os_facts() {
178        assert_eq!(
179            macos_candidates(
180                std::path::Path::new("/Users/operator"),
181                std::path::Path::new("/darwin/temp"),
182                "501"
183            ),
184            vec![
185                PathBuf::from("/Users/operator/.local/share/cortexkit/run/subc-connection.json"),
186                PathBuf::from("/darwin/temp/subc-501.connection.json"),
187            ]
188        );
189    }
190
191    #[test]
192    fn linux_candidate_order_from_os_facts() {
193        assert_eq!(
194            linux_candidates(std::path::Path::new("/home/operator"), "1001"),
195            vec![
196                PathBuf::from("/run/user/1001/subc-connection.json"),
197                PathBuf::from("/home/operator/.local/share/cortexkit/run/subc-connection.json"),
198            ]
199        );
200    }
201
202    #[test]
203    fn windows_candidates_from_os_facts() {
204        let base = std::path::Path::new("C:/Users/operator");
205        assert_eq!(
206            windows_candidates(base),
207            vec![PathBuf::from(
208                "C:/Users/operator/AppData/Local/cortexkit/run/subc-connection.json"
209            )]
210        );
211    }
212
213    #[test]
214    fn path_uses_first_existing_candidate_or_first_when_none_exist() {
215        let dir = cortexkit_test_support::ScratchDir::new("operator-path");
216        let candidates = macos_candidates(&dir.join("home"), &dir.join("temp"), "501");
217        assert_eq!(first_existing_candidate(&candidates), candidates[0]);
218        std::fs::create_dir_all(candidates[1].parent().unwrap()).unwrap();
219        std::fs::write(&candidates[1], b"connection file").unwrap();
220        assert_eq!(first_existing_candidate(&candidates), candidates[1]);
221        std::fs::create_dir_all(candidates[0].parent().unwrap()).unwrap();
222        std::fs::write(&candidates[0], b"connection file").unwrap();
223        assert_eq!(first_existing_candidate(&candidates), candidates[0]);
224    }
225
226    #[cfg(unix)]
227    #[test]
228    fn foreign_owned_home_rung_is_skipped() {
229        use cortexkit_test_support::ScratchDir;
230        use std::os::unix::fs::{MetadataExt, PermissionsExt};
231        let dir = ScratchDir::new("operator-owner");
232        let candidates = macos_candidates(&dir.join("home"), &dir.join("temp"), "501");
233        for path in &candidates {
234            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
235            std::fs::write(path, b"connection file").unwrap();
236            std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)).unwrap();
237        }
238        let expected_uid = std::fs::metadata(&candidates[1]).unwrap().uid();
239        let selected = owned_candidate_with(&candidates, |path, meta| {
240            let owner = if path == candidates[0] {
241                expected_uid.wrapping_add(1)
242            } else {
243                meta.uid()
244            };
245            owner == expected_uid
246        });
247        assert_eq!(selected, candidates[1]);
248        assert_eq!(owned_candidate(&candidates), candidates[0]);
249    }
250
251    #[test]
252    fn operator_app_path_ignores_environment() {
253        const PROBE: &str = "SUBC_OPERATOR_PATH_PROBE";
254        const MARKER: &str = "operator-app-path=";
255        const VARIABLES: &[&str] = &[
256            "SUBC_CONNECTION_FILE",
257            "XDG_RUNTIME_DIR",
258            "HOME",
259            "TMPDIR",
260            "LOCALAPPDATA",
261            "USERPROFILE",
262            "HOMEDRIVE",
263            "HOMEPATH",
264            "SystemDrive",
265            "USER",
266            "USERNAME",
267            "TMP",
268            "TEMP",
269        ];
270        if std::env::var_os(PROBE).is_some() {
271            let result = operator_app_candidates();
272            #[cfg(any(target_os = "macos", target_os = "linux", windows))]
273            assert!(
274                result.is_ok(),
275                "OS path resolution must succeed: {result:?}"
276            );
277            if let Ok(paths) = &result {
278                assert!(paths.iter().all(|path| path.is_absolute()), "{paths:?}");
279                let path = operator_app_path().unwrap();
280                assert_eq!(
281                    &path,
282                    paths.iter().find(|path| path.exists()).unwrap_or(&paths[0])
283                );
284            }
285            // libtest may have already printed the test name on the current line.
286            println!("\n{MARKER}{result:?}");
287            return;
288        }
289
290        let run = |hostile: bool| {
291            let mut child = Command::new(std::env::current_exe().unwrap());
292            child
293                .args([
294                    "--exact",
295                    "operator_app::tests::operator_app_path_ignores_environment",
296                    "--nocapture",
297                ])
298                .env(PROBE, "1");
299            for variable in VARIABLES {
300                if hostile {
301                    child.env(variable, "/untrusted/operator-app-must-ignore");
302                } else {
303                    child.env_remove(variable);
304                }
305            }
306            let output = child.output().unwrap();
307            assert!(output.status.success(), "{output:?}");
308            let stdout = String::from_utf8(output.stdout).unwrap();
309            assert!(stdout.contains("1 passed"), "path probe must run: {stdout}");
310            stdout
311                .lines()
312                .find_map(|line| line.strip_prefix(MARKER))
313                .expect("path probe must run in child")
314                .to_owned()
315        };
316        assert_eq!(run(false), run(true));
317    }
318}