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 CAPABILITIES_VERSION: u32 = 2;
20pub const MAX_FRAME: usize = 32 * 1024 * 1024;
22
23#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
25pub struct Submission {
26 #[serde(default)]
28 pub mode: Mode,
29 pub project_dir: PathBuf,
31 pub args: Vec<String>,
33 pub force: bool,
35 pub environment: BTreeMap<String, String>,
37 pub input_revision: Option<String>,
39}
40
41#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
43#[serde(tag = "kind", content = "selection", rename_all = "snake_case")]
44pub enum Mode {
45 #[default]
47 Stock,
48 Standalone,
50 StandaloneRepair {
52 function: String,
54 },
55 Interactive,
57 Repair(crate::repair::Selection),
59}
60
61#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
63#[serde(rename_all = "snake_case")]
64pub enum Lifecycle {
65 Queued,
67 Running,
69 Completed,
71 Cancelled,
73 Superseded,
75 InfrastructureError,
77}
78impl Lifecycle {
79 #[must_use]
81 pub const fn terminal(self) -> bool {
82 !matches!(self, Self::Queued | Self::Running)
83 }
84}
85
86#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
88#[serde(rename_all = "snake_case")]
89pub enum Currentness {
90 Current,
92 Historical,
94 Unknown,
96}
97
98#[derive(Debug, Clone, Serialize, Deserialize)]
100pub struct Status {
101 pub version: u32,
103 pub id: String,
105 pub project_dir: PathBuf,
107 pub args: Vec<String>,
109 pub state: Lifecycle,
111 pub submitted_at_ms: u64,
113 pub started_at_ms: Option<u64>,
115 pub finished_at_ms: Option<u64>,
117 pub exit_code: Option<i32>,
119 pub input_revision: Option<String>,
121 pub currentness: Currentness,
123 pub error: Option<String>,
125}
126
127pub const RETIRED_NEUTRAL_RECORD: &str = "SAIL3161: this record was written by a neutral source job, which Sail 0.3.0 removed; it cannot be read as verification evidence";
131
132#[derive(Deserialize)]
136struct ResultDocumentWire {
137 #[serde(default)]
138 contracts: Option<serde::de::IgnoredAny>,
139 #[serde(default)]
140 repair: Option<Box<crate::repair::ResultDocument>>,
141 job: Status,
142 result: Option<Value>,
143}
144impl TryFrom<ResultDocumentWire> for ResultDocument {
145 type Error = &'static str;
146 fn try_from(wire: ResultDocumentWire) -> Result<Self, Self::Error> {
147 if wire.contracts.is_some() {
148 return Err(RETIRED_NEUTRAL_RECORD);
149 }
150 Ok(Self {
151 repair: wire.repair,
152 job: wire.job,
153 result: wire.result,
154 })
155 }
156}
157
158#[derive(Debug, Clone, Serialize, Deserialize)]
160#[serde(try_from = "ResultDocumentWire")]
161pub struct ResultDocument {
162 #[serde(default, skip_serializing_if = "Option::is_none")]
164 pub repair: Option<Box<crate::repair::ResultDocument>>,
165 pub job: Status,
167 pub result: Option<Value>,
169}
170
171#[derive(Debug, Clone, Serialize, Deserialize)]
173pub struct Chunk {
174 pub next: u64,
176 pub text: String,
178 pub complete: bool,
180}
181
182#[derive(Debug, Clone, Serialize, Deserialize)]
184#[serde(tag = "operation", rename_all = "snake_case")]
185pub enum Request {
186 PreparationStatus,
188 Prepare(crate::preparation::Submission),
190 Foreground {
192 version: u32,
194 project_dir: PathBuf,
196 args: Vec<String>,
198 },
199 Capabilities,
201 SubmitAttributed {
203 submission: Submission,
205 requirements: Vec<crate::attribution::RequirementAttribution>,
207 },
208 AttributedAssurance {
210 id: String,
212 },
213 ProofEvents {
215 id: String,
217 cursor: crate::proof::Cursor,
219 limit: usize,
221 },
222 Explain {
224 id: String,
226 target: crate::proof::Target,
228 function: String,
230 obligation: Option<String>,
232 },
233 SaveBaseline {
235 id: String,
237 name: String,
239 },
240 Baselines,
242 GetBaseline {
244 name: String,
246 },
247 Compare {
249 before: crate::evidence::Reference,
251 after: String,
253 },
254 Submit {
256 submission: Submission,
258 },
259 List {
261 project_dir: Option<PathBuf>,
263 },
264 Status {
266 id: String,
268 },
269 Result {
271 id: String,
273 },
274 Cancel {
276 id: String,
278 superseded: bool,
280 },
281 Logs {
283 id: String,
285 offset: u64,
287 },
288 Events {
290 id: String,
292 offset: u64,
294 },
295}
296
297#[derive(Debug, Clone, Serialize, Deserialize)]
299#[serde(tag = "response", content = "value", rename_all = "snake_case")]
300pub enum Response {
301 Preparation(crate::preparation::Status),
303 Capabilities {
305 #[serde(default = "legacy_capabilities")]
307 capabilities_version: u32,
308 proof_version: u32,
310 #[serde(default, skip_serializing_if = "Option::is_none")]
312 attribution_version: Option<u32>,
313 #[serde(default)]
316 repair: bool,
317 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
319 standalone: bool,
320 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
322 standalone_repair: bool,
323 },
324 ProofEvents(crate::proof::Page),
326 Explanation(Box<crate::evidence::Explanation>),
328 AttributedAssurance(Box<crate::attribution::View>),
330 Baseline(Box<crate::evidence::Baseline>),
332 Baselines(Vec<String>),
334 Comparison(crate::evidence::Comparison),
336 Status(Status),
338 List(Vec<Status>),
340 Result(ResultDocument),
342 Chunk(Chunk),
344 Error(String),
346}
347
348#[derive(Serialize, Deserialize)]
349struct Envelope<T> {
350 version: u32,
351 body: T,
352}
353
354const fn legacy_capabilities() -> u32 {
355 1
356}
357
358pub fn write_frame<T: Serialize>(writer: &mut impl Write, body: &T) -> io::Result<()> {
363 let bytes = serde_json::to_vec(&Envelope {
364 version: VERSION,
365 body,
366 })
367 .map_err(io::Error::other)?;
368 if bytes.len() > MAX_FRAME {
369 return Err(io::Error::other("SAIL0802: job frame exceeds limit"));
370 }
371 let size = u32::try_from(bytes.len()).map_err(io::Error::other)?;
372 writer.write_all(&size.to_be_bytes())?;
373 writer.write_all(&bytes)?;
374 writer.flush()
375}
376
377pub fn read_frame<T: serde::de::DeserializeOwned>(reader: &mut impl Read) -> io::Result<T> {
382 let mut length = [0; 4];
383 reader.read_exact(&mut length)?;
384 let size = usize::try_from(u32::from_be_bytes(length)).map_err(io::Error::other)?;
385 if size > MAX_FRAME {
386 return Err(io::Error::other("SAIL0802: job frame exceeds limit"));
387 }
388 let mut bytes = vec![0; size];
389 reader.read_exact(&mut bytes)?;
390 let envelope: Envelope<T> = serde_json::from_slice(&bytes).map_err(io::Error::other)?;
391 if envelope.version != VERSION {
392 return Err(io::Error::other("SAIL0802: incompatible job protocol"));
393 }
394 Ok(envelope.body)
395}
396
397pub fn cache_directory() -> io::Result<PathBuf> {
402 let var = |name: &str| std::env::var_os(name).filter(|value| !value.is_empty());
403 var("SAIL_CACHE_DIR")
404 .map(PathBuf::from)
405 .or_else(|| var("XDG_CACHE_HOME").map(|root| PathBuf::from(root).join("sail")))
406 .or_else(|| var("HOME").map(|root| PathBuf::from(root).join(".cache/sail")))
407 .ok_or_else(|| {
408 io::Error::other(
409 "error[SAIL3001]: none of SAIL_CACHE_DIR, XDG_CACHE_HOME or HOME is set",
410 )
411 })
412}
413
414pub const MAX_SOCKET_PATH: usize = if cfg!(target_os = "linux") { 107 } else { 103 };
418
419#[must_use]
430pub fn default_cache_socket(cache: &Path) -> PathBuf {
431 let socket = cache.join(format!(
432 "daemon-v{}-workspace-v2-proof-v1.sock",
433 crate::protocol::PROTOCOL_VERSION
434 ));
435 if socket_fits(&socket) {
436 return socket;
437 }
438 short_socket(&socket).unwrap_or(socket)
439}
440
441#[must_use]
443pub fn socket_fits(cache_socket: &Path) -> bool {
444 let absolute = std::path::absolute(cache_socket).unwrap_or_else(|_| cache_socket.to_owned());
445 absolute.as_os_str().len() <= MAX_SOCKET_PATH
446 && socket_path(cache_socket).as_os_str().len() <= MAX_SOCKET_PATH
447}
448
449#[cfg(unix)]
450fn short_socket(socket: &Path) -> Option<PathBuf> {
451 use std::os::unix::fs::{DirBuilderExt as _, MetadataExt as _};
452 let name = socket.file_name()?;
453 let digest = sail_key::sha256(endpoint_path(socket).as_os_str().as_encoded_bytes());
454 let hash = digest
455 .iter()
456 .take(8)
457 .fold(String::new(), |mut value, byte| {
458 let _ = write!(value, "{byte:02x}");
459 value
460 });
461 let directory = Path::new("/tmp").join(format!("sail-{hash}"));
462 let _ = std::fs::DirBuilder::new().mode(0o700).create(&directory);
464 let metadata = std::fs::symlink_metadata(&directory).ok()?;
465 if !metadata.is_dir() || metadata.mode() & 0o077 != 0 {
466 return None;
467 }
468 let probe = directory.join(format!(".probe-{}", std::process::id()));
471 std::fs::File::create(&probe).ok()?;
472 std::fs::remove_file(&probe).ok()?;
473 let short = directory.join(name);
474 socket_fits(&short).then_some(short)
475}
476
477#[cfg(not(unix))]
478fn short_socket(_socket: &Path) -> Option<PathBuf> {
479 None
480}
481
482#[must_use]
485pub fn cache_socket(cache: &Path, explicit: Option<&Path>, cwd: &Path) -> PathBuf {
486 let socket = explicit.map_or_else(|| default_cache_socket(&cwd.join(cache)), Path::to_path_buf);
488 if socket.is_absolute() {
489 socket
490 } else {
491 cwd.join(socket)
492 }
493}
494
495pub fn configured_socket(cwd: &Path) -> io::Result<PathBuf> {
500 let explicit = std::env::var_os("SAIL_DAEMON_SOCKET")
501 .filter(|value| !value.is_empty())
502 .map(PathBuf::from);
503 Ok(socket_path(&cache_socket(
504 &cache_directory()?,
505 explicit.as_deref(),
506 cwd,
507 )))
508}
509
510#[must_use]
513pub fn socket_path(cache_socket: &Path) -> PathBuf {
514 let cache_socket = endpoint_path(cache_socket);
515 let digest = sail_key::sha256(cache_socket.as_os_str().as_encoded_bytes());
516 let suffix = digest
517 .iter()
518 .take(4)
519 .fold(String::new(), |mut value, byte| {
520 let _ = write!(value, "{byte:02x}");
521 value
522 });
523 cache_socket.with_file_name(format!("jobs-v1-proof-v1-{suffix}.sock"))
524}
525
526fn endpoint_path(path: &Path) -> PathBuf {
527 let absolute = std::path::absolute(path).unwrap_or_else(|_| path.to_owned());
528 for ancestor in absolute.ancestors() {
532 if let Ok(resolved) = ancestor.canonicalize()
533 && let Ok(suffix) = absolute.strip_prefix(ancestor)
534 {
535 return if suffix.as_os_str().is_empty() {
536 resolved
537 } else {
538 resolved.join(suffix)
539 };
540 }
541 }
542 absolute
543}
544
545#[cfg(unix)]
547#[derive(Debug, Clone)]
548pub struct Client {
549 socket: PathBuf,
550}
551#[cfg(unix)]
552impl Client {
553 pub fn submit_attributed(
560 &self,
561 submission: Submission,
562 requirements: Vec<crate::attribution::RequirementAttribution>,
563 ) -> io::Result<Status> {
564 let requirements = crate::attribution::canonical(requirements).map_err(io::Error::other)?;
565 if !crate::attribution::mode_supported(&submission.mode) {
566 return Err(io::Error::other(
567 "SAIL3160: requirement attribution applies only to stock and standalone jobs",
568 ));
569 }
570 self.require_attribution()?;
571 match self.call(&Request::SubmitAttributed {
572 submission,
573 requirements,
574 })? {
575 Response::Status(status) => Ok(status),
576 Response::Error(message) => Err(io::Error::other(message)),
577 _ => Err(io::Error::other(
578 "SAIL3160: unexpected attributed submission response",
579 )),
580 }
581 }
582
583 pub fn attributed_assurance(&self, id: &str) -> io::Result<crate::attribution::View> {
589 if id.is_empty() || id.len() > 256 || id.contains('\0') {
590 return Err(io::Error::other("SAIL3160: invalid assurance job identity"));
591 }
592 self.require_attribution()?;
593 match self.call(&Request::AttributedAssurance { id: id.into() })? {
594 Response::AttributedAssurance(view)
595 if view.version == crate::attribution::VERSION && view.job_id == id =>
596 {
597 Ok(*view)
598 }
599 Response::Error(message) => Err(io::Error::other(message)),
600 _ => Err(io::Error::other(
601 "SAIL3160: invalid attributed assurance response",
602 )),
603 }
604 }
605
606 fn require_attribution(&self) -> io::Result<()> {
607 if matches!(
608 self.call(&Request::Capabilities)?,
609 Response::Capabilities {
610 attribution_version: Some(crate::attribution::VERSION),
611 ..
612 }
613 ) {
614 Ok(())
615 } else {
616 Err(io::Error::other(
617 "SAIL3160: endpoint does not support requirement attribution; restart Sail's daemon",
618 ))
619 }
620 }
621
622 #[must_use]
624 pub fn new(socket: impl Into<PathBuf>) -> Self {
625 Self {
626 socket: socket.into(),
627 }
628 }
629 pub fn call(&self, request: &Request) -> io::Result<Response> {
634 self.call_with(request, |_| {})
635 }
636 pub fn call_with(
643 &self,
644 request: &Request,
645 connected: impl FnOnce(std::os::unix::net::UnixStream),
646 ) -> io::Result<Response> {
647 if matches!(request, Request::Submit { submission } if matches!(submission.mode, Mode::Interactive | Mode::Repair(_)))
648 && !matches!(
649 self.call(&Request::Capabilities)?,
650 Response::Capabilities {
651 proof_version: crate::proof::VERSION,
652 repair: true,
653 ..
654 }
655 )
656 {
657 return Err(io::Error::other(
658 "SAIL0903: endpoint does not support proof/repair contracts",
659 ));
660 }
661 if matches!(request, Request::Submit { submission } if submission.mode == Mode::Standalone)
662 && !matches!(
663 self.call(&Request::Capabilities)?,
664 Response::Capabilities {
665 standalone: true,
666 ..
667 }
668 )
669 {
670 return Err(io::Error::other(
671 "SAIL3150: endpoint does not support standalone file jobs; restart Sail's daemon",
672 ));
673 }
674 if matches!(request, Request::Submit { submission } if matches!(submission.mode, Mode::StandaloneRepair { .. }))
675 && !matches!(
676 self.call(&Request::Capabilities)?,
677 Response::Capabilities {
678 proof_version: crate::proof::VERSION,
679 repair: true,
680 standalone_repair: true,
681 ..
682 }
683 )
684 {
685 return Err(io::Error::other(
686 "SAIL3150: endpoint does not support standalone repair; restart Sail's daemon",
687 ));
688 }
689 let mut stream =
690 crate::client::connect_stream(&self.socket, std::time::Duration::from_secs(5))?;
691 connected(stream.try_clone()?);
692 write_frame(&mut stream, request)?;
693 match read_frame(&mut stream)? {
694 Response::Error(message) => Err(io::Error::other(message)),
695 response => Ok(response),
696 }
697 }
698}
699
700#[cfg(test)]
701mod tests {
702 use super::*;
703 #[test]
704 fn baseline_read_has_exact_additive_wire_identity() {
705 let request = Request::GetBaseline {
706 name: "--json".into(),
707 };
708 assert_eq!(
709 serde_json::to_value(&request).unwrap_or_else(|error| unreachable!("{error}")),
710 serde_json::json!({"operation":"get_baseline","name":"--json"})
711 );
712 let mut bytes = Vec::new();
713 assert!(write_frame(&mut bytes, &request).is_ok());
714 assert!(matches!(read_frame::<Request>(&mut bytes.as_slice()),
715 Ok(Request::GetBaseline { name }) if name == "--json"));
716 assert!(
717 serde_json::from_value::<Request>(
718 serde_json::json!({"operation":"unknown_baseline","name":"--json"})
719 )
720 .is_err()
721 );
722 }
723
724 #[test]
725 fn endpoint_resolution_anchors_only_relative_settings_to_each_caller() {
726 let a = Path::new("/workspace/a");
727 let b = Path::new("/workspace/b");
728 assert_ne!(
729 cache_socket(Path::new("cache"), None, a),
730 cache_socket(Path::new("cache"), None, b)
731 );
732 assert_eq!(
733 cache_socket(Path::new("/shared/cache"), None, a),
734 cache_socket(Path::new("/shared/cache"), None, b)
735 );
736 assert_eq!(
737 cache_socket(
738 Path::new("ignored"),
739 Some(Path::new("sockets/service.sock")),
740 a
741 ),
742 a.join("sockets/service.sock")
743 );
744 assert_eq!(
745 cache_socket(
746 Path::new("ignored"),
747 Some(Path::new("/explicit/service.sock")),
748 b
749 ),
750 Path::new("/explicit/service.sock")
751 );
752 assert_eq!(
753 cache_socket(Path::new("cache"), None, a),
754 default_cache_socket(&a.join("cache"))
755 );
756 }
757
758 #[cfg(unix)]
759 #[test]
760 fn endpoint_aliases_share_the_same_namespace_before_and_after_startup() {
761 use std::os::unix::fs::symlink;
762 let root = std::env::temp_dir().join(format!("sail-job-socket-{}", std::process::id()));
763 let canonical = root.join("actual");
764 assert!(std::fs::create_dir_all(&canonical).is_ok());
765 let canonical = canonical
766 .canonicalize()
767 .unwrap_or_else(|e| unreachable!("{e}"));
768 let alias = root.join("alias");
769 assert!(symlink(&canonical, &alias).is_ok());
770 let endpoint = canonical.join("nested/cache.sock");
771 assert_eq!(
772 socket_path(&endpoint),
773 socket_path(&alias.join("nested/cache.sock"))
774 );
775 assert!(std::fs::create_dir_all(endpoint.parent().unwrap_or(&canonical)).is_ok());
776 let current = std::env::current_dir().unwrap_or_else(|e| unreachable!("{e}"));
777 let relative = PathBuf::from("../".repeat(current.components().count().saturating_sub(1)))
778 .join(endpoint.strip_prefix("/").unwrap_or(&endpoint));
779 assert_eq!(socket_path(&endpoint), socket_path(&relative));
780 let listener = std::os::unix::net::UnixListener::bind(&endpoint)
781 .unwrap_or_else(|e| unreachable!("{e}"));
782 let socket_alias = root.join("cache-alias.sock");
783 assert!(symlink(&endpoint, &socket_alias).is_ok());
784 assert_eq!(socket_path(&endpoint), socket_path(&socket_alias));
785 let hash = sail_key::sha256(endpoint.as_os_str().as_encoded_bytes());
786 let suffix = hash.iter().take(4).fold(String::new(), |mut s, b| {
787 let _ = write!(s, "{b:02x}");
788 s
789 });
790 assert_eq!(
791 socket_path(&endpoint),
792 endpoint.with_file_name(format!("jobs-v1-proof-v1-{suffix}.sock"))
793 );
794 drop(listener);
795 let _ = std::fs::remove_dir_all(root);
796 }
797 #[cfg(unix)]
800 #[test]
801 fn long_cache_paths_get_a_short_private_socket() {
802 use std::os::unix::fs::MetadataExt as _;
803 let short = Path::new("/tmp/c");
804 assert_eq!(
805 default_cache_socket(short),
806 short.join(format!(
807 "daemon-v{}-workspace-v2-proof-v1.sock",
808 crate::protocol::PROTOCOL_VERSION
809 ))
810 );
811 let deep = Path::new("/nonexistent").join("d".repeat(120));
812 let socket = default_cache_socket(&deep);
813 assert!(socket.starts_with("/tmp"), "{}", socket.display());
814 assert!(socket_fits(&socket));
815 assert_eq!(socket, default_cache_socket(&deep), "deterministic");
816 let directory = socket.parent().unwrap_or(Path::new("/"));
817 let mode = std::fs::metadata(directory).map(|m| m.mode() & 0o777);
818 assert!(matches!(mode, Ok(0o700)), "{mode:?}");
819 assert_ne!(
820 socket,
821 default_cache_socket(&Path::new("/nonexistent").join("e".repeat(120))),
822 "one directory per cache"
823 );
824 assert!(
826 std::fs::set_permissions(
827 directory,
828 std::os::unix::fs::PermissionsExt::from_mode(0o755)
829 )
830 .is_ok()
831 );
832 assert!(!default_cache_socket(&deep).starts_with("/tmp"));
833 let _ = std::fs::remove_dir_all(directory);
834 }
835
836 #[test]
837 fn versions_and_size_are_checked() {
838 let mut bytes = Vec::new();
839 assert!(write_frame(&mut bytes, &Request::List { project_dir: None }).is_ok());
840 assert!(matches!(
841 read_frame::<Request>(&mut bytes.as_slice()),
842 Ok(Request::List { .. })
843 ));
844 let huge = u32::MAX.to_be_bytes();
845 assert!(read_frame::<Request>(&mut huge.as_slice()).is_err());
846 let body = br#"{"version":2,"body":{"operation":"list","project_dir":null}}"#;
847 let mut wrong = u32::try_from(body.len())
848 .unwrap_or(0)
849 .to_be_bytes()
850 .to_vec();
851 wrong.extend_from_slice(body);
852 assert!(read_frame::<Request>(&mut wrong.as_slice()).is_err());
853 }
854}