use std::collections::BTreeMap;
use std::fmt::Write as _;
use std::io::{self, Read, Write};
use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
use serde_json::Value;
pub const VERSION: u32 = 1;
pub const CAPABILITIES_VERSION: u32 = 2;
pub const MAX_FRAME: usize = 32 * 1024 * 1024;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Submission {
#[serde(default)]
pub mode: Mode,
pub project_dir: PathBuf,
pub args: Vec<String>,
pub force: bool,
pub environment: BTreeMap<String, String>,
pub input_revision: Option<String>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", content = "selection", rename_all = "snake_case")]
pub enum Mode {
#[default]
Stock,
Standalone,
StandaloneRepair {
function: String,
},
Interactive,
Repair(crate::repair::Selection),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Lifecycle {
Queued,
Running,
Completed,
Cancelled,
Superseded,
InfrastructureError,
}
impl Lifecycle {
#[must_use]
pub const fn terminal(self) -> bool {
!matches!(self, Self::Queued | Self::Running)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Currentness {
Current,
Historical,
Unknown,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Status {
pub version: u32,
pub id: String,
pub project_dir: PathBuf,
pub args: Vec<String>,
pub state: Lifecycle,
pub submitted_at_ms: u64,
pub started_at_ms: Option<u64>,
pub finished_at_ms: Option<u64>,
pub exit_code: Option<i32>,
pub input_revision: Option<String>,
pub currentness: Currentness,
pub error: Option<String>,
}
pub 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";
#[derive(Deserialize)]
struct ResultDocumentWire {
#[serde(default)]
contracts: Option<serde::de::IgnoredAny>,
#[serde(default)]
repair: Option<Box<crate::repair::ResultDocument>>,
job: Status,
result: Option<Value>,
}
impl TryFrom<ResultDocumentWire> for ResultDocument {
type Error = &'static str;
fn try_from(wire: ResultDocumentWire) -> Result<Self, Self::Error> {
if wire.contracts.is_some() {
return Err(RETIRED_NEUTRAL_RECORD);
}
Ok(Self {
repair: wire.repair,
job: wire.job,
result: wire.result,
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(try_from = "ResultDocumentWire")]
pub struct ResultDocument {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub repair: Option<Box<crate::repair::ResultDocument>>,
pub job: Status,
pub result: Option<Value>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Chunk {
pub next: u64,
pub text: String,
pub complete: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "operation", rename_all = "snake_case")]
pub enum Request {
PreparationStatus,
Prepare(crate::preparation::Submission),
Foreground {
version: u32,
project_dir: PathBuf,
args: Vec<String>,
},
Capabilities,
SubmitAttributed {
submission: Submission,
requirements: Vec<crate::attribution::RequirementAttribution>,
},
AttributedAssurance {
id: String,
},
ProofEvents {
id: String,
cursor: crate::proof::Cursor,
limit: usize,
},
Explain {
id: String,
target: crate::proof::Target,
function: String,
obligation: Option<String>,
},
SaveBaseline {
id: String,
name: String,
},
Baselines,
GetBaseline {
name: String,
},
Compare {
before: crate::evidence::Reference,
after: String,
},
Submit {
submission: Submission,
},
List {
project_dir: Option<PathBuf>,
},
Status {
id: String,
},
Result {
id: String,
},
Cancel {
id: String,
superseded: bool,
},
Logs {
id: String,
offset: u64,
},
Events {
id: String,
offset: u64,
},
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "response", content = "value", rename_all = "snake_case")]
pub enum Response {
Preparation(crate::preparation::Status),
Capabilities {
#[serde(default = "legacy_capabilities")]
capabilities_version: u32,
proof_version: u32,
#[serde(default, skip_serializing_if = "Option::is_none")]
attribution_version: Option<u32>,
#[serde(default)]
repair: bool,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
standalone: bool,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
standalone_repair: bool,
},
ProofEvents(crate::proof::Page),
Explanation(Box<crate::evidence::Explanation>),
AttributedAssurance(Box<crate::attribution::View>),
Baseline(Box<crate::evidence::Baseline>),
Baselines(Vec<String>),
Comparison(crate::evidence::Comparison),
Status(Status),
List(Vec<Status>),
Result(ResultDocument),
Chunk(Chunk),
Error(String),
}
#[derive(Serialize, Deserialize)]
struct Envelope<T> {
version: u32,
body: T,
}
const fn legacy_capabilities() -> u32 {
1
}
pub fn write_frame<T: Serialize>(writer: &mut impl Write, body: &T) -> io::Result<()> {
let bytes = serde_json::to_vec(&Envelope {
version: VERSION,
body,
})
.map_err(io::Error::other)?;
if bytes.len() > MAX_FRAME {
return Err(io::Error::other("SAIL0802: job frame exceeds limit"));
}
let size = u32::try_from(bytes.len()).map_err(io::Error::other)?;
writer.write_all(&size.to_be_bytes())?;
writer.write_all(&bytes)?;
writer.flush()
}
pub fn read_frame<T: serde::de::DeserializeOwned>(reader: &mut impl Read) -> io::Result<T> {
let mut length = [0; 4];
reader.read_exact(&mut length)?;
let size = usize::try_from(u32::from_be_bytes(length)).map_err(io::Error::other)?;
if size > MAX_FRAME {
return Err(io::Error::other("SAIL0802: job frame exceeds limit"));
}
let mut bytes = vec![0; size];
reader.read_exact(&mut bytes)?;
let envelope: Envelope<T> = serde_json::from_slice(&bytes).map_err(io::Error::other)?;
if envelope.version != VERSION {
return Err(io::Error::other("SAIL0802: incompatible job protocol"));
}
Ok(envelope.body)
}
pub fn cache_directory() -> io::Result<PathBuf> {
let var = |name: &str| std::env::var_os(name).filter(|value| !value.is_empty());
var("SAIL_CACHE_DIR")
.map(PathBuf::from)
.or_else(|| var("XDG_CACHE_HOME").map(|root| PathBuf::from(root).join("sail")))
.or_else(|| var("HOME").map(|root| PathBuf::from(root).join(".cache/sail")))
.ok_or_else(|| {
io::Error::other(
"error[SAIL3001]: none of SAIL_CACHE_DIR, XDG_CACHE_HOME or HOME is set",
)
})
}
pub const MAX_SOCKET_PATH: usize = if cfg!(target_os = "linux") { 107 } else { 103 };
#[must_use]
pub fn default_cache_socket(cache: &Path) -> PathBuf {
let socket = cache.join(format!(
"daemon-v{}-workspace-v2-proof-v1.sock",
crate::protocol::PROTOCOL_VERSION
));
if socket_fits(&socket) {
return socket;
}
short_socket(&socket).unwrap_or(socket)
}
#[must_use]
pub fn socket_fits(cache_socket: &Path) -> bool {
let absolute = std::path::absolute(cache_socket).unwrap_or_else(|_| cache_socket.to_owned());
absolute.as_os_str().len() <= MAX_SOCKET_PATH
&& socket_path(cache_socket).as_os_str().len() <= MAX_SOCKET_PATH
}
#[cfg(unix)]
fn short_socket(socket: &Path) -> Option<PathBuf> {
use std::os::unix::fs::{DirBuilderExt as _, MetadataExt as _};
let name = socket.file_name()?;
let digest = sail_key::sha256(endpoint_path(socket).as_os_str().as_encoded_bytes());
let hash = digest
.iter()
.take(8)
.fold(String::new(), |mut value, byte| {
let _ = write!(value, "{byte:02x}");
value
});
let directory = Path::new("/tmp").join(format!("sail-{hash}"));
let _ = std::fs::DirBuilder::new().mode(0o700).create(&directory);
let metadata = std::fs::symlink_metadata(&directory).ok()?;
if !metadata.is_dir() || metadata.mode() & 0o077 != 0 {
return None;
}
let probe = directory.join(format!(".probe-{}", std::process::id()));
std::fs::File::create(&probe).ok()?;
std::fs::remove_file(&probe).ok()?;
let short = directory.join(name);
socket_fits(&short).then_some(short)
}
#[cfg(not(unix))]
fn short_socket(_socket: &Path) -> Option<PathBuf> {
None
}
#[must_use]
pub fn cache_socket(cache: &Path, explicit: Option<&Path>, cwd: &Path) -> PathBuf {
let socket = explicit.map_or_else(|| default_cache_socket(&cwd.join(cache)), Path::to_path_buf);
if socket.is_absolute() {
socket
} else {
cwd.join(socket)
}
}
pub fn configured_socket(cwd: &Path) -> io::Result<PathBuf> {
let explicit = std::env::var_os("SAIL_DAEMON_SOCKET")
.filter(|value| !value.is_empty())
.map(PathBuf::from);
Ok(socket_path(&cache_socket(
&cache_directory()?,
explicit.as_deref(),
cwd,
)))
}
#[must_use]
pub fn socket_path(cache_socket: &Path) -> PathBuf {
let cache_socket = endpoint_path(cache_socket);
let digest = sail_key::sha256(cache_socket.as_os_str().as_encoded_bytes());
let suffix = digest
.iter()
.take(4)
.fold(String::new(), |mut value, byte| {
let _ = write!(value, "{byte:02x}");
value
});
cache_socket.with_file_name(format!("jobs-v1-proof-v1-{suffix}.sock"))
}
fn endpoint_path(path: &Path) -> PathBuf {
let absolute = std::path::absolute(path).unwrap_or_else(|_| path.to_owned());
for ancestor in absolute.ancestors() {
if let Ok(resolved) = ancestor.canonicalize()
&& let Ok(suffix) = absolute.strip_prefix(ancestor)
{
return if suffix.as_os_str().is_empty() {
resolved
} else {
resolved.join(suffix)
};
}
}
absolute
}
#[cfg(unix)]
#[derive(Debug, Clone)]
pub struct Client {
socket: PathBuf,
}
#[cfg(unix)]
impl Client {
pub fn submit_attributed(
&self,
submission: Submission,
requirements: Vec<crate::attribution::RequirementAttribution>,
) -> io::Result<Status> {
let requirements = crate::attribution::canonical(requirements).map_err(io::Error::other)?;
if !crate::attribution::mode_supported(&submission.mode) {
return Err(io::Error::other(
"SAIL3160: requirement attribution applies only to stock and standalone jobs",
));
}
self.require_attribution()?;
match self.call(&Request::SubmitAttributed {
submission,
requirements,
})? {
Response::Status(status) => Ok(status),
Response::Error(message) => Err(io::Error::other(message)),
_ => Err(io::Error::other(
"SAIL3160: unexpected attributed submission response",
)),
}
}
pub fn attributed_assurance(&self, id: &str) -> io::Result<crate::attribution::View> {
if id.is_empty() || id.len() > 256 || id.contains('\0') {
return Err(io::Error::other("SAIL3160: invalid assurance job identity"));
}
self.require_attribution()?;
match self.call(&Request::AttributedAssurance { id: id.into() })? {
Response::AttributedAssurance(view)
if view.version == crate::attribution::VERSION && view.job_id == id =>
{
Ok(*view)
}
Response::Error(message) => Err(io::Error::other(message)),
_ => Err(io::Error::other(
"SAIL3160: invalid attributed assurance response",
)),
}
}
fn require_attribution(&self) -> io::Result<()> {
if matches!(
self.call(&Request::Capabilities)?,
Response::Capabilities {
attribution_version: Some(crate::attribution::VERSION),
..
}
) {
Ok(())
} else {
Err(io::Error::other(
"SAIL3160: endpoint does not support requirement attribution; restart Sail's daemon",
))
}
}
#[must_use]
pub fn new(socket: impl Into<PathBuf>) -> Self {
Self {
socket: socket.into(),
}
}
pub fn call(&self, request: &Request) -> io::Result<Response> {
self.call_with(request, |_| {})
}
pub fn call_with(
&self,
request: &Request,
connected: impl FnOnce(std::os::unix::net::UnixStream),
) -> io::Result<Response> {
if matches!(request, Request::Submit { submission } if matches!(submission.mode, Mode::Interactive | Mode::Repair(_)))
&& !matches!(
self.call(&Request::Capabilities)?,
Response::Capabilities {
proof_version: crate::proof::VERSION,
repair: true,
..
}
)
{
return Err(io::Error::other(
"SAIL0903: endpoint does not support proof/repair contracts",
));
}
if matches!(request, Request::Submit { submission } if submission.mode == Mode::Standalone)
&& !matches!(
self.call(&Request::Capabilities)?,
Response::Capabilities {
standalone: true,
..
}
)
{
return Err(io::Error::other(
"SAIL3150: endpoint does not support standalone file jobs; restart Sail's daemon",
));
}
if matches!(request, Request::Submit { submission } if matches!(submission.mode, Mode::StandaloneRepair { .. }))
&& !matches!(
self.call(&Request::Capabilities)?,
Response::Capabilities {
proof_version: crate::proof::VERSION,
repair: true,
standalone_repair: true,
..
}
)
{
return Err(io::Error::other(
"SAIL3150: endpoint does not support standalone repair; restart Sail's daemon",
));
}
let mut stream =
crate::client::connect_stream(&self.socket, std::time::Duration::from_secs(5))?;
connected(stream.try_clone()?);
write_frame(&mut stream, request)?;
match read_frame(&mut stream)? {
Response::Error(message) => Err(io::Error::other(message)),
response => Ok(response),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn baseline_read_has_exact_additive_wire_identity() {
let request = Request::GetBaseline {
name: "--json".into(),
};
assert_eq!(
serde_json::to_value(&request).unwrap_or_else(|error| unreachable!("{error}")),
serde_json::json!({"operation":"get_baseline","name":"--json"})
);
let mut bytes = Vec::new();
assert!(write_frame(&mut bytes, &request).is_ok());
assert!(matches!(read_frame::<Request>(&mut bytes.as_slice()),
Ok(Request::GetBaseline { name }) if name == "--json"));
assert!(
serde_json::from_value::<Request>(
serde_json::json!({"operation":"unknown_baseline","name":"--json"})
)
.is_err()
);
}
#[test]
fn endpoint_resolution_anchors_only_relative_settings_to_each_caller() {
let a = Path::new("/workspace/a");
let b = Path::new("/workspace/b");
assert_ne!(
cache_socket(Path::new("cache"), None, a),
cache_socket(Path::new("cache"), None, b)
);
assert_eq!(
cache_socket(Path::new("/shared/cache"), None, a),
cache_socket(Path::new("/shared/cache"), None, b)
);
assert_eq!(
cache_socket(
Path::new("ignored"),
Some(Path::new("sockets/service.sock")),
a
),
a.join("sockets/service.sock")
);
assert_eq!(
cache_socket(
Path::new("ignored"),
Some(Path::new("/explicit/service.sock")),
b
),
Path::new("/explicit/service.sock")
);
assert_eq!(
cache_socket(Path::new("cache"), None, a),
default_cache_socket(&a.join("cache"))
);
}
#[cfg(unix)]
#[test]
fn endpoint_aliases_share_the_same_namespace_before_and_after_startup() {
use std::os::unix::fs::symlink;
let root = std::env::temp_dir().join(format!("sail-job-socket-{}", std::process::id()));
let canonical = root.join("actual");
assert!(std::fs::create_dir_all(&canonical).is_ok());
let canonical = canonical
.canonicalize()
.unwrap_or_else(|e| unreachable!("{e}"));
let alias = root.join("alias");
assert!(symlink(&canonical, &alias).is_ok());
let endpoint = canonical.join("nested/cache.sock");
assert_eq!(
socket_path(&endpoint),
socket_path(&alias.join("nested/cache.sock"))
);
assert!(std::fs::create_dir_all(endpoint.parent().unwrap_or(&canonical)).is_ok());
let current = std::env::current_dir().unwrap_or_else(|e| unreachable!("{e}"));
let relative = PathBuf::from("../".repeat(current.components().count().saturating_sub(1)))
.join(endpoint.strip_prefix("/").unwrap_or(&endpoint));
assert_eq!(socket_path(&endpoint), socket_path(&relative));
let listener = std::os::unix::net::UnixListener::bind(&endpoint)
.unwrap_or_else(|e| unreachable!("{e}"));
let socket_alias = root.join("cache-alias.sock");
assert!(symlink(&endpoint, &socket_alias).is_ok());
assert_eq!(socket_path(&endpoint), socket_path(&socket_alias));
let hash = sail_key::sha256(endpoint.as_os_str().as_encoded_bytes());
let suffix = hash.iter().take(4).fold(String::new(), |mut s, b| {
let _ = write!(s, "{b:02x}");
s
});
assert_eq!(
socket_path(&endpoint),
endpoint.with_file_name(format!("jobs-v1-proof-v1-{suffix}.sock"))
);
drop(listener);
let _ = std::fs::remove_dir_all(root);
}
#[cfg(unix)]
#[test]
fn long_cache_paths_get_a_short_private_socket() {
use std::os::unix::fs::MetadataExt as _;
let short = Path::new("/tmp/c");
assert_eq!(
default_cache_socket(short),
short.join(format!(
"daemon-v{}-workspace-v2-proof-v1.sock",
crate::protocol::PROTOCOL_VERSION
))
);
let deep = Path::new("/nonexistent").join("d".repeat(120));
let socket = default_cache_socket(&deep);
assert!(socket.starts_with("/tmp"), "{}", socket.display());
assert!(socket_fits(&socket));
assert_eq!(socket, default_cache_socket(&deep), "deterministic");
let directory = socket.parent().unwrap_or(Path::new("/"));
let mode = std::fs::metadata(directory).map(|m| m.mode() & 0o777);
assert!(matches!(mode, Ok(0o700)), "{mode:?}");
assert_ne!(
socket,
default_cache_socket(&Path::new("/nonexistent").join("e".repeat(120))),
"one directory per cache"
);
assert!(
std::fs::set_permissions(
directory,
std::os::unix::fs::PermissionsExt::from_mode(0o755)
)
.is_ok()
);
assert!(!default_cache_socket(&deep).starts_with("/tmp"));
let _ = std::fs::remove_dir_all(directory);
}
#[test]
fn versions_and_size_are_checked() {
let mut bytes = Vec::new();
assert!(write_frame(&mut bytes, &Request::List { project_dir: None }).is_ok());
assert!(matches!(
read_frame::<Request>(&mut bytes.as_slice()),
Ok(Request::List { .. })
));
let huge = u32::MAX.to_be_bytes();
assert!(read_frame::<Request>(&mut huge.as_slice()).is_err());
let body = br#"{"version":2,"body":{"operation":"list","project_dir":null}}"#;
let mut wrong = u32::try_from(body.len())
.unwrap_or(0)
.to_be_bytes()
.to_vec();
wrong.extend_from_slice(body);
assert!(read_frame::<Request>(&mut wrong.as_slice()).is_err());
}
}