1use std::collections::BTreeMap;
4use std::fmt::Write as _;
5use std::io::{self, Read, Write};
6use std::path::{Path, PathBuf};
7
8use serde::{Deserialize, Serialize};
9use serde_json::Value;
10
11pub const VERSION: u32 = 1;
13pub const MAX_FRAME: usize = 32 * 1024 * 1024;
15
16#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
18pub struct Submission {
19 #[serde(default)]
21 pub mode: Mode,
22 pub project_dir: PathBuf,
24 pub args: Vec<String>,
26 pub force: bool,
28 pub environment: BTreeMap<String, String>,
30 pub input_revision: Option<String>,
32}
33
34#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
36#[serde(tag = "kind", content = "selection", rename_all = "snake_case")]
37pub enum Mode {
38 #[default]
40 Stock,
41 Standalone,
43 StandaloneRepair {
45 function: String,
47 },
48 Interactive,
50 Repair(crate::repair::Selection),
52}
53
54#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
56#[serde(rename_all = "snake_case")]
57pub enum Lifecycle {
58 Queued,
60 Running,
62 Completed,
64 Cancelled,
66 Superseded,
68 InfrastructureError,
70}
71impl Lifecycle {
72 #[must_use]
74 pub const fn terminal(self) -> bool {
75 !matches!(self, Self::Queued | Self::Running)
76 }
77}
78
79#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
81#[serde(rename_all = "snake_case")]
82pub enum Currentness {
83 Current,
85 Historical,
87 Unknown,
89}
90
91#[derive(Debug, Clone, Serialize, Deserialize)]
93pub struct Status {
94 pub version: u32,
96 pub id: String,
98 pub project_dir: PathBuf,
100 pub args: Vec<String>,
102 pub state: Lifecycle,
104 pub submitted_at_ms: u64,
106 pub started_at_ms: Option<u64>,
108 pub finished_at_ms: Option<u64>,
110 pub exit_code: Option<i32>,
112 pub input_revision: Option<String>,
114 pub currentness: Currentness,
116 pub error: Option<String>,
118}
119
120#[derive(Debug, Clone, Serialize, Deserialize)]
122pub struct ResultDocument {
123 #[serde(default, skip_serializing_if = "Option::is_none")]
125 pub contracts: Option<Box<crate::contracts::Evidence>>,
126 #[serde(default, skip_serializing_if = "Option::is_none")]
128 pub repair: Option<Box<crate::repair::ResultDocument>>,
129 pub job: Status,
131 pub result: Option<Value>,
133}
134
135#[derive(Debug, Clone, Serialize, Deserialize)]
137pub struct Chunk {
138 pub next: u64,
140 pub text: String,
142 pub complete: bool,
144}
145
146#[derive(Debug, Clone, Serialize, Deserialize)]
148#[serde(tag = "operation", rename_all = "snake_case")]
149pub enum Request {
150 PreparationStatus,
152 Prepare(crate::preparation::Submission),
154 Foreground {
156 version: u32,
158 project_dir: PathBuf,
160 args: Vec<String>,
162 },
163 Capabilities,
165 SubmitMutation(crate::mutation::Submission),
167 PrepareLiteralWitness {
169 source: crate::contracts::Submission,
171 max_mutants: usize,
173 },
174 ValidateLiteralWitness {
176 plan: Box<crate::literal_witness::Plan>,
178 candidate_id: String,
180 result: Box<crate::runtime::QueryResult>,
182 },
183 Mutation {
185 id: String,
187 },
188 CancelMutation {
190 id: String,
192 },
193 Assurance {
195 id: String,
197 },
198 SubmitContracts(crate::contracts::Submission),
200 ProofEvents {
202 id: String,
204 cursor: crate::proof::Cursor,
206 limit: usize,
208 },
209 Explain {
211 id: String,
213 target: crate::proof::Target,
215 function: String,
217 obligation: Option<String>,
219 },
220 SaveBaseline {
222 id: String,
224 name: String,
226 },
227 Baselines,
229 GetBaseline {
231 name: String,
233 },
234 Compare {
236 before: crate::evidence::Reference,
238 after: String,
240 },
241 Submit {
243 submission: Submission,
245 },
246 List {
248 project_dir: Option<PathBuf>,
250 },
251 Status {
253 id: String,
255 },
256 Result {
258 id: String,
260 },
261 Cancel {
263 id: String,
265 superseded: bool,
267 },
268 Logs {
270 id: String,
272 offset: u64,
274 },
275 Events {
277 id: String,
279 offset: u64,
281 },
282}
283
284#[derive(Debug, Clone, Serialize, Deserialize)]
286#[serde(tag = "response", content = "value", rename_all = "snake_case")]
287pub enum Response {
288 Preparation(crate::preparation::Status),
290 Capabilities {
292 proof_version: u32,
294 #[serde(default, skip_serializing_if = "Option::is_none")]
296 neutral_contracts_version: Option<u32>,
297 #[serde(default, skip_serializing_if = "Vec::is_empty")]
299 neutral_contract_profiles: Vec<u32>,
300 #[serde(default, skip_serializing_if = "Option::is_none")]
302 assurance_version: Option<u32>,
303 #[serde(default, skip_serializing_if = "Option::is_none")]
305 mutation_version: Option<u32>,
306 #[serde(default)]
309 repair: bool,
310 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
312 standalone: bool,
313 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
315 standalone_repair: bool,
316 },
317 Mutation(Box<crate::mutation::View>),
319 LiteralWitness(Box<crate::literal_witness::Plan>),
321 LiteralWitnessValidated(Box<crate::literal_witness::Validated>),
323 ProofEvents(crate::proof::Page),
325 Explanation(Box<crate::evidence::Explanation>),
327 Assurance(Box<crate::assurance::View>),
329 Baseline(Box<crate::evidence::Baseline>),
331 Baselines(Vec<String>),
333 Comparison(crate::evidence::Comparison),
335 Status(Status),
337 List(Vec<Status>),
339 Result(ResultDocument),
341 Chunk(Chunk),
343 Error(String),
345}
346
347#[derive(Serialize, Deserialize)]
348struct Envelope<T> {
349 version: u32,
350 body: T,
351}
352
353pub fn write_frame<T: Serialize>(writer: &mut impl Write, body: &T) -> io::Result<()> {
358 let bytes = serde_json::to_vec(&Envelope {
359 version: VERSION,
360 body,
361 })
362 .map_err(io::Error::other)?;
363 if bytes.len() > MAX_FRAME {
364 return Err(io::Error::other("SAIL0802: job frame exceeds limit"));
365 }
366 let size = u32::try_from(bytes.len()).map_err(io::Error::other)?;
367 writer.write_all(&size.to_be_bytes())?;
368 writer.write_all(&bytes)?;
369 writer.flush()
370}
371
372pub fn read_frame<T: serde::de::DeserializeOwned>(reader: &mut impl Read) -> io::Result<T> {
377 let mut length = [0; 4];
378 reader.read_exact(&mut length)?;
379 let size = usize::try_from(u32::from_be_bytes(length)).map_err(io::Error::other)?;
380 if size > MAX_FRAME {
381 return Err(io::Error::other("SAIL0802: job frame exceeds limit"));
382 }
383 let mut bytes = vec![0; size];
384 reader.read_exact(&mut bytes)?;
385 let envelope: Envelope<T> = serde_json::from_slice(&bytes).map_err(io::Error::other)?;
386 if envelope.version != VERSION {
387 return Err(io::Error::other("SAIL0802: incompatible job protocol"));
388 }
389 Ok(envelope.body)
390}
391
392pub fn cache_directory() -> io::Result<PathBuf> {
397 let var = |name: &str| std::env::var_os(name).filter(|value| !value.is_empty());
398 var("SAIL_CACHE_DIR")
399 .map(PathBuf::from)
400 .or_else(|| var("XDG_CACHE_HOME").map(|root| PathBuf::from(root).join("sail")))
401 .or_else(|| var("HOME").map(|root| PathBuf::from(root).join(".cache/sail")))
402 .ok_or_else(|| {
403 io::Error::other(
404 "error[SAIL3001]: none of SAIL_CACHE_DIR, XDG_CACHE_HOME or HOME is set",
405 )
406 })
407}
408
409pub const MAX_SOCKET_PATH: usize = if cfg!(target_os = "linux") { 107 } else { 103 };
413
414#[must_use]
425pub fn default_cache_socket(cache: &Path) -> PathBuf {
426 let socket = cache.join(format!(
427 "daemon-v{}-workspace-v2-proof-v1.sock",
428 crate::protocol::PROTOCOL_VERSION
429 ));
430 if socket_fits(&socket) {
431 return socket;
432 }
433 short_socket(&socket).unwrap_or(socket)
434}
435
436#[must_use]
438pub fn socket_fits(cache_socket: &Path) -> bool {
439 let absolute = std::path::absolute(cache_socket).unwrap_or_else(|_| cache_socket.to_owned());
440 absolute.as_os_str().len() <= MAX_SOCKET_PATH
441 && socket_path(cache_socket).as_os_str().len() <= MAX_SOCKET_PATH
442}
443
444#[cfg(unix)]
445fn short_socket(socket: &Path) -> Option<PathBuf> {
446 use std::os::unix::fs::{DirBuilderExt as _, MetadataExt as _};
447 let name = socket.file_name()?;
448 let digest = sail_key::sha256(endpoint_path(socket).as_os_str().as_encoded_bytes());
449 let hash = digest
450 .iter()
451 .take(8)
452 .fold(String::new(), |mut value, byte| {
453 let _ = write!(value, "{byte:02x}");
454 value
455 });
456 let directory = Path::new("/tmp").join(format!("sail-{hash}"));
457 let _ = std::fs::DirBuilder::new().mode(0o700).create(&directory);
459 let metadata = std::fs::symlink_metadata(&directory).ok()?;
460 if !metadata.is_dir() || metadata.mode() & 0o077 != 0 {
461 return None;
462 }
463 let probe = directory.join(format!(".probe-{}", std::process::id()));
466 std::fs::File::create(&probe).ok()?;
467 std::fs::remove_file(&probe).ok()?;
468 let short = directory.join(name);
469 socket_fits(&short).then_some(short)
470}
471
472#[cfg(not(unix))]
473fn short_socket(_socket: &Path) -> Option<PathBuf> {
474 None
475}
476
477#[must_use]
480pub fn cache_socket(cache: &Path, explicit: Option<&Path>, cwd: &Path) -> PathBuf {
481 let socket = explicit.map_or_else(|| default_cache_socket(&cwd.join(cache)), Path::to_path_buf);
483 if socket.is_absolute() {
484 socket
485 } else {
486 cwd.join(socket)
487 }
488}
489
490pub fn configured_socket(cwd: &Path) -> io::Result<PathBuf> {
495 let explicit = std::env::var_os("SAIL_DAEMON_SOCKET")
496 .filter(|value| !value.is_empty())
497 .map(PathBuf::from);
498 Ok(socket_path(&cache_socket(
499 &cache_directory()?,
500 explicit.as_deref(),
501 cwd,
502 )))
503}
504
505#[must_use]
508pub fn socket_path(cache_socket: &Path) -> PathBuf {
509 let cache_socket = endpoint_path(cache_socket);
510 let digest = sail_key::sha256(cache_socket.as_os_str().as_encoded_bytes());
511 let suffix = digest
512 .iter()
513 .take(4)
514 .fold(String::new(), |mut value, byte| {
515 let _ = write!(value, "{byte:02x}");
516 value
517 });
518 cache_socket.with_file_name(format!("jobs-v1-proof-v1-{suffix}.sock"))
519}
520
521fn endpoint_path(path: &Path) -> PathBuf {
522 let absolute = std::path::absolute(path).unwrap_or_else(|_| path.to_owned());
523 for ancestor in absolute.ancestors() {
527 if let Ok(resolved) = ancestor.canonicalize()
528 && let Ok(suffix) = absolute.strip_prefix(ancestor)
529 {
530 return if suffix.as_os_str().is_empty() {
531 resolved
532 } else {
533 resolved.join(suffix)
534 };
535 }
536 }
537 absolute
538}
539
540#[cfg(unix)]
542#[derive(Debug, Clone)]
543pub struct Client {
544 socket: PathBuf,
545}
546#[cfg(unix)]
547impl Client {
548 pub fn validate_literal_witness(
552 &self,
553 plan: crate::literal_witness::Plan,
554 candidate_id: String,
555 result: &crate::runtime::QueryResult,
556 ) -> io::Result<crate::literal_witness::Validated> {
557 let prepared = plan
558 .prepared
559 .iter()
560 .find(|p| p.candidate.id == candidate_id)
561 .cloned()
562 .ok_or_else(|| io::Error::other("SAIL3145: missing literal witness candidate"))?;
563 match self.call(&Request::ValidateLiteralWitness {
564 plan: Box::new(plan),
565 candidate_id,
566 result: Box::new(result.clone()),
567 })? {
568 Response::LiteralWitnessValidated(value)
569 if value.prepared == prepared && value.model_result == *result =>
570 {
571 Ok(*value)
572 }
573 Response::Error(message) => Err(io::Error::other(message)),
574 _ => Err(io::Error::other(
575 "SAIL3145: incompatible concrete witness response",
576 )),
577 }
578 }
579 pub fn literal_witnesses(
584 &self,
585 source: &crate::contracts::Submission,
586 max_mutants: usize,
587 ) -> io::Result<crate::literal_witness::Plan> {
588 source.validate().map_err(io::Error::other)?;
589 match self.call(&Request::PrepareLiteralWitness {
590 source: source.clone(),
591 max_mutants,
592 })? {
593 Response::LiteralWitness(plan)
594 if plan.baseline == *source && plan.max_mutants == max_mutants =>
595 {
596 plan.validate().map_err(io::Error::other)?;
597 Ok(*plan)
598 }
599 Response::Error(message) => Err(io::Error::other(message)),
600 _ => Err(io::Error::other(
601 "SAIL3145: incompatible literal witness response",
602 )),
603 }
604 }
605 pub fn submit_mutation(
609 &self,
610 submission: crate::mutation::Submission,
611 ) -> io::Result<crate::mutation::View> {
612 if !matches!(
613 self.call(&Request::Capabilities)?,
614 Response::Capabilities {
615 mutation_version: Some(crate::mutation::VERSION),
616 ..
617 }
618 ) {
619 return Err(io::Error::other(
620 "SAIL3144: running service has no compatible mutation API",
621 ));
622 }
623 let expected = submission.clone();
624 let result = self.mutation_call(&Request::SubmitMutation(submission))?;
625 if result.submission != expected {
626 return Err(io::Error::other(
627 "SAIL3144: mutation submission attribution differs",
628 ));
629 }
630 Ok(result)
631 }
632 pub fn mutation(&self, id: &str) -> io::Result<crate::mutation::View> {
636 let result = self.mutation_call(&Request::Mutation { id: id.into() })?;
637 if result.id != id {
638 return Err(io::Error::other(
639 "SAIL3144: mutation campaign attribution differs",
640 ));
641 }
642 Ok(result)
643 }
644 pub fn cancel_mutation(&self, id: &str) -> io::Result<crate::mutation::View> {
648 let result = self.mutation_call(&Request::CancelMutation { id: id.into() })?;
649 if result.id != id {
650 return Err(io::Error::other(
651 "SAIL3144: mutation cancellation attribution differs",
652 ));
653 }
654 Ok(result)
655 }
656 fn mutation_call(&self, request: &Request) -> io::Result<crate::mutation::View> {
657 match self.call(request)? {
658 Response::Mutation(view) if view.version == crate::mutation::VERSION => {
659 crate::mutation::validate_view(&view).map_err(io::Error::other)?;
660 Ok(*view)
661 }
662 Response::Error(message) => Err(io::Error::other(message)),
663 _ => Err(io::Error::other("SAIL3144: incompatible mutation response")),
664 }
665 }
666 pub fn requirement_assurance(&self, id: &str) -> io::Result<crate::assurance::View> {
671 if id.is_empty() || id.len() > 256 || id.contains('\0') {
672 return Err(io::Error::other("SAIL3143: invalid assurance job identity"));
673 }
674 if !matches!(
675 self.call(&Request::Capabilities)?,
676 Response::Capabilities {
677 assurance_version: Some(crate::assurance::VERSION),
678 ..
679 }
680 ) {
681 return Err(io::Error::other(
682 "SAIL3143: endpoint does not support requirement assurance",
683 ));
684 }
685 match self.call(&Request::Assurance { id: id.into() })? {
686 Response::Assurance(view)
687 if view.version == crate::assurance::VERSION && view.job_id == id =>
688 {
689 Ok(*view)
690 }
691 Response::Error(message) => Err(io::Error::other(message)),
692 _ => Err(io::Error::other(
693 "SAIL3143: invalid assurance response attribution",
694 )),
695 }
696 }
697
698 pub fn submit_contracts(&self, submission: crate::contracts::Submission) -> io::Result<Status> {
702 submission.validate().map_err(io::Error::other)?;
703 let supported = match self.call(&Request::Capabilities)? {
704 Response::Capabilities {
705 neutral_contracts_version: Some(crate::contracts::VERSION),
706 neutral_contract_profiles,
707 ..
708 } => submission.profile == 1 || neutral_contract_profiles.contains(&submission.profile),
709 _ => false,
710 };
711 if !supported {
712 return Err(io::Error::other(
713 "SAIL3142: endpoint does not support the selected neutral source profile",
714 ));
715 }
716 match self.call(&Request::SubmitContracts(submission))? {
717 Response::Status(status) => Ok(status),
718 Response::Error(message) => Err(io::Error::other(message)),
719 _ => Err(io::Error::other(
720 "SAIL3142: unexpected neutral submission response",
721 )),
722 }
723 }
724
725 #[must_use]
727 pub fn new(socket: impl Into<PathBuf>) -> Self {
728 Self {
729 socket: socket.into(),
730 }
731 }
732 pub fn call(&self, request: &Request) -> io::Result<Response> {
737 self.call_with(request, |_| {})
738 }
739 pub fn call_with(
746 &self,
747 request: &Request,
748 connected: impl FnOnce(std::os::unix::net::UnixStream),
749 ) -> io::Result<Response> {
750 if matches!(request, Request::Submit { submission } if matches!(submission.mode, Mode::Interactive | Mode::Repair(_)))
751 && !matches!(
752 self.call(&Request::Capabilities)?,
753 Response::Capabilities {
754 proof_version: crate::proof::VERSION,
755 repair: true,
756 ..
757 }
758 )
759 {
760 return Err(io::Error::other(
761 "SAIL0903: endpoint does not support proof/repair contracts",
762 ));
763 }
764 if matches!(request, Request::Submit { submission } if submission.mode == Mode::Standalone)
765 && !matches!(
766 self.call(&Request::Capabilities)?,
767 Response::Capabilities {
768 standalone: true,
769 ..
770 }
771 )
772 {
773 return Err(io::Error::other(
774 "SAIL3150: endpoint does not support standalone file jobs; restart Sail's daemon",
775 ));
776 }
777 if matches!(request, Request::Submit { submission } if matches!(submission.mode, Mode::StandaloneRepair { .. }))
778 && !matches!(
779 self.call(&Request::Capabilities)?,
780 Response::Capabilities {
781 proof_version: crate::proof::VERSION,
782 repair: true,
783 standalone_repair: true,
784 ..
785 }
786 )
787 {
788 return Err(io::Error::other(
789 "SAIL3150: endpoint does not support standalone repair; restart Sail's daemon",
790 ));
791 }
792 let mut stream =
793 crate::client::connect_stream(&self.socket, std::time::Duration::from_secs(5))?;
794 connected(stream.try_clone()?);
795 write_frame(&mut stream, request)?;
796 match read_frame(&mut stream)? {
797 Response::Error(message) => Err(io::Error::other(message)),
798 response => Ok(response),
799 }
800 }
801}
802
803#[cfg(test)]
804mod tests {
805 use super::*;
806 #[test]
807 fn baseline_read_has_exact_additive_wire_identity() {
808 let request = Request::GetBaseline {
809 name: "--json".into(),
810 };
811 assert_eq!(
812 serde_json::to_value(&request).unwrap_or_else(|error| unreachable!("{error}")),
813 serde_json::json!({"operation":"get_baseline","name":"--json"})
814 );
815 let mut bytes = Vec::new();
816 assert!(write_frame(&mut bytes, &request).is_ok());
817 assert!(matches!(read_frame::<Request>(&mut bytes.as_slice()),
818 Ok(Request::GetBaseline { name }) if name == "--json"));
819 assert!(
820 serde_json::from_value::<Request>(
821 serde_json::json!({"operation":"unknown_baseline","name":"--json"})
822 )
823 .is_err()
824 );
825 }
826
827 #[test]
828 fn endpoint_resolution_anchors_only_relative_settings_to_each_caller() {
829 let a = Path::new("/workspace/a");
830 let b = Path::new("/workspace/b");
831 assert_ne!(
832 cache_socket(Path::new("cache"), None, a),
833 cache_socket(Path::new("cache"), None, b)
834 );
835 assert_eq!(
836 cache_socket(Path::new("/shared/cache"), None, a),
837 cache_socket(Path::new("/shared/cache"), None, b)
838 );
839 assert_eq!(
840 cache_socket(
841 Path::new("ignored"),
842 Some(Path::new("sockets/service.sock")),
843 a
844 ),
845 a.join("sockets/service.sock")
846 );
847 assert_eq!(
848 cache_socket(
849 Path::new("ignored"),
850 Some(Path::new("/explicit/service.sock")),
851 b
852 ),
853 Path::new("/explicit/service.sock")
854 );
855 assert_eq!(
856 cache_socket(Path::new("cache"), None, a),
857 default_cache_socket(&a.join("cache"))
858 );
859 }
860
861 #[cfg(unix)]
862 #[test]
863 fn endpoint_aliases_share_the_same_namespace_before_and_after_startup() {
864 use std::os::unix::fs::symlink;
865 let root = std::env::temp_dir().join(format!("sail-job-socket-{}", std::process::id()));
866 let canonical = root.join("actual");
867 assert!(std::fs::create_dir_all(&canonical).is_ok());
868 let canonical = canonical
869 .canonicalize()
870 .unwrap_or_else(|e| unreachable!("{e}"));
871 let alias = root.join("alias");
872 assert!(symlink(&canonical, &alias).is_ok());
873 let endpoint = canonical.join("nested/cache.sock");
874 assert_eq!(
875 socket_path(&endpoint),
876 socket_path(&alias.join("nested/cache.sock"))
877 );
878 assert!(std::fs::create_dir_all(endpoint.parent().unwrap_or(&canonical)).is_ok());
879 let current = std::env::current_dir().unwrap_or_else(|e| unreachable!("{e}"));
880 let relative = PathBuf::from("../".repeat(current.components().count().saturating_sub(1)))
881 .join(endpoint.strip_prefix("/").unwrap_or(&endpoint));
882 assert_eq!(socket_path(&endpoint), socket_path(&relative));
883 let listener = std::os::unix::net::UnixListener::bind(&endpoint)
884 .unwrap_or_else(|e| unreachable!("{e}"));
885 let socket_alias = root.join("cache-alias.sock");
886 assert!(symlink(&endpoint, &socket_alias).is_ok());
887 assert_eq!(socket_path(&endpoint), socket_path(&socket_alias));
888 let hash = sail_key::sha256(endpoint.as_os_str().as_encoded_bytes());
889 let suffix = hash.iter().take(4).fold(String::new(), |mut s, b| {
890 let _ = write!(s, "{b:02x}");
891 s
892 });
893 assert_eq!(
894 socket_path(&endpoint),
895 endpoint.with_file_name(format!("jobs-v1-proof-v1-{suffix}.sock"))
896 );
897 drop(listener);
898 let _ = std::fs::remove_dir_all(root);
899 }
900 #[cfg(unix)]
903 #[test]
904 fn long_cache_paths_get_a_short_private_socket() {
905 use std::os::unix::fs::MetadataExt as _;
906 let short = Path::new("/tmp/c");
907 assert_eq!(
908 default_cache_socket(short),
909 short.join(format!(
910 "daemon-v{}-workspace-v2-proof-v1.sock",
911 crate::protocol::PROTOCOL_VERSION
912 ))
913 );
914 let deep = Path::new("/nonexistent").join("d".repeat(120));
915 let socket = default_cache_socket(&deep);
916 assert!(socket.starts_with("/tmp"), "{}", socket.display());
917 assert!(socket_fits(&socket));
918 assert_eq!(socket, default_cache_socket(&deep), "deterministic");
919 let directory = socket.parent().unwrap_or(Path::new("/"));
920 let mode = std::fs::metadata(directory).map(|m| m.mode() & 0o777);
921 assert!(matches!(mode, Ok(0o700)), "{mode:?}");
922 assert_ne!(
923 socket,
924 default_cache_socket(&Path::new("/nonexistent").join("e".repeat(120))),
925 "one directory per cache"
926 );
927 assert!(
929 std::fs::set_permissions(
930 directory,
931 std::os::unix::fs::PermissionsExt::from_mode(0o755)
932 )
933 .is_ok()
934 );
935 assert!(!default_cache_socket(&deep).starts_with("/tmp"));
936 let _ = std::fs::remove_dir_all(directory);
937 }
938
939 #[test]
940 fn versions_and_size_are_checked() {
941 let mut bytes = Vec::new();
942 assert!(write_frame(&mut bytes, &Request::List { project_dir: None }).is_ok());
943 assert!(matches!(
944 read_frame::<Request>(&mut bytes.as_slice()),
945 Ok(Request::List { .. })
946 ));
947 let huge = u32::MAX.to_be_bytes();
948 assert!(read_frame::<Request>(&mut huge.as_slice()).is_err());
949 let body = br#"{"version":2,"body":{"operation":"list","project_dir":null}}"#;
950 let mut wrong = u32::try_from(body.len())
951 .unwrap_or(0)
952 .to_be_bytes()
953 .to_vec();
954 wrong.extend_from_slice(body);
955 assert!(read_frame::<Request>(&mut wrong.as_slice()).is_err());
956 }
957}