Skip to main content

subc_transport/
connection_file.rs

1use std::{
2    env,
3    error::Error,
4    ffi::{OsStr, OsString},
5    fmt,
6    fs::{self, File},
7    io::{self, Read, Write},
8    path::{Path, PathBuf},
9    process,
10    time::{Duration, SystemTime},
11};
12
13#[cfg(not(windows))]
14use std::fs::OpenOptions;
15
16use serde::{Deserialize, Serialize};
17use subc_protocol::PROTOCOL_VERSION;
18
19pub const SCHEMA_VERSION: u32 = 1;
20pub const MIN_KEY_LEN: usize = 32;
21pub const KEY_LEN: usize = 32;
22pub const DAEMON_ID_LEN: usize = 16;
23
24/// The daemon's connection-file name. Public so the writer (bootstrap) and
25/// every reader spell it once; three private copies of this literal used to
26/// exist and nothing asserted they agreed.
27pub const CONNECTION_FILE_NAME: &str = "subc-connection.json";
28const PROD_CONNECTION_RELATIVE_PATH: &[&str] =
29    &[".local", "share", "cortexkit", "run", CONNECTION_FILE_NAME];
30
31#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
32pub struct Endpoint {
33    pub host: String,
34    pub port: u16,
35}
36
37#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
38pub struct ConnectionInfo {
39    pub schema: u32,
40    #[serde(default, skip_serializing_if = "Option::is_none")]
41    pub wire_version: Option<u8>,
42    pub endpoints: Vec<Endpoint>,
43    pub key: Vec<u8>,
44    pub daemon_id: [u8; DAEMON_ID_LEN],
45    pub pid: u32,
46    pub daemon_ver: String,
47}
48
49// Hand-written so the transport key is never printed. A derived Debug would dump
50// the raw key bytes into any log or panic message that formats a ConnectionInfo.
51impl fmt::Debug for ConnectionInfo {
52    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
53        f.debug_struct("ConnectionInfo")
54            .field("schema", &self.schema)
55            .field("wire_version", &self.wire_version)
56            .field("endpoints", &self.endpoints)
57            .field("key", &format_args!("<{} bytes redacted>", self.key.len()))
58            .field("daemon_id", &self.daemon_id)
59            .field("pid", &self.pid)
60            .field("daemon_ver", &self.daemon_ver)
61            .finish()
62    }
63}
64
65/// The daemon's same-user local listener, published in the connection file under
66/// the optional `local_endpoint` key: `{"kind":"unix","path":"…"}` for a
67/// Unix-domain socket (macOS, Linux) or `{"kind":"pipe","name":"…"}` for a
68/// Windows named pipe.
69///
70/// It lives beside `ConnectionInfo` rather than inside it because
71/// `ConnectionInfo` has only public fields and other crates build it by struct
72/// literal, so adding a field there would break them. `ConnectionInfo` ignores
73/// unknown keys, so `read` still accepts a file that carries this one; only
74/// `read_with_local_endpoint` and `write_atomic_with_local_endpoint` see it.
75#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
76#[serde(tag = "kind", rename_all = "lowercase")]
77#[non_exhaustive]
78pub enum LocalEndpoint {
79    /// A Unix-domain socket at this filesystem path.
80    Unix { path: PathBuf },
81    /// A Windows named pipe with this full pipe name (`\\.\pipe\…`).
82    Pipe { name: String },
83}
84
85impl LocalEndpoint {
86    /// Refuses an empty path or pipe name: neither names a listener a client
87    /// could connect to.
88    pub fn validate(&self) -> Result<(), ConnectionFileError> {
89        let empty = match self {
90            Self::Unix { path } => path.as_os_str().is_empty(),
91            Self::Pipe { name } => name.is_empty(),
92        };
93        if empty {
94            return Err(ConnectionFileError::Invalid {
95                reason: "connection file local_endpoint must name a path or pipe".to_owned(),
96            });
97        }
98        Ok(())
99    }
100}
101
102/// A connection file's `ConnectionInfo` together with its optional
103/// `local_endpoint`, both read from the same owner-checked file.
104#[derive(Debug, Clone, PartialEq, Eq)]
105pub struct ConnectionInfoWithLocalEndpoint {
106    pub info: ConnectionInfo,
107    /// `None` when the file has no `local_endpoint` key, as in every file
108    /// written before the key existed or by a daemon with no local listener.
109    pub local_endpoint: Option<LocalEndpoint>,
110}
111
112/// The `local_endpoint` key on its own, parsed from the same bytes as
113/// `ConnectionInfo` so the `ConnectionInfo` parse is exactly the one `read`
114/// performs.
115#[derive(Deserialize)]
116struct LocalEndpointField {
117    #[serde(default)]
118    local_endpoint: Option<LocalEndpoint>,
119}
120
121/// The on-disk shape written by `write_atomic_with_local_endpoint`: every
122/// `ConnectionInfo` key in its usual order, then `local_endpoint` when present.
123/// With no endpoint the bytes are identical to `write_atomic`'s.
124#[derive(Serialize)]
125struct ConnectionFileOut<'a> {
126    #[serde(flatten)]
127    info: &'a ConnectionInfo,
128    #[serde(skip_serializing_if = "Option::is_none")]
129    local_endpoint: Option<&'a LocalEndpoint>,
130}
131
132/// A connection file selected by reader-side discovery.
133#[derive(Debug, Clone, PartialEq, Eq)]
134pub struct Discovered {
135    pub path: PathBuf,
136    pub info: ConnectionInfo,
137}
138
139/// One connection-file candidate that could not be read or parsed.
140#[derive(Debug, Clone, PartialEq, Eq)]
141pub struct TriedCandidate {
142    pub path: PathBuf,
143    pub reason: String,
144}
145
146/// Every connection-file candidate reader-side discovery tried.
147#[derive(Debug, Clone, PartialEq, Eq)]
148pub struct DiscoveryError {
149    pub tried: Vec<TriedCandidate>,
150}
151
152impl fmt::Display for DiscoveryError {
153    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
154        let rendered = self
155            .tried
156            .iter()
157            .map(|attempt| format!("{} ({})", attempt.path.display(), attempt.reason))
158            .collect::<Vec<_>>()
159            .join(", ");
160        write!(f, "no usable subc connection file found; tried: {rendered}")
161    }
162}
163
164impl Error for DiscoveryError {}
165
166impl ConnectionInfo {
167    pub fn validate(&self) -> Result<(), ConnectionFileError> {
168        if self.schema != SCHEMA_VERSION {
169            return Err(ConnectionFileError::UnsupportedSchema {
170                schema: self.schema,
171                supported: SCHEMA_VERSION,
172            });
173        }
174        if self.endpoints.is_empty() {
175            return Err(ConnectionFileError::Invalid {
176                reason: "connection file must include at least one endpoint".to_owned(),
177            });
178        }
179        if self.key.len() < MIN_KEY_LEN {
180            return Err(ConnectionFileError::KeyTooShort {
181                len: self.key.len(),
182                min: MIN_KEY_LEN,
183            });
184        }
185        Ok(())
186    }
187
188    /// Validates a declared envelope version without rejecting older files that
189    /// omit the additive field.
190    pub fn validate_wire_version(&self, supported: u8) -> Result<(), ConnectionFileError> {
191        if let Some(file) = self.wire_version {
192            if file != supported {
193                return Err(ConnectionFileError::WireVersionMismatch { file, supported });
194            }
195        }
196        Ok(())
197    }
198}
199
200#[derive(Debug)]
201pub enum ConnectionFileError {
202    MissingParent {
203        path: PathBuf,
204    },
205    MissingFileName {
206        path: PathBuf,
207    },
208    Io {
209        op: &'static str,
210        path: PathBuf,
211        source: io::Error,
212    },
213    JsonRead {
214        path: PathBuf,
215        source: serde_json::Error,
216    },
217    JsonWrite {
218        path: PathBuf,
219        source: serde_json::Error,
220    },
221    Random(getrandom::Error),
222    UnsupportedSchema {
223        schema: u32,
224        supported: u32,
225    },
226    WireVersionMismatch {
227        file: u8,
228        supported: u8,
229    },
230    Invalid {
231        reason: String,
232    },
233    KeyTooShort {
234        len: usize,
235        min: usize,
236    },
237    InsecurePermissions {
238        path: PathBuf,
239        mode: u32,
240    },
241    InsecureParentDirectory {
242        component: PathBuf,
243        mode: u32,
244    },
245}
246
247pub fn write_atomic(
248    path: impl AsRef<Path>,
249    info: &ConnectionInfo,
250) -> Result<(), ConnectionFileError> {
251    write_atomic_with_local_endpoint(path, info, None)
252}
253
254/// Like `write_atomic`, and also publishes `local_endpoint` when one is given.
255/// With `None` the key is omitted and the file is byte-identical to the one
256/// `write_atomic` writes.
257pub fn write_atomic_with_local_endpoint(
258    path: impl AsRef<Path>,
259    info: &ConnectionInfo,
260    local_endpoint: Option<&LocalEndpoint>,
261) -> Result<(), ConnectionFileError> {
262    let path = path.as_ref();
263    info.validate()?;
264    if let Some(endpoint) = local_endpoint {
265        endpoint.validate()?;
266    }
267    // Serialise before touching the filesystem so a value that cannot be
268    // written (a non-UTF-8 socket path) leaves no temp behind.
269    let json = serde_json::to_vec_pretty(&ConnectionFileOut {
270        info,
271        local_endpoint,
272    })
273    .map_err(|source| ConnectionFileError::JsonWrite {
274        path: path.to_path_buf(),
275        source,
276    })?;
277
278    let parent = path
279        .parent()
280        .filter(|parent| !parent.as_os_str().is_empty())
281        .ok_or_else(|| ConnectionFileError::MissingParent {
282            path: path.to_path_buf(),
283        })?;
284    let file_name = path
285        .file_name()
286        .ok_or_else(|| ConnectionFileError::MissingFileName {
287            path: path.to_path_buf(),
288        })?;
289    ensure_parent_directory(parent)?;
290    refuse_writable_ancestor(parent)?;
291    // Sweep temps stranded by an earlier writer before creating our own. The
292    // error path below removes this call's temp, but nothing removes one left by
293    // a process that died BETWEEN create and rename -- and a connection file
294    // carries the daemon's auth key, so a stranded temp is a stale credential
295    // sitting in the runtime directory indefinitely. Owner-only mode means no
296    // other user can read it and the key dies with the daemon that minted it;
297    // the objection is to key material with no owner and no expiry, not to an
298    // active leak.
299    //
300    // Best-effort and non-fatal: publishing must not fail because cleanup could
301    // not remove somebody else's file.
302    sweep_stale_temps(parent, file_name);
303
304    let temp_path = temp_path(parent, file_name)?;
305    let result = write_atomic_inner(path, &temp_path, &json);
306    if result.is_err() {
307        let _ = fs::remove_file(&temp_path);
308    }
309    result
310}
311
312/// Create the connection file's parent with owner-only permissions when it is
313/// absent.
314///
315/// The daemon OWNS this directory, so it can make the misconfiguration
316/// unproducible rather than only reporting it — which is strictly stronger than
317/// the check below and is available to us precisely because we choose the path.
318/// A caller that names its own destination has only the check.
319///
320/// An existing directory is left alone: changing modes under an operator is a
321/// bigger act than refusing, and `refuse_writable_ancestor` reports it.
322fn ensure_parent_directory(parent: &Path) -> Result<(), ConnectionFileError> {
323    if parent.exists() {
324        return Ok(());
325    }
326    #[cfg(unix)]
327    let created = {
328        use std::os::unix::fs::DirBuilderExt;
329        fs::DirBuilder::new()
330            .recursive(true)
331            .mode(0o700)
332            .create(parent)
333    };
334    #[cfg(windows)]
335    let created = subc_os::windows_acl::create_private_dir(parent);
336    #[cfg(not(any(unix, windows)))]
337    let created = fs::create_dir_all(parent);
338
339    created.map_err(|source| ConnectionFileError::Io {
340        op: "create connection-file parent",
341        path: parent.to_path_buf(),
342        source,
343    })
344}
345
346/// Refuse to publish key material beneath a directory another user can write.
347///
348/// This catches misconfiguration; it is not a security boundary. A process
349/// running as the same user can read the finished 0600 file anyway, so the
350/// check does nothing against one. What it catches is another user: whoever can
351/// write a directory can unlink and create entries in it, whatever the mode or
352/// owner of the file inside, so another user with write access to any ancestor
353/// could delete the 0600 file and put their own in its place.
354///
355/// The check covers every ancestor up to `/`. Stopping at `$HOME` or an XDG
356/// base would take the bound from the environment, which an attacker can
357/// influence and which may be unset. It would also be wrong: an attacker who can
358/// unlink in any ancestor can rename an intermediate directory aside and put
359/// their own tree in its place, so a 0700 leaf under a 0777 grandparent protects
360/// nothing.
361///
362/// The path is canonicalised first, resolving symlinks. Walking the unresolved
363/// path would check the modes of a path other than the one written through: a
364/// symlink component pointing somewhere permissive would pass every `stat`.
365///
366/// Each ancestor must be owned by the effective user or by root, and is refused
367/// otherwise: even a 0755 directory can be renamed or have its permissions
368/// changed by its owner. Root is trusted because the transport does not defend
369/// against root processes.
370///
371/// A group- or world-writable ancestor is refused unless it is sticky. The
372/// sticky bit lets only an entry's owner remove or rename it, and `/tmp` and
373/// `/Users/Shared` are 1777 by design; without this exemption the check would
374/// fire on correctly configured systems, and a check that refuses healthy
375/// configuration gets disabled, after which it protects nothing. A sticky
376/// directory must still pass the ownership check above.
377#[cfg(unix)]
378fn refuse_writable_ancestor(parent: &Path) -> Result<(), ConnectionFileError> {
379    refuse_writable_ancestor_for_uid(parent, rustix::process::geteuid().as_raw())
380}
381
382#[cfg(unix)]
383fn refuse_writable_ancestor_for_uid(parent: &Path, uid: u32) -> Result<(), ConnectionFileError> {
384    use std::os::unix::fs::{MetadataExt, PermissionsExt};
385
386    const GROUP_OR_WORLD_WRITABLE: u32 = 0o022;
387    const STICKY: u32 = 0o1000;
388
389    // A parent that cannot be canonicalised is reported by the write itself with
390    // its own io::Error; refusing here would replace a precise errno with a
391    // permissions verdict about a path we could not resolve.
392    let Ok(resolved) = fs::canonicalize(parent) else {
393        return Ok(());
394    };
395
396    let mut component = resolved.as_path();
397    loop {
398        // A component whose metadata cannot be read is SKIPPED, not refused, and
399        // the silence is deliberate. Canonicalising above already required
400        // traverse permission on every component, so a failure here is close to
401        // unreachable and is a transient io error rather than evidence about
402        // permissions; refusing on it would convert that error into a confident
403        // verdict about a mode we never observed, which is the same trade the
404        // canonicalise arm declines. Argued at the site because an UNARGUED
405        // fail-open is the one a later reader tightens into a refusal.
406        if let Ok(metadata) = fs::metadata(component) {
407            if metadata.uid() != uid && metadata.uid() != 0 {
408                return Err(ConnectionFileError::Invalid {
409                    reason: format!(
410                        "connection-file ancestor {} is owned by uid {}, expected effective uid {uid} or root",
411                        component.display(), metadata.uid()
412                    ),
413                });
414            }
415            let mode = metadata.permissions().mode();
416            if mode & GROUP_OR_WORLD_WRITABLE != 0 && mode & STICKY == 0 {
417                return Err(ConnectionFileError::InsecureParentDirectory {
418                    component: component.to_path_buf(),
419                    mode: mode & 0o7777,
420                });
421            }
422        }
423        match component.parent() {
424            Some(next) => component = next,
425            None => return Ok(()),
426        }
427    }
428}
429
430#[cfg(windows)]
431fn refuse_writable_ancestor(parent: &Path) -> Result<(), ConnectionFileError> {
432    // Refuse a redirected publication directory with a foreign owner or broad
433    // DACL; the writer must not repair an operator-supplied existing directory.
434    subc_os::windows_acl::verify_private_dir(parent).map_err(|error| ConnectionFileError::Invalid {
435        reason: format!(
436            "connection-file directory {} is not owner-only: {error}",
437            parent.display()
438        ),
439    })
440}
441
442#[cfg(not(any(unix, windows)))]
443fn refuse_writable_ancestor(_parent: &Path) -> Result<(), ConnectionFileError> {
444    Ok(())
445}
446
447/// Remove `.<file_name>.<pid>.<hex>.tmp` siblings older than ten minutes.
448///
449/// AGE IS THE SOLE PREDICATE. Testing whether the embedded pid is alive reads
450/// false-positive on exactly the oldest files, because pid numbers are recycled:
451/// an unrelated long-lived process inherits the number and the stalest temp
452/// looks owned. That failure direction resembles caution, which is why nobody
453/// investigates the survivors. Ten minutes is far longer than the window this
454/// guards, which spans two syscalls.
455fn sweep_stale_temps(parent: &Path, file_name: &std::ffi::OsStr) {
456    const STALE_AFTER: Duration = Duration::from_secs(600);
457
458    let prefix = format!(".{}.", file_name.to_string_lossy());
459    let Ok(entries) = fs::read_dir(parent) else {
460        return;
461    };
462    for entry in entries.flatten() {
463        let name = entry.file_name();
464        let name = name.to_string_lossy();
465        if !name.starts_with(&prefix) || !name.ends_with(".tmp") {
466            continue;
467        }
468        let stale = entry
469            .metadata()
470            .and_then(|meta| meta.modified())
471            .map(|modified| {
472                SystemTime::now()
473                    .duration_since(modified)
474                    .is_ok_and(|age| age >= STALE_AFTER)
475            })
476            .unwrap_or(false);
477        if stale {
478            let _ = fs::remove_file(entry.path());
479        }
480    }
481}
482
483pub fn read(path: impl AsRef<Path>) -> Result<ConnectionInfo, ConnectionFileError> {
484    let path = path.as_ref();
485    let bytes = read_owner_checked(path)?;
486    parse_info(path, &bytes)
487}
488
489/// Reads `ConnectionInfo` and the optional `local_endpoint` from one read of
490/// one owner-checked file, so the endpoint and the key always come from the
491/// same file the same check accepted.
492///
493/// A missing `local_endpoint` is `None`. A key that is present but malformed
494/// (unknown `kind`, missing or empty `path`/`name`) is an error rather than
495/// `None`: a caller that asked for the local endpoint must not mistake a
496/// damaged one for an absent one.
497pub fn read_with_local_endpoint(
498    path: impl AsRef<Path>,
499) -> Result<ConnectionInfoWithLocalEndpoint, ConnectionFileError> {
500    let path = path.as_ref();
501    let bytes = read_owner_checked(path)?;
502    let info = parse_info(path, &bytes)?;
503    let LocalEndpointField { local_endpoint } =
504        serde_json::from_slice(&bytes).map_err(|source| ConnectionFileError::JsonRead {
505            path: path.to_path_buf(),
506            source,
507        })?;
508    if let Some(endpoint) = &local_endpoint {
509        endpoint.validate()?;
510    }
511    Ok(ConnectionInfoWithLocalEndpoint {
512        info,
513        local_endpoint,
514    })
515}
516
517/// `read_with_local_endpoint` with the same wire-version check as
518/// `read_for_client`.
519pub fn read_for_client_with_local_endpoint(
520    path: impl AsRef<Path>,
521) -> Result<ConnectionInfoWithLocalEndpoint, ConnectionFileError> {
522    let read = read_with_local_endpoint(path)?;
523    read.info.validate_wire_version(PROTOCOL_VERSION)?;
524    Ok(read)
525}
526
527fn read_owner_checked(path: &Path) -> Result<Vec<u8>, ConnectionFileError> {
528    let mut file = File::open(path).map_err(|source| ConnectionFileError::Io {
529        op: "open",
530        path: path.to_path_buf(),
531        source,
532    })?;
533    // Verify the opened inode, not a separate path lookup: replacing the path
534    // between stat and read must not let an unverified key through.
535    verify_owner_only(path, &file)?;
536    let mut bytes = Vec::new();
537    file.read_to_end(&mut bytes)
538        .map_err(|source| ConnectionFileError::Io {
539            op: "read",
540            path: path.to_path_buf(),
541            source,
542        })?;
543    Ok(bytes)
544}
545
546fn parse_info(path: &Path, bytes: &[u8]) -> Result<ConnectionInfo, ConnectionFileError> {
547    let info: ConnectionInfo =
548        serde_json::from_slice(bytes).map_err(|source| ConnectionFileError::JsonRead {
549            path: path.to_path_buf(),
550            source,
551        })?;
552    info.validate()?;
553    Ok(info)
554}
555
556/// Reads connection information for a client and rejects a declared envelope
557/// version this binary cannot decode before a TCP connection is attempted.
558pub fn read_for_client(path: impl AsRef<Path>) -> Result<ConnectionInfo, ConnectionFileError> {
559    let info = read(path)?;
560    info.validate_wire_version(PROTOCOL_VERSION)?;
561    Ok(info)
562}
563
564/// The paths a reader consults, most specific first. `explicit` is the
565/// caller's own override (a `--subc` flag); `env_named` is the value of
566/// `SUBC_CONNECTION_FILE` read by the caller. Either, when present, is the
567/// ONLY candidate.
568pub fn discovery_candidates(explicit: Option<&Path>, env_named: Option<&OsStr>) -> Vec<PathBuf> {
569    let runtime_dir = non_empty_os_var("XDG_RUNTIME_DIR");
570    let home = non_empty_os_var("HOME");
571    discovery_candidates_with_environment(
572        explicit,
573        env_named,
574        runtime_dir.as_deref(),
575        home.as_deref(),
576        &env::temp_dir(),
577    )
578}
579
580/// Read the reader-side environment and return the first usable connection file.
581/// Unlike writer-side `subc_daemon::bootstrap::connection_file_path()`, this searches
582/// every location where an already-running daemon may have written its file.
583pub fn discover(explicit: Option<&Path>) -> Result<Discovered, DiscoveryError> {
584    let env_named = non_empty_os_var("SUBC_CONNECTION_FILE");
585    discover_candidates(discovery_candidates(explicit, env_named.as_deref()))
586}
587
588fn discovery_candidates_with_environment(
589    explicit: Option<&Path>,
590    env_named: Option<&OsStr>,
591    runtime_dir: Option<&OsStr>,
592    home: Option<&OsStr>,
593    temp_dir: &Path,
594) -> Vec<PathBuf> {
595    if let Some(path) = explicit {
596        return vec![path.to_path_buf()];
597    }
598
599    let env_named = env_named.filter(|value| !value.is_empty());
600    let runtime_dir = runtime_dir.filter(|value| !value.is_empty());
601
602    // SUBC_CONNECTION_FILE names the daemon the caller means, so it is EXCLUSIVE
603    // rather than first-in-a-list. It used to be pushed ahead of the discovery
604    // candidates, which reads as honouring it and is not: a path that is set and
605    // wrong falls through to discovery and answers from whichever daemon is found
606    // -- in practice production. The reply is then true and about the wrong
607    // machine, and every later verdict inherits that while the operator believes
608    // they are reading a rig.
609    //
610    // A fallback is only a hazard where the primary is optional, so removing the
611    // fallback for a deliberately supplied value removes the class. Returning a
612    // single candidate keeps the existing error path: the file is stat-ed, and an
613    // unreadable one is reported as a failure naming that path.
614    if let Some(only) = env_named {
615        return vec![PathBuf::from(only)];
616    }
617
618    let mut candidates = Vec::new();
619    if let Some(runtime_dir) = runtime_dir {
620        push_unique(
621            &mut candidates,
622            PathBuf::from(runtime_dir).join(CONNECTION_FILE_NAME),
623        );
624    }
625    if let Some(home) = home {
626        let mut path = PathBuf::from(home);
627        for part in PROD_CONNECTION_RELATIVE_PATH {
628            path.push(part);
629        }
630        push_unique(&mut candidates, path);
631    }
632    push_unique(
633        &mut candidates,
634        temp_dir.join(format!("subc-{}.connection.json", user_connection_token())),
635    );
636    candidates
637}
638
639fn discover_candidates(candidates: Vec<PathBuf>) -> Result<Discovered, DiscoveryError> {
640    let mut tried = Vec::new();
641    for path in candidates {
642        match read_for_client(&path) {
643            Ok(info) => return Ok(Discovered { path, info }),
644            Err(source) => tried.push(TriedCandidate {
645                path,
646                reason: discovery_reason(&source),
647            }),
648        }
649    }
650    Err(DiscoveryError { tried })
651}
652
653fn push_unique(paths: &mut Vec<PathBuf>, path: PathBuf) {
654    if !paths.iter().any(|existing| existing == &path) {
655        paths.push(path);
656    }
657}
658
659fn non_empty_os_var(key: &str) -> Option<OsString> {
660    let value = env::var_os(key)?;
661    if value.is_empty() {
662        None
663    } else {
664        Some(value)
665    }
666}
667
668fn discovery_reason(source: &ConnectionFileError) -> String {
669    match source {
670        ConnectionFileError::Io { source, .. } if source.kind() == io::ErrorKind::NotFound => {
671            "not found".to_string()
672        }
673        other => other.to_string(),
674    }
675}
676
677/// The per-user component of the temp-fallback connection-file name.
678///
679/// The daemon writer and every reader use this one implementation so a naming
680/// drift cannot make a running daemon appear absent.
681pub fn user_connection_token() -> String {
682    // On Unix the token is the real uid, read from the kernel. Identity must not
683    // depend on a fallible filesystem probe because a transient failure would
684    // make the same user derive a different connection-file name.
685    #[cfg(unix)]
686    {
687        rustix::process::getuid().as_raw().to_string()
688    }
689
690    #[cfg(not(unix))]
691    {
692        for key in ["USER", "USERNAME", "HOME", "USERPROFILE"] {
693            if let Some(value) = non_empty_os_var(key) {
694                return sanitize_token(&value.to_string_lossy());
695            }
696        }
697
698        "unknown".to_string()
699    }
700}
701
702#[cfg(not(unix))]
703fn sanitize_token(raw: &str) -> String {
704    let mut token = String::new();
705    for ch in raw.chars() {
706        if ch.is_ascii_alphanumeric() || matches!(ch, '-' | '_') {
707            token.push(ch);
708        } else {
709            token.push('_');
710        }
711    }
712    if token.is_empty() {
713        "unknown".to_string()
714    } else {
715        token
716    }
717}
718
719#[cfg(unix)]
720fn verify_owner_only(path: &Path, file: &File) -> Result<(), ConnectionFileError> {
721    let meta = file.metadata().map_err(|source| ConnectionFileError::Io {
722        op: "fstat",
723        path: path.to_path_buf(),
724        source,
725    })?;
726    verify_owner_only_for_uid(path, &meta, rustix::process::geteuid().as_raw())
727}
728
729#[cfg(unix)]
730fn verify_owner_only_for_uid(
731    path: &Path,
732    meta: &fs::Metadata,
733    uid: u32,
734) -> Result<(), ConnectionFileError> {
735    use std::os::unix::fs::{MetadataExt, PermissionsExt};
736    // A foreign owner can substitute their own endpoint and key even at 0600.
737    // This also refuses a foreign-owned file readable through an ACL or by root.
738    if meta.uid() != uid {
739        return Err(ConnectionFileError::Invalid {
740            reason: format!(
741                "connection file {} is owned by uid {}, expected effective uid {uid}",
742                path.display(),
743                meta.uid()
744            ),
745        });
746    }
747    let mode = meta.permissions().mode();
748    // Any group or other permission bit means the key is exposed beyond the owner.
749    if mode & 0o077 != 0 {
750        return Err(ConnectionFileError::InsecurePermissions {
751            path: path.to_path_buf(),
752            mode: mode & 0o777,
753        });
754    }
755    Ok(())
756}
757
758#[cfg(windows)]
759fn verify_owner_only(path: &Path, file: &File) -> Result<(), ConnectionFileError> {
760    subc_os::windows_acl::verify_owner_only(file).map_err(|error| ConnectionFileError::Invalid {
761        reason: format!(
762            "connection file {} is not owner-only: {error}",
763            path.display()
764        ),
765    })
766}
767
768#[cfg(not(any(unix, windows)))]
769fn verify_owner_only(_path: &Path, _file: &File) -> Result<(), ConnectionFileError> {
770    Ok(())
771}
772
773pub fn generate_key() -> Result<Vec<u8>, ConnectionFileError> {
774    let mut key = vec![0u8; KEY_LEN];
775    getrandom::getrandom(&mut key).map_err(ConnectionFileError::Random)?;
776    Ok(key)
777}
778
779pub fn generate_daemon_id() -> Result<[u8; DAEMON_ID_LEN], ConnectionFileError> {
780    let mut daemon_id = [0u8; DAEMON_ID_LEN];
781    getrandom::getrandom(&mut daemon_id).map_err(ConnectionFileError::Random)?;
782    Ok(daemon_id)
783}
784
785fn write_atomic_inner(
786    path: &Path,
787    temp_path: &Path,
788    json: &[u8],
789) -> Result<(), ConnectionFileError> {
790    {
791        let mut file =
792            open_owner_only_new(temp_path).map_err(|source| ConnectionFileError::Io {
793                op: "create_temp",
794                path: temp_path.to_path_buf(),
795                source,
796            })?;
797        file.write_all(json)
798            .and_then(|()| file.sync_all())
799            .map_err(|source| ConnectionFileError::Io {
800                op: "write_temp",
801                path: temp_path.to_path_buf(),
802                source,
803            })?;
804    }
805
806    fs::rename(temp_path, path).map_err(|source| ConnectionFileError::Io {
807        op: "rename",
808        path: path.to_path_buf(),
809        source,
810    })?;
811    Ok(())
812}
813
814#[cfg(not(windows))]
815fn open_owner_only_new(path: &Path) -> io::Result<File> {
816    let mut options = OpenOptions::new();
817    options.write(true).create_new(true);
818    #[cfg(unix)]
819    {
820        use std::os::unix::fs::OpenOptionsExt;
821        options.mode(0o600);
822    }
823    options.open(path)
824}
825
826#[cfg(windows)]
827fn open_owner_only_new(path: &Path) -> io::Result<File> {
828    subc_os::windows_acl::create_private_file(path)
829}
830
831fn temp_path(parent: &Path, file_name: &std::ffi::OsStr) -> Result<PathBuf, ConnectionFileError> {
832    let mut suffix = [0u8; 16];
833    getrandom::getrandom(&mut suffix).map_err(ConnectionFileError::Random)?;
834    let file_name = file_name.to_string_lossy();
835    Ok(parent.join(format!(
836        ".{file_name}.{}.{}.tmp",
837        process::id(),
838        hex(&suffix)
839    )))
840}
841
842fn hex(bytes: &[u8]) -> String {
843    const HEX: &[u8; 16] = b"0123456789abcdef";
844    let mut out = String::with_capacity(bytes.len() * 2);
845    for byte in bytes {
846        out.push(HEX[(byte >> 4) as usize] as char);
847        out.push(HEX[(byte & 0x0f) as usize] as char);
848    }
849    out
850}
851
852impl fmt::Display for ConnectionFileError {
853    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
854        match self {
855            Self::MissingParent { path } => {
856                write!(f, "connection file path has no parent: {}", path.display())
857            }
858            Self::MissingFileName { path } => {
859                write!(
860                    f,
861                    "connection file path has no file name: {}",
862                    path.display()
863                )
864            }
865            Self::Io { op, path, source } => write!(
866                f,
867                "connection file {op} failed for {}: {source}",
868                path.display()
869            ),
870            Self::JsonRead { path, source } => write!(
871                f,
872                "connection file JSON read failed for {}: {source}",
873                path.display()
874            ),
875            Self::JsonWrite { path, source } => write!(
876                f,
877                "connection file JSON write failed for {}: {source}",
878                path.display()
879            ),
880            Self::Random(source) => write!(f, "connection file random generation failed: {source}"),
881            Self::UnsupportedSchema { schema, supported } => write!(
882                f,
883                "unsupported connection file schema {schema}; expected {supported}"
884            ),
885            Self::WireVersionMismatch { file, supported } => write!(
886                f,
887                "connection file wire version {file} does not match supported wire version {supported}; the binary must be upgraded"
888            ),
889            Self::Invalid { reason } => write!(f, "invalid connection file: {reason}"),
890            Self::KeyTooShort { len, min } => write!(
891                f,
892                "connection file key is too short: {len} bytes, need at least {min}"
893            ),
894            Self::InsecurePermissions { path, mode } => write!(
895                f,
896                "connection file {} has insecure permissions {mode:#o}; expected owner-only 0600",
897                path.display()
898            ),
899            Self::InsecureParentDirectory { component, mode } => write!(
900                f,
901                "refusing to publish the connection file: ancestor {} is mode {mode:#o}, \
902                 which lets another user replace the file regardless of its own 0600 mode; \
903                 this is a misconfiguration check, not a defence against a same-uid caller",
904                component.display()
905            ),
906        }
907    }
908}
909
910impl Error for ConnectionFileError {
911    fn source(&self) -> Option<&(dyn Error + 'static)> {
912        match self {
913            Self::Io { source, .. } => Some(source),
914            Self::JsonRead { source, .. } | Self::JsonWrite { source, .. } => Some(source),
915            Self::Random(_) => None,
916            Self::MissingParent { .. }
917            | Self::MissingFileName { .. }
918            | Self::InsecureParentDirectory { .. }
919            | Self::UnsupportedSchema { .. }
920            | Self::WireVersionMismatch { .. }
921            | Self::Invalid { .. }
922            | Self::KeyTooShort { .. }
923            | Self::InsecurePermissions { .. } => None,
924        }
925    }
926}
927
928#[cfg(test)]
929mod tests {
930    use super::*;
931    use cortexkit_test_support::ScratchDir;
932
933    fn sample_info() -> ConnectionInfo {
934        ConnectionInfo {
935            schema: SCHEMA_VERSION,
936            wire_version: None,
937            endpoints: vec![Endpoint {
938                host: "127.0.0.1".to_owned(),
939                port: 8799,
940            }],
941            key: vec![0xABu8; KEY_LEN],
942            daemon_id: [0x11u8; DAEMON_ID_LEN],
943            pid: 4242,
944            daemon_ver: "subc-test".to_owned(),
945        }
946    }
947
948    #[cfg(windows)]
949    #[test]
950    fn windows_connection_temp_has_exact_protected_dacl_before_write() {
951        use subc_os::windows_acl::test_support::{assert_owner_only, grant_everyone};
952        let root = unique_temp_dir("windows-connection-temp");
953        grant_everyone(root.path());
954        let path = root.join("temp.json");
955        let _file = open_owner_only_new(&path).unwrap();
956        assert_owner_only(&path, false, true);
957    }
958
959    #[cfg(windows)]
960    #[test]
961    fn windows_connection_publication_has_exact_protected_dacl() {
962        use subc_os::windows_acl::test_support::{assert_owner_only, grant_everyone};
963        let root = unique_temp_dir("windows-connection-publication");
964        grant_everyone(root.path());
965        let parent = root.join("run");
966        let path = parent.join(CONNECTION_FILE_NAME);
967        write_atomic(&path, &sample_info()).unwrap();
968        assert_owner_only(&parent, true, true);
969        assert_owner_only(&path, false, true);
970        assert_eq!(read(&path).unwrap(), sample_info());
971    }
972
973    #[cfg(windows)]
974    #[test]
975    fn windows_reader_refuses_everyone_read_without_repairing_file() {
976        use subc_os::windows_acl::test_support::grant_everyone_read;
977        let root = unique_temp_dir("windows-reader-everyone");
978        subc_os::windows_acl::create_private_dir(root.path()).unwrap();
979        let path = root.join(CONNECTION_FILE_NAME);
980        write_atomic(&path, &sample_info()).unwrap();
981        grant_everyone_read(&path);
982        let json = fs::read(&path).unwrap();
983        assert!(matches!(
984            read(&path),
985            Err(ConnectionFileError::Invalid { .. })
986        ));
987        assert_eq!(fs::read(&path).unwrap(), json);
988        assert!(subc_os::windows_acl::verify_owner_only(&File::open(&path).unwrap()).is_err());
989    }
990
991    #[cfg(windows)]
992    #[test]
993    fn windows_reader_refuses_foreign_owner_when_token_can_assign_one() {
994        use subc_os::windows_acl::test_support::apply_sddl;
995        let root = unique_temp_dir("windows-reader-owner");
996        subc_os::windows_acl::create_private_dir(root.path()).unwrap();
997        let path = root.join(CONNECTION_FILE_NAME);
998        write_atomic(&path, &sample_info()).unwrap();
999        // BUILTIN\Users: an ordinary group, unlike the Administrators owner an
1000        // elevated writer produces, which the reader accepts.
1001        match apply_sddl(&path, "O:BU", true) {
1002            Ok(()) => {}
1003            Err(error) if matches!(error.raw_os_error(), Some(5 | 1300 | 1307 | 1314)) => {
1004                eprintln!("foreign owner fixture requires an elevated token: {error}");
1005                return;
1006            }
1007            Err(error) => panic!("assign foreign owner: {error}"),
1008        }
1009        assert!(matches!(
1010            read(&path),
1011            Err(ConnectionFileError::Invalid { .. })
1012        ));
1013    }
1014
1015    #[cfg(windows)]
1016    #[test]
1017    fn windows_writer_refuses_existing_shared_directory_without_repair() {
1018        use subc_os::windows_acl::test_support::grant_everyone;
1019        let root = unique_temp_dir("windows-writer-shared");
1020        grant_everyone(root.path());
1021        let path = root.join(CONNECTION_FILE_NAME);
1022        assert!(matches!(
1023            write_atomic(&path, &sample_info()),
1024            Err(ConnectionFileError::Invalid { .. })
1025        ));
1026        assert!(!path.exists());
1027        assert!(subc_os::windows_acl::verify_private_dir(root.path()).is_err());
1028    }
1029
1030    fn unique_temp_path() -> PathBuf {
1031        let mut suffix = [0u8; 8];
1032        getrandom::getrandom(&mut suffix).expect("random suffix");
1033        let mut name = String::from("subc-connfile-test-");
1034        for byte in suffix {
1035            name.push_str(&format!("{byte:02x}"));
1036        }
1037        name.push_str(".json");
1038        std::env::temp_dir().join(name)
1039    }
1040
1041    fn unique_temp_dir(label: &str) -> ScratchDir {
1042        ScratchDir::new(label)
1043    }
1044
1045    #[cfg(unix)]
1046    #[test]
1047    fn a_foreign_owned_ancestor_refuses_even_with_mode_0755() {
1048        use std::os::unix::fs::{MetadataExt, PermissionsExt};
1049        let root = unique_temp_dir("foreign-ancestor");
1050        let parent = root.join("run");
1051        fs::create_dir(&parent).unwrap();
1052        fs::set_permissions(&parent, fs::Permissions::from_mode(0o755)).unwrap();
1053        // Model a root writer inspecting an ordinary user's directory. The walk
1054        // uses actual filesystem metadata, without changing the test process uid.
1055        if fs::metadata(&parent).unwrap().uid() == 0 {
1056            assert!(process::Command::new("chown")
1057                .args(["65534"])
1058                .arg(&parent)
1059                .status()
1060                .unwrap()
1061                .success());
1062        }
1063        assert_ne!(fs::metadata(&parent).unwrap().uid(), 0);
1064        assert!(
1065            refuse_writable_ancestor_for_uid(&parent, 0).is_err(),
1066            "0755 does not prevent its owner replacing the key"
1067        );
1068        if rustix::process::geteuid().as_raw() != 0 {
1069            assert!(
1070                refuse_writable_ancestor(&parent).is_ok(),
1071                "the same directory is safe for its actual owner"
1072            );
1073        }
1074    }
1075
1076    #[cfg(unix)]
1077    #[test]
1078    fn owner_only_file_validation_refuses_a_different_effective_uid() {
1079        use std::os::unix::fs::{MetadataExt, PermissionsExt};
1080        let root = unique_temp_dir("foreign-file");
1081        let path = root.join(CONNECTION_FILE_NAME);
1082        write_atomic(&path, &sample_info()).unwrap();
1083        fs::set_permissions(&path, fs::Permissions::from_mode(0o600)).unwrap();
1084        let owner = fs::metadata(&path).unwrap().uid();
1085        let meta = fs::metadata(&path).unwrap();
1086        assert!(verify_owner_only_for_uid(&path, &meta, owner).is_ok());
1087        let different_uid = if owner == 0 { 1 } else { 0 };
1088        assert!(
1089            matches!(
1090                verify_owner_only_for_uid(&path, &meta, different_uid),
1091                Err(ConnectionFileError::Invalid { .. })
1092            ),
1093            "0600 is not proof that the file belongs to the reader"
1094        );
1095        assert_eq!(read(&path).unwrap(), sample_info());
1096    }
1097
1098    /// A GROUP-writable ancestor must refuse, and the passing control on the same
1099    /// fixture minus the group bit is what makes this test discriminate.
1100    ///
1101    /// Both arms are here because the refusal MESSAGE is not the property: a test
1102    /// matching on message text passes through a removed check whenever the
1103    /// wording survives, which is how the adjacent guard in claustrum kept three
1104    /// green tests while examining only `0o002`. The arms differ by one bit on
1105    /// one directory and nothing else.
1106    #[cfg(unix)]
1107    #[test]
1108    fn a_group_writable_ancestor_refuses_and_the_same_tree_without_the_bit_publishes() {
1109        use std::os::unix::fs::PermissionsExt;
1110
1111        for (ancestor_mode, expect_refusal) in [(0o770, true), (0o750, false)] {
1112            let root = unique_temp_dir(&format!("ancestor-{ancestor_mode:o}"));
1113            let ancestor = root.join("ancestor");
1114            let leaf = ancestor.join("run");
1115            fs::create_dir_all(&leaf).expect("create leaf");
1116            fs::set_permissions(&leaf, fs::Permissions::from_mode(0o700))
1117                .expect("tighten the leaf so only the ancestor differs");
1118            fs::set_permissions(&ancestor, fs::Permissions::from_mode(ancestor_mode))
1119                .expect("set ancestor mode");
1120
1121            let result = write_atomic(leaf.join(CONNECTION_FILE_NAME), &sample_info());
1122
1123            match (expect_refusal, result) {
1124                (true, Err(ConnectionFileError::InsecureParentDirectory { component, mode })) => {
1125                    let expected = ancestor.canonicalize().unwrap_or_else(|_| ancestor.clone());
1126                    assert_eq!(component, expected);
1127                    assert_eq!(mode & 0o020, 0o020, "the group bit is what refused");
1128                }
1129                (true, other) => panic!("a group-writable ancestor must refuse, got {other:?}"),
1130                (false, Ok(())) => {}
1131                (false, other) => panic!("0o750 is not writable by another user: {other:?}"),
1132            }
1133
1134            let _ = fs::set_permissions(&ancestor, fs::Permissions::from_mode(0o700));
1135            let _ = fs::remove_dir_all(root);
1136        }
1137    }
1138
1139    /// `/tmp` is 1777 by design. Without the sticky exemption this check fires on
1140    /// every correctly-configured system, and a check that refuses healthy
1141    /// configuration gets disabled -- after which it protects nothing.
1142    #[cfg(unix)]
1143    #[test]
1144    fn a_sticky_world_writable_ancestor_publishes() {
1145        use std::os::unix::fs::PermissionsExt;
1146
1147        let root = unique_temp_dir("ancestor-sticky");
1148        let ancestor = root.join("sticky");
1149        let leaf = ancestor.join("run");
1150        fs::create_dir_all(&leaf).expect("create leaf");
1151        fs::set_permissions(&leaf, fs::Permissions::from_mode(0o700)).expect("tighten leaf");
1152        fs::set_permissions(&ancestor, fs::Permissions::from_mode(0o1777)).expect("sticky 1777");
1153
1154        let published = write_atomic(leaf.join(CONNECTION_FILE_NAME), &sample_info());
1155        assert!(
1156            published.is_ok(),
1157            "a sticky 1777 ancestor is /tmp's own shape and must publish: {published:?}"
1158        );
1159
1160        let _ = fs::set_permissions(&ancestor, fs::Permissions::from_mode(0o700));
1161        let _ = fs::remove_dir_all(root);
1162    }
1163
1164    /// The daemon owns this directory, so the misconfiguration is unproducible
1165    /// rather than merely reported when the directory does not yet exist.
1166    #[cfg(unix)]
1167    #[test]
1168    fn an_absent_parent_is_created_owner_only() {
1169        use std::os::unix::fs::PermissionsExt;
1170
1171        let root = unique_temp_dir("absent-parent");
1172        let parent = root.join("run");
1173        assert!(!parent.exists(), "fixture must start with no parent");
1174
1175        write_atomic(parent.join(CONNECTION_FILE_NAME), &sample_info()).expect("publishes");
1176
1177        let mode = fs::metadata(&parent)
1178            .expect("parent exists")
1179            .permissions()
1180            .mode()
1181            & 0o777;
1182        assert_eq!(mode, 0o700, "an absent parent is created owner-only");
1183
1184        let _ = fs::remove_dir_all(root);
1185    }
1186
1187    fn prod_connection_file(home: &Path) -> PathBuf {
1188        let mut path = home.to_path_buf();
1189        for part in PROD_CONNECTION_RELATIVE_PATH {
1190            path.push(part);
1191        }
1192        path
1193    }
1194
1195    #[test]
1196    fn an_explicit_path_is_the_only_discovery_candidate() {
1197        let explicit = PathBuf::from("/rig/explicit.json");
1198        let env_named = OsStr::new("/rig/from-env.json");
1199
1200        assert_eq!(
1201            discovery_candidates(Some(&explicit), Some(env_named)),
1202            vec![explicit],
1203            "the caller's explicit override must exclude every fallback"
1204        );
1205    }
1206
1207    #[test]
1208    fn set_and_wrong_environment_path_fails_without_fallback() {
1209        let root = unique_temp_dir("env-exclusive");
1210        let runtime = root.join("runtime");
1211        let home = root.join("home");
1212        let temp = root.join("temp");
1213        let named = root.join("missing-rig.json");
1214        let production = prod_connection_file(&home);
1215        fs::create_dir_all(production.parent().expect("production parent"))
1216            .expect("create production parent");
1217        write_atomic(&production, &sample_info()).expect("write discoverable production file");
1218
1219        assert_eq!(
1220            discovery_candidates(None, Some(named.as_os_str())),
1221            vec![named.clone()],
1222            "a named connection file must not be followed by discovery paths"
1223        );
1224        let candidates = discovery_candidates_with_environment(
1225            None,
1226            Some(named.as_os_str()),
1227            Some(runtime.as_os_str()),
1228            Some(home.as_os_str()),
1229            &temp,
1230        );
1231        let error = discover_candidates(candidates)
1232            .expect_err("set-and-wrong SUBC_CONNECTION_FILE must fail rather than use production");
1233
1234        assert_eq!(
1235            error.tried,
1236            vec![TriedCandidate {
1237                path: named.clone(),
1238                reason: "not found".to_owned(),
1239            }],
1240            "the named rig path must be the only attempted file"
1241        );
1242        assert!(
1243            error.to_string().contains(&named.display().to_string()),
1244            "the failure must name the operator-selected rig path"
1245        );
1246        drop(root);
1247    }
1248
1249    #[test]
1250    fn empty_environment_paths_are_unset_and_fallback_candidates_are_absolute() {
1251        let root = unique_temp_dir("empty-candidates");
1252        let runtime = root.join("runtime");
1253        let home = root.join("home");
1254        let temp = root.join("temp");
1255        let empty = OsStr::new("");
1256
1257        let without_named_override = discovery_candidates_with_environment(
1258            None,
1259            None,
1260            Some(runtime.as_os_str()),
1261            Some(home.as_os_str()),
1262            &temp,
1263        );
1264        let with_empty_named_override = discovery_candidates_with_environment(
1265            None,
1266            Some(empty),
1267            Some(runtime.as_os_str()),
1268            Some(home.as_os_str()),
1269            &temp,
1270        );
1271        assert_eq!(with_empty_named_override, without_named_override);
1272
1273        let without_runtime =
1274            discovery_candidates_with_environment(None, None, None, Some(home.as_os_str()), &temp);
1275        let with_empty_runtime = discovery_candidates_with_environment(
1276            None,
1277            None,
1278            Some(empty),
1279            Some(home.as_os_str()),
1280            &temp,
1281        );
1282        assert_eq!(with_empty_runtime, without_runtime);
1283        assert!(
1284            with_empty_named_override.iter().all(|path| path.is_absolute())
1285                && with_empty_runtime.iter().all(|path| path.is_absolute()),
1286            "every fallback candidate must be absolute: {with_empty_named_override:?} {with_empty_runtime:?}"
1287        );
1288
1289        drop(root);
1290    }
1291
1292    #[test]
1293    fn discovery_without_overrides_keeps_three_rung_order_and_deduplicates() {
1294        let root = unique_temp_dir("candidate-order");
1295        let runtime = root.join("runtime");
1296        let home = root.join("home");
1297        let temp = root.join("temp");
1298
1299        let candidates = discovery_candidates_with_environment(
1300            None,
1301            None,
1302            Some(runtime.as_os_str()),
1303            Some(home.as_os_str()),
1304            &temp,
1305        );
1306        assert_eq!(
1307            candidates,
1308            vec![
1309                runtime.join(CONNECTION_FILE_NAME),
1310                prod_connection_file(&home),
1311                temp.join(format!("subc-{}.connection.json", user_connection_token())),
1312            ],
1313            "readers must try runtime, production, then the per-user temp fallback"
1314        );
1315
1316        let production = prod_connection_file(&home);
1317        let production_dir = production.parent().expect("production directory");
1318        let deduplicated = discovery_candidates_with_environment(
1319            None,
1320            None,
1321            Some(production_dir.as_os_str()),
1322            Some(home.as_os_str()),
1323            &temp,
1324        );
1325        assert_eq!(
1326            deduplicated,
1327            vec![
1328                production,
1329                temp.join(format!("subc-{}.connection.json", user_connection_token())),
1330            ],
1331            "one path reached through two rungs must only be tried once"
1332        );
1333        drop(root);
1334    }
1335
1336    #[test]
1337    fn discover_on_a_temp_home_returns_the_parsed_production_file() {
1338        const CHILD_MARKER: &str = "SUBC_TRANSPORT_DISCOVERY_CHILD_EXPECTED";
1339        if let Some(expected) = env::var_os(CHILD_MARKER) {
1340            let expected = PathBuf::from(expected);
1341            let discovered = discover(None).expect("discover production connection file");
1342            assert_eq!(discovered.path, expected);
1343            assert_eq!(discovered.info, sample_info());
1344            return;
1345        }
1346
1347        let root = unique_temp_dir("discover-home");
1348        let home = root.join("home");
1349        let temp = root.join("temp");
1350        fs::create_dir_all(&temp).expect("create child temp directory");
1351        let production = prod_connection_file(&home);
1352        fs::create_dir_all(production.parent().expect("production parent"))
1353            .expect("create production parent");
1354        write_atomic(&production, &sample_info()).expect("write production connection file");
1355
1356        // Run the public environment-reading API in a child so this test does not
1357        // mutate process-global environment while sibling tests execute.
1358        let output = process::Command::new(env::current_exe().expect("current test executable"))
1359            .args([
1360                "--exact",
1361                "connection_file::tests::discover_on_a_temp_home_returns_the_parsed_production_file",
1362                "--nocapture",
1363            ])
1364            .env(CHILD_MARKER, &production)
1365            .env_remove("SUBC_CONNECTION_FILE")
1366            .env_remove("XDG_RUNTIME_DIR")
1367            .env("HOME", &home)
1368            .env("TMPDIR", &temp)
1369            .env("TMP", &temp)
1370            .env("TEMP", &temp)
1371            .output()
1372            .expect("run isolated discovery child");
1373        assert!(
1374            output.status.success(),
1375            "discovery child failed\nstdout:\n{}\nstderr:\n{}",
1376            String::from_utf8_lossy(&output.stdout),
1377            String::from_utf8_lossy(&output.stderr)
1378        );
1379        drop(root);
1380    }
1381
1382    #[test]
1383    fn write_atomic_sweeps_stale_temps_and_spares_recent_and_unrelated_files() {
1384        let dir = ScratchDir::new("subc-sweep");
1385        let target = dir.join("subc-connection.json");
1386
1387        // A temp stranded by a dead writer: correct shape, old enough to sweep.
1388        let stale = dir.join(".subc-connection.json.99999.deadbeef.tmp");
1389        fs::write(&stale, b"stranded").expect("write stale");
1390        let old = SystemTime::now() - Duration::from_secs(3600);
1391        File::options()
1392            .write(true)
1393            .open(&stale)
1394            .expect("open stale")
1395            .set_modified(old)
1396            .expect("backdate stale");
1397
1398        // A temp from a writer that may still be mid-rename: same shape, fresh.
1399        // Sweeping this would race a concurrent publish.
1400        let recent = dir.join(".subc-connection.json.99998.feedface.tmp");
1401        fs::write(&recent, b"in flight").expect("write recent");
1402
1403        // An old file that is not one of our temps. Age alone must not condemn it.
1404        let unrelated = dir.join("unrelated.txt");
1405        fs::write(&unrelated, b"not ours").expect("write unrelated");
1406        File::options()
1407            .write(true)
1408            .open(&unrelated)
1409            .expect("open unrelated")
1410            .set_modified(old)
1411            .expect("backdate unrelated");
1412
1413        write_atomic(&target, &sample_info()).expect("publish");
1414
1415        assert!(!stale.exists(), "a stale temp must be swept");
1416        assert!(
1417            recent.exists(),
1418            "a recent temp may belong to an in-flight publish and must be spared"
1419        );
1420        assert!(
1421            unrelated.exists(),
1422            "age alone must not condemn a file that is not one of our temps"
1423        );
1424        assert!(target.exists(), "the publish itself must still land");
1425    }
1426
1427    #[test]
1428    fn debug_redacts_key_bytes() {
1429        let info = sample_info();
1430        let rendered = format!("{info:?}");
1431        assert!(
1432            rendered.contains("redacted"),
1433            "Debug must mark the key as redacted: {rendered}"
1434        );
1435        // The raw key byte pattern (0xab) must not appear anywhere in the output.
1436        assert!(
1437            !rendered.contains("171") && !rendered.to_lowercase().contains("ab, ab"),
1438            "Debug must not leak raw key bytes: {rendered}"
1439        );
1440    }
1441
1442    #[test]
1443    fn validate_rejects_unsupported_schema_empty_endpoints_and_short_key() {
1444        let mut unsupported_schema = sample_info();
1445        unsupported_schema.schema = SCHEMA_VERSION + 1;
1446        let before = unsupported_schema.clone();
1447        let err = unsupported_schema
1448            .validate()
1449            .expect_err("unsupported schema must be rejected");
1450        assert!(matches!(
1451            err,
1452            ConnectionFileError::UnsupportedSchema {
1453                schema,
1454                supported: SCHEMA_VERSION,
1455            } if schema == SCHEMA_VERSION + 1
1456        ));
1457        assert_eq!(unsupported_schema, before, "validate must not mutate input");
1458
1459        let mut empty_endpoints = sample_info();
1460        empty_endpoints.endpoints.clear();
1461        let before = empty_endpoints.clone();
1462        let err = empty_endpoints
1463            .validate()
1464            .expect_err("empty endpoint list must be rejected");
1465        assert!(matches!(
1466            err,
1467            ConnectionFileError::Invalid { ref reason }
1468                if reason == "connection file must include at least one endpoint"
1469        ));
1470        assert_eq!(empty_endpoints, before, "validate must not mutate input");
1471
1472        let mut short_key = sample_info();
1473        short_key.key = vec![0xAB; MIN_KEY_LEN - 1];
1474        let before = short_key.clone();
1475        let err = short_key
1476            .validate()
1477            .expect_err("short key must be rejected");
1478        assert!(matches!(
1479            err,
1480            ConnectionFileError::KeyTooShort {
1481                len,
1482                min: MIN_KEY_LEN,
1483            } if len == MIN_KEY_LEN - 1
1484        ));
1485        assert_eq!(short_key, before, "validate must not mutate input");
1486    }
1487
1488    #[test]
1489    fn optional_wire_version_round_trips() {
1490        let path = unique_temp_path();
1491        let legacy = sample_info();
1492        write_atomic(&path, &legacy).expect("write legacy connection file");
1493        let legacy_json = fs::read_to_string(&path).expect("read legacy connection file");
1494        assert!(!legacy_json.contains("wire_version"));
1495        assert_eq!(
1496            read_for_client(&path).expect("legacy file remains readable"),
1497            legacy
1498        );
1499
1500        let mut current = sample_info();
1501        current.wire_version = Some(PROTOCOL_VERSION);
1502        write_atomic(&path, &current).expect("write current connection file");
1503        let current_json = fs::read_to_string(&path).expect("read current connection file");
1504        let current_json: serde_json::Value =
1505            serde_json::from_str(&current_json).expect("parse current connection file");
1506        assert_eq!(
1507            current_json["wire_version"].as_u64(),
1508            Some(u64::from(PROTOCOL_VERSION))
1509        );
1510        assert_eq!(
1511            read_for_client(&path).expect("current file is readable"),
1512            current
1513        );
1514        let _ = fs::remove_file(&path);
1515    }
1516
1517    #[test]
1518    fn read_for_client_rejects_mismatched_wire_version() {
1519        let path = unique_temp_path();
1520        let mut info = sample_info();
1521        let file_version = PROTOCOL_VERSION + 1;
1522        info.wire_version = Some(file_version);
1523        write_atomic(&path, &info).expect("write mismatched connection file");
1524
1525        let err = read_for_client(&path).expect_err("mismatched wire version must fail discovery");
1526        assert!(matches!(
1527            err,
1528            ConnectionFileError::WireVersionMismatch { file, supported }
1529                if file == file_version && supported == PROTOCOL_VERSION
1530        ));
1531        let rendered = err.to_string();
1532        assert!(rendered.contains(&file_version.to_string()));
1533        assert!(rendered.contains(&PROTOCOL_VERSION.to_string()));
1534        assert!(rendered.contains("binary must be upgraded"));
1535        let _ = fs::remove_file(&path);
1536    }
1537
1538    fn unix_endpoint() -> LocalEndpoint {
1539        LocalEndpoint::Unix {
1540            path: PathBuf::from("/run/user/1000/cortexkit/subc.sock"),
1541        }
1542    }
1543
1544    fn pipe_endpoint() -> LocalEndpoint {
1545        LocalEndpoint::Pipe {
1546            name: r"\\.\pipe\subc-0123456789abcdef".to_owned(),
1547        }
1548    }
1549
1550    /// Writes raw JSON as an owner-only file so a test can hand the readers a
1551    /// shape the writer would never produce.
1552    fn write_raw_owner_only(path: &Path, json: &serde_json::Value) {
1553        let mut file = open_owner_only_new(path).expect("create owner-only fixture");
1554        file.write_all(&serde_json::to_vec_pretty(json).unwrap())
1555            .expect("write fixture");
1556    }
1557
1558    #[test]
1559    fn local_endpoint_serialises_as_kind_tagged_objects() {
1560        assert_eq!(
1561            serde_json::to_value(unix_endpoint()).unwrap(),
1562            serde_json::json!({"kind": "unix", "path": "/run/user/1000/cortexkit/subc.sock"})
1563        );
1564        assert_eq!(
1565            serde_json::to_value(pipe_endpoint()).unwrap(),
1566            serde_json::json!({"kind": "pipe", "name": r"\\.\pipe\subc-0123456789abcdef"})
1567        );
1568    }
1569
1570    #[test]
1571    fn writer_without_local_endpoint_matches_write_atomic_byte_for_byte() {
1572        let dir = unique_temp_dir("local-endpoint-absent");
1573        let plain = dir.join("plain.json");
1574        let variant = dir.join("variant.json");
1575        write_atomic(&plain, &sample_info()).expect("write plain");
1576        write_atomic_with_local_endpoint(&variant, &sample_info(), None).expect("write variant");
1577
1578        let variant_bytes = fs::read(&variant).unwrap();
1579        assert_eq!(fs::read(&plain).unwrap(), variant_bytes);
1580        assert!(
1581            !String::from_utf8(variant_bytes)
1582                .unwrap()
1583                .contains("local_endpoint"),
1584            "an absent endpoint must be omitted, never written as null"
1585        );
1586
1587        let read_back = read_with_local_endpoint(&variant).expect("read variant");
1588        assert_eq!(read_back.info, sample_info());
1589        assert_eq!(read_back.local_endpoint, None);
1590    }
1591
1592    #[test]
1593    fn local_endpoint_round_trips_and_the_plain_reader_still_parses_the_file() {
1594        for endpoint in [unix_endpoint(), pipe_endpoint()] {
1595            let dir = unique_temp_dir("local-endpoint-round-trip");
1596            let path = dir.join(CONNECTION_FILE_NAME);
1597            let mut info = sample_info();
1598            info.wire_version = Some(PROTOCOL_VERSION);
1599            write_atomic_with_local_endpoint(&path, &info, Some(&endpoint)).expect("write");
1600
1601            let json: serde_json::Value =
1602                serde_json::from_slice(&fs::read(&path).unwrap()).unwrap();
1603            assert_eq!(
1604                json["local_endpoint"],
1605                serde_json::to_value(&endpoint).unwrap()
1606            );
1607            assert_eq!(json["schema"], serde_json::json!(SCHEMA_VERSION));
1608
1609            assert_eq!(
1610                read_with_local_endpoint(&path).expect("read with endpoint"),
1611                ConnectionInfoWithLocalEndpoint {
1612                    info: info.clone(),
1613                    local_endpoint: Some(endpoint.clone()),
1614                }
1615            );
1616            assert_eq!(
1617                read_for_client_with_local_endpoint(&path)
1618                    .expect("client read with endpoint")
1619                    .local_endpoint,
1620                Some(endpoint)
1621            );
1622            // Existing readers ignore the key and see the same ConnectionInfo.
1623            assert_eq!(read(&path).expect("plain read"), info);
1624            assert_eq!(read_for_client(&path).expect("plain client read"), info);
1625        }
1626    }
1627
1628    #[test]
1629    fn a_file_written_before_local_endpoint_existed_reads_as_absent() {
1630        let dir = unique_temp_dir("local-endpoint-legacy");
1631        let path = dir.join(CONNECTION_FILE_NAME);
1632        // The exact key set an older daemon writes, with no wire_version either.
1633        let key = vec![0xABu8; KEY_LEN];
1634        let daemon_id = [0x11u8; DAEMON_ID_LEN];
1635        write_raw_owner_only(
1636            &path,
1637            &serde_json::json!({
1638                "schema": SCHEMA_VERSION,
1639                "endpoints": [{"host": "127.0.0.1", "port": 8799}],
1640                "key": key,
1641                "daemon_id": daemon_id,
1642                "pid": 4242,
1643                "daemon_ver": "subc-test",
1644            }),
1645        );
1646
1647        assert_eq!(read(&path).expect("legacy plain read"), sample_info());
1648        let read_back = read_with_local_endpoint(&path).expect("legacy read with endpoint");
1649        assert_eq!(read_back.info, sample_info());
1650        assert_eq!(read_back.local_endpoint, None);
1651    }
1652
1653    #[test]
1654    fn a_malformed_local_endpoint_is_an_error_not_absent_and_the_plain_reader_ignores_it() {
1655        let malformed = [
1656            serde_json::json!({"kind": "tcp", "host": "127.0.0.1"}),
1657            serde_json::json!({"kind": "unix"}),
1658            serde_json::json!({"path": "/tmp/subc.sock"}),
1659            serde_json::json!("/tmp/subc.sock"),
1660            serde_json::json!({"kind": "unix", "path": ""}),
1661            serde_json::json!({"kind": "pipe", "name": ""}),
1662        ];
1663        for (index, endpoint) in malformed.into_iter().enumerate() {
1664            let dir = unique_temp_dir("local-endpoint-malformed");
1665            let path = dir.join(CONNECTION_FILE_NAME);
1666            let mut json = serde_json::to_value(sample_info()).unwrap();
1667            json["local_endpoint"] = endpoint.clone();
1668            write_raw_owner_only(&path, &json);
1669
1670            assert!(
1671                matches!(
1672                    read_with_local_endpoint(&path),
1673                    Err(ConnectionFileError::JsonRead { .. } | ConnectionFileError::Invalid { .. })
1674                ),
1675                "case {index}: {endpoint} must not read as an absent endpoint"
1676            );
1677            assert_eq!(
1678                read(&path).expect("plain reader ignores local_endpoint"),
1679                sample_info(),
1680                "case {index}"
1681            );
1682        }
1683    }
1684
1685    #[test]
1686    fn writer_refuses_an_empty_local_endpoint_without_publishing() {
1687        let dir = unique_temp_dir("local-endpoint-empty");
1688        let path = dir.join(CONNECTION_FILE_NAME);
1689        for endpoint in [
1690            LocalEndpoint::Unix {
1691                path: PathBuf::new(),
1692            },
1693            LocalEndpoint::Pipe {
1694                name: String::new(),
1695            },
1696        ] {
1697            assert!(matches!(
1698                write_atomic_with_local_endpoint(&path, &sample_info(), Some(&endpoint)),
1699                Err(ConnectionFileError::Invalid { .. })
1700            ));
1701            assert!(!path.exists());
1702        }
1703    }
1704
1705    #[cfg(unix)]
1706    #[test]
1707    fn read_with_local_endpoint_keeps_the_owner_only_check() {
1708        use std::os::unix::fs::PermissionsExt;
1709
1710        let dir = unique_temp_dir("local-endpoint-perms");
1711        let path = dir.join(CONNECTION_FILE_NAME);
1712        write_atomic_with_local_endpoint(&path, &sample_info(), Some(&unix_endpoint()))
1713            .expect("write");
1714        fs::set_permissions(&path, fs::Permissions::from_mode(0o644)).expect("relax");
1715        assert!(matches!(
1716            read_with_local_endpoint(&path),
1717            Err(ConnectionFileError::InsecurePermissions { mode, .. }) if mode == 0o644
1718        ));
1719    }
1720
1721    #[cfg(unix)]
1722    #[test]
1723    fn read_rejects_group_or_world_readable_file() {
1724        use std::os::unix::fs::PermissionsExt;
1725
1726        let path = unique_temp_path();
1727        write_atomic(&path, &sample_info()).expect("write owner-only file");
1728        // Loosen permissions as if the key leaked to other local users.
1729        fs::set_permissions(&path, fs::Permissions::from_mode(0o644)).expect("relax permissions");
1730
1731        let err = read(&path).expect_err("group/world-readable key file must be rejected");
1732        assert!(
1733            matches!(err, ConnectionFileError::InsecurePermissions { mode, .. } if mode == 0o644),
1734            "expected InsecurePermissions, got {err:?}"
1735        );
1736        let _ = fs::remove_file(&path);
1737    }
1738}