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