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
24pub 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
49impl 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
76#[serde(tag = "kind", rename_all = "lowercase")]
77#[non_exhaustive]
78pub enum LocalEndpoint {
79 Unix { path: PathBuf },
81 Pipe { name: String },
83}
84
85impl LocalEndpoint {
86 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#[derive(Debug, Clone, PartialEq, Eq)]
105pub struct ConnectionInfoWithLocalEndpoint {
106 pub info: ConnectionInfo,
107 pub local_endpoint: Option<LocalEndpoint>,
110}
111
112#[derive(Deserialize)]
116struct LocalEndpointField {
117 #[serde(default)]
118 local_endpoint: Option<LocalEndpoint>,
119}
120
121#[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#[derive(Debug, Clone, PartialEq, Eq)]
134pub struct Discovered {
135 pub path: PathBuf,
136 pub info: ConnectionInfo,
137}
138
139#[derive(Debug, Clone, PartialEq, Eq)]
141pub struct TriedCandidate {
142 pub path: PathBuf,
143 pub reason: String,
144}
145
146#[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 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
254pub 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 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_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
312fn 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#[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 let Ok(resolved) = fs::canonicalize(parent) else {
393 return Ok(());
394 };
395
396 let mut component = resolved.as_path();
397 loop {
398 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 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
447fn 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
489pub 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
517pub 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_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
556pub 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
564pub 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
580pub 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 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
677pub fn user_connection_token() -> String {
682 #[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 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 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 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 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 #[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 #[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 #[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 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 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 let recent = dir.join(".subc-connection.json.99998.feedface.tmp");
1401 fs::write(&recent, b"in flight").expect("write recent");
1402
1403 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 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, ¤t).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(¤t_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 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 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 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 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}