1use std::collections::BTreeMap;
30use std::io::{Read as _, Write as _};
31use std::path::{Path, PathBuf};
32use std::sync::atomic::{AtomicU64, Ordering};
33use std::time::SystemTime;
34
35use ed25519_dalek::{Signature, Signer as _, SigningKey, VerifyingKey};
36use sail_key::{QueryKey, sha256};
37use serde::{Deserialize, Serialize};
38
39use crate::maint::FileKind;
40use crate::{DiskCache, Effort, hex, shape_ok};
41
42pub const FORMAT: &str = "sail-shared-entry";
44
45pub const SHARED_VERSION: u32 = 2;
48
49pub const MODE_DEFAULT: &str = "default";
52
53pub const MAX_ENTRY_BYTES: u64 = 64 * 1024 * 1024;
56
57const DOMAIN: &[u8] = b"sail-shared/entry/v1";
59
60const STORE_DIR: &str = "v2";
62
63const SECRET_TAG: &str = "sail-ed25519-secret-v1";
64const PUBLIC_TAG: &str = "sail-ed25519-public-v1";
65
66static TMP_SEQ: AtomicU64 = AtomicU64::new(0);
68
69fn unhex<const N: usize>(text: &str) -> Option<[u8; N]> {
70 if text.len() != 2 * N {
71 return None;
72 }
73 let mut out = [0u8; N];
74 for (i, b) in out.iter_mut().enumerate() {
75 let pair = text.get(2 * i..2 * i + 2)?;
76 if !pair.bytes().all(|c| c.is_ascii_hexdigit()) {
77 return None;
78 }
79 *b = u8::from_str_radix(pair, 16).ok()?;
80 }
81 Some(out)
82}
83
84#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
87pub struct Solver {
88 pub name: String,
90 pub version: String,
92 pub binary_sha256: String,
94 pub platform: String,
96}
97
98impl Solver {
99 #[must_use]
102 pub fn summary(&self) -> String {
103 format!(
104 "{} {} {} {}",
105 self.name, self.version, self.binary_sha256, self.platform
106 )
107 }
108
109 #[must_use]
112 pub fn parse_summary(text: &str) -> Option<Self> {
113 let mut words = text.split_whitespace();
114 let s = Self {
115 name: words.next()?.to_owned(),
116 version: words.next()?.to_owned(),
117 binary_sha256: words.next()?.to_owned(),
118 platform: words.next()?.to_owned(),
119 };
120 (words.next().is_none() && s.well_formed()).then_some(s)
121 }
122
123 #[must_use]
126 pub fn well_formed(&self) -> bool {
127 let safe = |s: &str| {
128 !s.is_empty()
129 && s != "."
130 && s != ".."
131 && s.bytes()
132 .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-' | b'+'))
133 };
134 safe(&self.name)
135 && safe(&self.version)
136 && safe(&self.platform)
137 && self.binary_sha256.len() == 64
138 && self
139 .binary_sha256
140 .bytes()
141 .all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
142 }
143}
144
145#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
147pub struct Header {
148 pub format: String,
150 pub entry_version: u32,
152 pub key: String,
154 pub reply_sha256: String,
156 pub command: String,
158 pub mode: String,
160 pub solver: Solver,
162 #[serde(default)]
164 pub effort: Option<Effort>,
165 pub published_unix: u64,
167 pub signer: String,
169 pub signature: String,
171}
172
173fn field(out: &mut Vec<u8>, bytes: &[u8]) {
174 out.extend_from_slice(&(bytes.len() as u64).to_le_bytes());
175 out.extend_from_slice(bytes);
176}
177
178fn opt_u64(out: &mut Vec<u8>, v: Option<u64>) {
179 match v {
180 None => out.push(0),
181 Some(n) => {
182 out.push(1);
183 out.extend_from_slice(&n.to_le_bytes());
184 }
185 }
186}
187
188impl Header {
189 #[must_use]
193 pub fn signed_bytes(&self) -> Vec<u8> {
194 let mut out = Vec::with_capacity(512);
195 field(&mut out, DOMAIN);
196 field(&mut out, self.format.as_bytes());
197 out.extend_from_slice(&self.entry_version.to_le_bytes());
198 field(&mut out, self.key.as_bytes());
199 field(&mut out, self.reply_sha256.as_bytes());
200 field(&mut out, self.command.as_bytes());
201 field(&mut out, self.mode.as_bytes());
202 field(&mut out, self.solver.name.as_bytes());
203 field(&mut out, self.solver.version.as_bytes());
204 field(&mut out, self.solver.binary_sha256.as_bytes());
205 field(&mut out, self.solver.platform.as_bytes());
206 match &self.effort {
207 None => out.push(0),
208 Some(e) => {
209 out.push(1);
210 opt_u64(&mut out, e.limit);
211 opt_u64(&mut out, e.used);
212 match &e.reason {
213 None => out.push(0),
214 Some(r) => {
215 out.push(1);
216 field(&mut out, r.as_bytes());
217 }
218 }
219 }
220 }
221 out.extend_from_slice(&self.published_unix.to_le_bytes());
222 field(&mut out, self.signer.as_bytes());
223 out
224 }
225}
226
227pub struct SecretKey(SigningKey);
230
231impl std::fmt::Debug for SecretKey {
232 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
233 write!(f, "SecretKey({})", self.public().id())
234 }
235}
236
237impl SecretKey {
238 pub fn generate() -> std::io::Result<Self> {
244 let mut seed = [0u8; 32];
245 std::fs::File::open("/dev/urandom")?.read_exact(&mut seed)?;
246 let key = Self::from_seed(seed);
247 seed.fill(0);
248 Ok(key)
249 }
250
251 #[must_use]
253 pub fn from_seed(seed: [u8; 32]) -> Self {
254 Self(SigningKey::from_bytes(&seed))
255 }
256
257 #[must_use]
259 pub fn public(&self) -> PublicKey {
260 PublicKey(self.0.verifying_key())
261 }
262
263 #[must_use]
265 pub fn to_text(&self) -> String {
266 format!("{SECRET_TAG} {}\n", hex(self.0.as_bytes()))
267 }
268
269 #[must_use]
271 pub fn parse(text: &str) -> Option<Self> {
272 let mut words = text.split_whitespace();
273 (words.next()? == SECRET_TAG).then_some(())?;
274 let seed = unhex::<32>(words.next()?)?;
275 words.next().is_none().then(|| Self::from_seed(seed))
276 }
277
278 pub fn read_file(path: &Path) -> Result<Self, String> {
284 let text = std::fs::read_to_string(path)
285 .map_err(|e| format!("cannot read {}: {e}", path.display()))?;
286 Self::parse(&text).ok_or_else(|| format!("{} is not a sail secret key", path.display()))
287 }
288
289 pub fn write_files(&self, path: &Path) -> std::io::Result<PathBuf> {
296 let mut public = path.as_os_str().to_owned();
297 public.push(".pub");
298 let public = PathBuf::from(public);
299 let mut opts = std::fs::OpenOptions::new();
300 opts.write(true).create_new(true);
301 #[cfg(unix)]
302 {
303 use std::os::unix::fs::OpenOptionsExt as _;
304 opts.mode(0o600);
305 }
306 if public.exists() {
307 return Err(std::io::Error::new(
308 std::io::ErrorKind::AlreadyExists,
309 format!("{} exists", public.display()),
310 ));
311 }
312 opts.open(path)?.write_all(self.to_text().as_bytes())?;
313 std::fs::OpenOptions::new()
314 .write(true)
315 .create_new(true)
316 .open(&public)?
317 .write_all(self.public().to_text().as_bytes())?;
318 Ok(public)
319 }
320
321 fn sign(&self, message: &[u8]) -> Signature {
322 self.0.sign(message)
323 }
324}
325
326#[derive(Debug, Clone, Copy, PartialEq, Eq)]
328pub struct PublicKey(VerifyingKey);
329
330impl PublicKey {
331 #[must_use]
335 pub fn id(&self) -> String {
336 hex(&sha256(self.0.as_bytes())).chars().take(16).collect()
337 }
338
339 #[must_use]
341 pub fn to_text(&self) -> String {
342 format!("{PUBLIC_TAG} {}\n", hex(self.0.as_bytes()))
343 }
344
345 #[must_use]
349 pub fn parse(text: &str) -> Option<Self> {
350 let mut words = text.split_whitespace();
351 (words.next()? == PUBLIC_TAG).then_some(())?;
352 let bytes = unhex::<32>(words.next()?)?;
353 VerifyingKey::from_bytes(&bytes)
354 .ok()
355 .filter(|k| !k.is_weak())
356 .map(Self)
357 }
358
359 pub fn read_file(path: &Path) -> Result<Self, String> {
365 let text = std::fs::read_to_string(path)
366 .map_err(|e| format!("cannot read {}: {e}", path.display()))?;
367 Self::parse(&text).ok_or_else(|| format!("{} is not a sail public key", path.display()))
368 }
369}
370
371#[must_use]
373pub fn trust_dir(root: &Path) -> PathBuf {
374 root.join("trust")
375}
376
377#[derive(Debug, Clone, Default, PartialEq, Eq)]
379pub struct TrustedKeys {
380 keys: BTreeMap<String, PublicKey>,
381}
382
383impl TrustedKeys {
384 #[must_use]
387 pub fn load_dir(dir: &Path) -> (Self, Vec<String>) {
388 let mut keys = Self::default();
389 let mut problems = Vec::new();
390 let Ok(entries) = std::fs::read_dir(dir) else {
391 return (keys, problems);
392 };
393 for e in entries.flatten() {
394 let path = e.path();
395 if path.extension().is_none_or(|x| x != "pub") {
396 continue;
397 }
398 match PublicKey::read_file(&path) {
399 Ok(k) => keys.insert(k),
400 Err(msg) => problems.push(msg),
401 }
402 }
403 (keys, problems)
404 }
405
406 pub fn insert(&mut self, key: PublicKey) {
408 self.keys.insert(key.id(), key);
409 }
410
411 #[must_use]
413 pub fn get(&self, id: &str) -> Option<&PublicKey> {
414 self.keys.get(id)
415 }
416
417 #[must_use]
419 pub fn ids(&self) -> Vec<String> {
420 self.keys.keys().cloned().collect()
421 }
422
423 #[must_use]
425 pub fn len(&self) -> usize {
426 self.keys.len()
427 }
428
429 #[must_use]
431 pub fn is_empty(&self) -> bool {
432 self.keys.is_empty()
433 }
434}
435
436pub fn add_trusted(root: &Path, key: &PublicKey) -> std::io::Result<PathBuf> {
443 let dir = trust_dir(root);
444 std::fs::create_dir_all(&dir)?;
445 let path = dir.join(format!("{}.pub", key.id()));
446 let tmp = dir.join(format!(".tmp-{}-{}", std::process::id(), key.id()));
447 std::fs::write(&tmp, key.to_text())?;
448 std::fs::rename(&tmp, &path).inspect_err(|_| {
449 let _ = std::fs::remove_file(&tmp);
450 })?;
451 Ok(path)
452}
453
454#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
456#[serde(rename_all = "kebab-case")]
457pub enum Rejection {
458 Unreadable,
460 NotAFile,
462 TooLarge,
464 BadHeader,
466 WrongFormat,
468 KeyMismatch,
470 UntrustedSigner,
472 BadSignature,
474 HashMismatch,
476 OtherSolver,
478 OtherPlatform,
481 OtherMode,
483 BadShape,
485 UnservableUnknown,
487}
488
489impl Rejection {
490 #[must_use]
492 pub fn name(self) -> &'static str {
493 match self {
494 Self::Unreadable => "unreadable",
495 Self::NotAFile => "not-a-file",
496 Self::TooLarge => "too-large",
497 Self::BadHeader => "bad-header",
498 Self::WrongFormat => "wrong-format",
499 Self::KeyMismatch => "key-mismatch",
500 Self::UntrustedSigner => "untrusted-signer",
501 Self::BadSignature => "bad-signature",
502 Self::HashMismatch => "hash-mismatch",
503 Self::OtherSolver => "other-solver",
504 Self::OtherPlatform => "other-platform",
505 Self::OtherMode => "other-mode",
506 Self::BadShape => "bad-shape",
507 Self::UnservableUnknown => "unservable-unknown",
508 }
509 }
510}
511
512#[derive(Debug, Clone, PartialEq, Eq)]
514pub struct Verified {
515 pub command: String,
517 pub reply: Vec<u8>,
519 pub effort: Option<Effort>,
521 pub signer: String,
523}
524
525impl Verified {
526 #[must_use]
529 pub fn provenance(&self) -> String {
530 format!("{PROVENANCE_PREFIX}{}", self.signer)
531 }
532}
533
534pub const PROVENANCE_PREFIX: &str = "shared:";
537
538pub const PINNED_SOLVER: &str = "pinned-solver";
541
542#[must_use]
545pub fn sign_entry(
546 secret: &SecretKey,
547 key: &QueryKey,
548 reply: &[u8],
549 command: &str,
550 solver: &Solver,
551 effort: Option<&Effort>,
552 published_unix: u64,
553) -> Vec<u8> {
554 let mut header = Header {
555 format: FORMAT.to_owned(),
556 entry_version: SHARED_VERSION,
557 key: key.to_string(),
558 reply_sha256: hex(&sha256(reply)),
559 command: command.to_owned(),
560 mode: MODE_DEFAULT.to_owned(),
561 solver: solver.clone(),
562 effort: effort.cloned(),
563 published_unix,
564 signer: secret.public().id(),
565 signature: String::new(),
566 };
567 header.signature = hex(&secret.sign(&header.signed_bytes()).to_bytes());
568 let mut out = serde_json::to_vec(&header).unwrap_or_default();
569 out.push(b'\n');
570 out.extend_from_slice(reply);
571 out
572}
573
574pub fn verify_entry(
585 data: &[u8],
586 key: &QueryKey,
587 trusted: &TrustedKeys,
588 local: &Solver,
589) -> Result<Verified, Rejection> {
590 let (header, reply) = verify_entry_ref(data, key, trusted, local)?;
591 Ok(Verified {
592 command: header.command,
593 reply: reply.to_vec(),
594 effort: header.effort,
595 signer: header.signer,
596 })
597}
598
599pub fn verify_entry_ref<'a>(
605 data: &'a [u8],
606 key: &QueryKey,
607 trusted: &TrustedKeys,
608 local: &Solver,
609) -> Result<(Header, &'a [u8]), Rejection> {
610 let nl = data
611 .iter()
612 .position(|&b| b == b'\n')
613 .ok_or(Rejection::BadHeader)?;
614 let header: Header = data
615 .get(..nl)
616 .and_then(|h| serde_json::from_slice(h).ok())
617 .ok_or(Rejection::BadHeader)?;
618 if header.format != FORMAT || header.entry_version != SHARED_VERSION {
619 return Err(Rejection::WrongFormat);
620 }
621 if header.key != key.to_string() {
622 return Err(Rejection::KeyMismatch);
623 }
624 let signer = trusted
625 .get(&header.signer)
626 .ok_or(Rejection::UntrustedSigner)?;
627 let signature = unhex::<64>(&header.signature)
628 .map(|b| Signature::from_bytes(&b))
629 .ok_or(Rejection::BadSignature)?;
630 signer
631 .0
632 .verify_strict(&header.signed_bytes(), &signature)
633 .map_err(|_| Rejection::BadSignature)?;
634 let reply = data.get(nl + 1..).unwrap_or_default();
635 if header.reply_sha256 != hex(&sha256(reply)) {
636 return Err(Rejection::HashMismatch);
637 }
638 let s = &header.solver;
639 if s.name != local.name || s.version != local.version || s.binary_sha256 != local.binary_sha256
640 {
641 return Err(Rejection::OtherSolver);
642 }
643 if s.platform != local.platform {
644 return Err(Rejection::OtherPlatform);
645 }
646 if header.mode != MODE_DEFAULT {
647 return Err(Rejection::OtherMode);
648 }
649 if !shape_ok(&header.command, reply) {
650 return Err(Rejection::BadShape);
651 }
652 Ok((header, reply))
653}
654
655#[derive(Debug, Clone)]
657pub struct SharedStore {
658 root: PathBuf,
659}
660
661impl SharedStore {
662 #[must_use]
664 pub fn new(root: impl Into<PathBuf>) -> Self {
665 Self { root: root.into() }
666 }
667
668 #[must_use]
670 pub fn root(&self) -> &Path {
671 &self.root
672 }
673
674 #[must_use]
677 pub fn entry_path(&self, solver: &Solver, key: &QueryKey) -> Option<PathBuf> {
678 if !solver.well_formed() {
679 return None;
680 }
681 let k = key.to_string();
682 Some(
683 self.root
684 .join(STORE_DIR)
685 .join(&solver.platform)
686 .join(&solver.binary_sha256)
687 .join(k.get(..2).unwrap_or("xx"))
688 .join(k),
689 )
690 }
691
692 pub fn read(path: &Path) -> Result<Option<Vec<u8>>, Rejection> {
700 let mut file = match std::fs::File::open(path) {
701 Ok(f) => f,
702 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
703 Err(_) => return Err(Rejection::Unreadable),
704 };
705 let meta = file.metadata().map_err(|_| Rejection::Unreadable)?;
706 if !meta.is_file() {
707 return Err(Rejection::NotAFile);
708 }
709 if meta.len() > MAX_ENTRY_BYTES {
710 return Err(Rejection::TooLarge);
711 }
712 let mut data = Vec::with_capacity(usize::try_from(meta.len()).unwrap_or(0));
713 (&mut file)
715 .take(MAX_ENTRY_BYTES + 1)
716 .read_to_end(&mut data)
717 .map_err(|_| Rejection::Unreadable)?;
718 if data.len() as u64 > MAX_ENTRY_BYTES {
719 return Err(Rejection::TooLarge);
720 }
721 Ok(Some(data))
722 }
723
724 pub fn write(path: &Path, data: &[u8]) -> std::io::Result<()> {
731 let dir = path.parent().ok_or_else(|| {
732 std::io::Error::new(std::io::ErrorKind::InvalidInput, "entry path has no parent")
733 })?;
734 std::fs::create_dir_all(dir)?;
735 let seq = TMP_SEQ.fetch_add(1, Ordering::Relaxed);
736 let tmp = dir.join(format!(".tmp-{}-{seq}", std::process::id()));
737 let written = std::fs::write(&tmp, data).and_then(|()| std::fs::rename(&tmp, path));
738 if written.is_err() {
739 let _ = std::fs::remove_file(&tmp);
740 }
741 written
742 }
743}
744
745#[derive(Debug, Clone, Default)]
747pub struct PublishOptions {
748 pub commands: Vec<String>,
750 pub solver_sha256: Option<String>,
752 pub dry_run: bool,
754}
755
756#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
758pub struct PublishReport {
759 pub examined: u64,
761 pub published: u64,
763 pub present: u64,
765 pub from_shared: u64,
767 pub other_provenance: u64,
769 pub unattributed: u64,
772 pub unknown_held: u64,
774 pub filtered: u64,
776 pub invalid: u64,
778 pub failed: u64,
780}
781
782pub(crate) struct Eligible {
785 pub(crate) key: QueryKey,
786 pub(crate) meta: crate::Meta,
787 pub(crate) reply: Vec<u8>,
788 pub(crate) solver: Solver,
789}
790
791pub(crate) fn eligible(
797 disk: &DiskCache,
798 options: &PublishOptions,
799 unknown_ok: &dyn Fn(Option<&Effort>) -> bool,
800 r: &mut PublishReport,
801 mut each: impl FnMut(Eligible, &mut PublishReport),
802) {
803 for listed in disk.list() {
804 let FileKind::Entry(key) = listed.kind else {
805 continue;
806 };
807 let Ok((meta, reply)) = DiskCache::check_file(&listed.path, &key) else {
808 r.invalid += 1;
809 continue;
810 };
811 r.examined += 1;
812 if meta.mode != MODE_DEFAULT {
813 r.filtered += 1;
814 continue;
815 }
816 if meta.provenance.starts_with(PROVENANCE_PREFIX) {
817 r.from_shared += 1;
818 continue;
819 }
820 if meta.provenance != PINNED_SOLVER {
821 r.other_provenance += 1;
822 continue;
823 }
824 let Some(solver) = Solver::parse_summary(&meta.solver) else {
825 r.unattributed += 1;
826 continue;
827 };
828 if (!options.commands.is_empty() && !options.commands.contains(&meta.command))
829 || options
830 .solver_sha256
831 .as_ref()
832 .is_some_and(|p| !solver.binary_sha256.starts_with(p.as_str()))
833 {
834 r.filtered += 1;
835 continue;
836 }
837 if meta.command.starts_with("check-sat")
838 && reply.trim_ascii() == b"unknown"
839 && !unknown_ok(meta.effort.as_ref())
840 {
841 r.unknown_held += 1;
842 continue;
843 }
844 each(
845 Eligible {
846 key,
847 meta,
848 reply,
849 solver,
850 },
851 r,
852 );
853 }
854}
855
856pub(crate) fn now_unix() -> u64 {
858 SystemTime::now()
859 .duration_since(std::time::UNIX_EPOCH)
860 .map_or(0, |d| d.as_secs())
861}
862
863pub fn publish(
872 disk: &DiskCache,
873 store: &SharedStore,
874 secret: &SecretKey,
875 options: &PublishOptions,
876 unknown_ok: &dyn Fn(Option<&Effort>) -> bool,
877) -> PublishReport {
878 let mut report = PublishReport::default();
879 let mut ours = TrustedKeys::default();
880 ours.insert(secret.public());
881 let now = now_unix();
882 eligible(disk, options, unknown_ok, &mut report, |e, r| {
883 let Some(path) = store.entry_path(&e.solver, &e.key) else {
884 r.unattributed += 1;
885 return;
886 };
887 let present = SharedStore::read(&path)
888 .ok()
889 .flatten()
890 .is_some_and(|data| verify_entry(&data, &e.key, &ours, &e.solver).is_ok());
891 if present {
892 r.present += 1;
893 return;
894 }
895 if options.dry_run {
896 r.published += 1;
897 return;
898 }
899 let data = sign_entry(
900 secret,
901 &e.key,
902 &e.reply,
903 &e.meta.command,
904 &e.solver,
905 e.meta.effort.as_ref(),
906 now,
907 );
908 match SharedStore::write(&path, &data) {
909 Ok(()) => r.published += 1,
910 Err(_) => r.failed += 1,
911 }
912 });
913 report
914}
915
916#[cfg(test)]
917mod tests {
918 use super::*;
919
920 fn solver() -> Solver {
921 Solver {
922 name: "z3".to_owned(),
923 version: "4.16.0".to_owned(),
924 binary_sha256: "ab".repeat(32),
925 platform: "macos-aarch64".to_owned(),
926 }
927 }
928
929 fn trusting(k: &SecretKey) -> TrustedKeys {
930 let mut t = TrustedKeys::default();
931 t.insert(k.public());
932 t
933 }
934
935 const KEY: QueryKey = QueryKey([7; 32]);
936
937 type Put<'a> = (u8, &'a [u8], &'a str, &'a str, &'a str, Option<&'a Effort>);
939
940 #[test]
941 fn a_signed_entry_verifies_and_every_field_is_bound() {
942 let sk = SecretKey::from_seed([1; 32]);
943 let trusted = trusting(&sk);
944 let effort = Effort {
945 limit: Some(100),
946 used: Some(3),
947 reason: Some("(:reason-unknown \"incomplete quantifiers\")".to_owned()),
948 };
949 let data = sign_entry(
950 &sk,
951 &KEY,
952 b"unknown\n",
953 "check-sat",
954 &solver(),
955 Some(&effort),
956 9,
957 );
958 let v = verify_entry(&data, &KEY, &trusted, &solver());
959 assert_eq!(
960 v.as_ref().map(|v| (v.reply.as_slice(), v.effort.as_ref())),
961 Ok((&b"unknown\n"[..], Some(&effort)))
962 );
963 assert_eq!(
964 v.map(|v| v.provenance()),
965 Ok(format!("shared:{}", sk.public().id()))
966 );
967
968 let nl = data.iter().position(|&b| b == b'\n').unwrap_or(0);
970 let header: serde_json::Value =
971 serde_json::from_slice(data.get(..nl).unwrap_or_default()).unwrap_or_default();
972 let reply = data.get(nl + 1..).unwrap_or_default();
973 assert_eq!(
975 header["signature"].as_str(),
976 Some(concat!(
977 "5e3e7aef8f5e9b7a207c5a2639b6d2e878d252287c291f46d96eae719b600a32",
978 "6f50de40e8bf38d0f4f1303d76d2397f6820dd5e3c0259a7cc95db9e9a680b01",
979 )),
980 );
981 let edits: &[(&str, serde_json::Value)] = &[
982 ("command", "get-model".into()),
983 ("mode", "opt-in".into()),
984 ("published_unix", 10.into()),
985 (
986 "effort",
987 serde_json::json!({"limit": 100, "used": 99, "reason": null}),
988 ),
989 ("effort", serde_json::Value::Null),
990 ];
991 for (name, value) in edits {
992 let mut h = header.clone();
993 h[*name] = value.clone();
994 let mut forged = serde_json::to_vec(&h).unwrap_or_default();
995 forged.push(b'\n');
996 forged.extend_from_slice(reply);
997 assert_eq!(
998 verify_entry(&forged, &KEY, &trusted, &solver()),
999 Err(Rejection::BadSignature),
1000 "{name}"
1001 );
1002 }
1003 for (field, value) in [
1004 ("name", "cvc5"),
1005 ("version", "4.16.1"),
1006 ("platform", "linux-x86_64"),
1007 ] {
1008 let mut h = header.clone();
1009 h["solver"][field] = value.into();
1010 let mut forged = serde_json::to_vec(&h).unwrap_or_default();
1011 forged.push(b'\n');
1012 forged.extend_from_slice(reply);
1013 assert_eq!(
1014 verify_entry(&forged, &KEY, &trusted, &solver()),
1015 Err(Rejection::BadSignature),
1016 "{field}"
1017 );
1018 }
1019 }
1020
1021 #[test]
1022 fn forged_untrusted_corrupt_and_foreign_entries_are_rejected() {
1023 let sk = SecretKey::from_seed([1; 32]);
1024 let other = SecretKey::from_seed([2; 32]);
1025 let trusted = trusting(&sk);
1026 let good = sign_entry(&sk, &KEY, b"unsat\n", "check-sat", &solver(), None, 1);
1027 let end = good.iter().position(|&b| b == b'\n').unwrap_or(0);
1029 let mut old_header: Header = serde_json::from_slice(&good[..end])
1030 .unwrap_or_else(|e| unreachable!("valid fixture: {e}"));
1031 old_header.entry_version = 1;
1032 old_header.signature = hex(&sk.sign(&old_header.signed_bytes()).to_bytes());
1033 let mut old = serde_json::to_vec(&old_header).unwrap_or_default();
1034 old.extend_from_slice(&good[end..]);
1035 assert_eq!(
1036 verify_entry(&old, &KEY, &trusted, &solver()),
1037 Err(Rejection::WrongFormat)
1038 );
1039
1040 let mut forged = sign_entry(&other, &KEY, b"sat\n", "check-sat", &solver(), None, 1);
1042 assert_eq!(
1043 verify_entry(&forged, &KEY, &trusted, &solver()),
1044 Err(Rejection::UntrustedSigner)
1045 );
1046 let text =
1048 String::from_utf8_lossy(&forged).replace(&other.public().id(), &sk.public().id());
1049 forged = text.into_bytes();
1050 assert_eq!(
1051 verify_entry(&forged, &KEY, &trusted, &solver()),
1052 Err(Rejection::BadSignature)
1053 );
1054 let swapped = String::from_utf8_lossy(&good).replace("\nunsat\n", "\nsat\n");
1056 assert_eq!(
1057 verify_entry(swapped.as_bytes(), &KEY, &trusted, &solver()),
1058 Err(Rejection::HashMismatch)
1059 );
1060 let half = good.get(..good.len() / 2).unwrap_or_default();
1062 assert_eq!(
1063 verify_entry(half, &KEY, &trusted, &solver()),
1064 Err(Rejection::BadHeader)
1065 );
1066 assert_eq!(
1067 verify_entry(b"", &KEY, &trusted, &solver()),
1068 Err(Rejection::BadHeader)
1069 );
1070 assert!(verify_entry(b"\x00\xff garbage\nunsat\n", &KEY, &trusted, &solver()).is_err());
1071 assert_eq!(
1073 verify_entry(&good, &QueryKey([8; 32]), &trusted, &solver()),
1074 Err(Rejection::KeyMismatch)
1075 );
1076 let mut s = solver();
1078 s.binary_sha256 = "cd".repeat(32);
1079 assert_eq!(
1080 verify_entry(&good, &KEY, &trusted, &s),
1081 Err(Rejection::OtherSolver)
1082 );
1083 let mut p = solver();
1084 p.platform = "linux-x86_64".to_owned();
1085 assert_eq!(
1086 verify_entry(&good, &KEY, &trusted, &p),
1087 Err(Rejection::OtherPlatform)
1088 );
1089 let bad = sign_entry(
1091 &sk,
1092 &KEY,
1093 b"(error \"x\")\n",
1094 "check-sat",
1095 &solver(),
1096 None,
1097 1,
1098 );
1099 assert_eq!(
1100 verify_entry(&bad, &KEY, &trusted, &solver()),
1101 Err(Rejection::BadShape)
1102 );
1103 assert_eq!(
1105 verify_entry(&good, &KEY, &TrustedKeys::default(), &solver()),
1106 Err(Rejection::UntrustedSigner)
1107 );
1108 }
1109
1110 #[test]
1111 fn keys_round_trip_through_text_and_files() {
1112 let sk = SecretKey::from_seed([3; 32]);
1113 let parsed = SecretKey::parse(&sk.to_text()).map(|k| k.public());
1114 assert_eq!(parsed, Some(sk.public()));
1115 assert_eq!(PublicKey::parse(&sk.public().to_text()), Some(sk.public()));
1116 assert_eq!(
1117 PublicKey::parse(&format!("{} ci release", sk.public().to_text().trim())),
1118 Some(sk.public())
1119 );
1120 assert!(PublicKey::parse(&sk.to_text()).is_none());
1121 assert!(SecretKey::parse(&sk.public().to_text()).is_none());
1122 assert!(PublicKey::parse("sail-ed25519-public-v1 zz").is_none());
1123 let weak = format!("{PUBLIC_TAG} 01{}", "00".repeat(31));
1125 assert!(PublicKey::parse(&weak).is_none());
1126 assert!(!format!("{sk:?}").contains(&hex(&[3; 32])));
1127 assert_eq!(sk.public().id().len(), 16);
1128
1129 let dir = std::env::temp_dir().join(format!("sail-shared-keys-{}", std::process::id()));
1130 let _ = std::fs::remove_dir_all(&dir);
1131 assert!(std::fs::create_dir_all(&dir).is_ok());
1132 let generated = SecretKey::generate();
1133 assert!(generated.is_ok());
1134 if let Ok(g) = generated {
1135 let file = dir.join("ci.key");
1136 let public = g.write_files(&file);
1137 assert!(public.is_ok());
1138 assert!(g.write_files(&file).is_err(), "never overwrites a key");
1139 assert_eq!(
1140 SecretKey::read_file(&file).map(|k| k.public()),
1141 Ok(g.public())
1142 );
1143 #[cfg(unix)]
1144 {
1145 use std::os::unix::fs::PermissionsExt as _;
1146 let mode = std::fs::metadata(&file).map(|m| m.permissions().mode() & 0o777);
1147 assert_eq!(mode.ok(), Some(0o600));
1148 }
1149 let root = dir.join("cache");
1150 assert!(add_trusted(&root, &g.public()).is_ok());
1151 assert!(std::fs::write(trust_dir(&root).join("junk.pub"), "nope").is_ok());
1152 let (keys, problems) = TrustedKeys::load_dir(&trust_dir(&root));
1153 assert_eq!(keys.ids(), vec![g.public().id()]);
1154 assert_eq!(problems.len(), 1);
1155 }
1156 let _ = std::fs::remove_dir_all(&dir);
1157 }
1158
1159 #[test]
1160 fn solver_summaries_round_trip_and_unsafe_ones_are_refused() {
1161 assert_eq!(Solver::parse_summary(&solver().summary()), Some(solver()));
1162 assert_eq!(Solver::parse_summary(""), None);
1163 assert_eq!(Solver::parse_summary("z3 4.16.0 abc macos"), None);
1164 let mut s = solver();
1165 s.platform = "../etc".to_owned();
1166 assert!(!s.well_formed());
1167 assert!(SharedStore::new("/s").entry_path(&s, &KEY).is_none());
1168 }
1169
1170 #[test]
1171 fn publish_exports_only_local_pinned_solver_entries() {
1172 let dir = std::env::temp_dir().join(format!("sail-shared-pub-{}", std::process::id()));
1173 let _ = std::fs::remove_dir_all(&dir);
1174 let disk = DiskCache::new(dir.join("cache"));
1175 let store = SharedStore::new(dir.join("store"));
1176 let sk = SecretKey::from_seed([4; 32]);
1177 let id = solver().summary();
1178 let far = Effort {
1179 limit: Some(100),
1180 used: Some(1),
1181 reason: Some("(:reason-unknown \"incomplete quantifiers\")".to_owned()),
1182 };
1183 let near = Effort {
1184 used: Some(90),
1185 ..far.clone()
1186 };
1187 let puts: &[Put] = &[
1188 (1, b"unsat\n", "check-sat", &id, PINNED_SOLVER, None),
1189 (
1190 2,
1191 b"sat\n",
1192 "check-sat",
1193 &id,
1194 "shared:0123456789abcdef",
1195 None,
1196 ),
1197 (3, b"unsat\n", "check-sat", "", PINNED_SOLVER, None),
1198 (
1199 4,
1200 b"unknown\n",
1201 "check-sat",
1202 &id,
1203 PINNED_SOLVER,
1204 Some(&near),
1205 ),
1206 (5, b"unknown\n", "check-sat", &id, PINNED_SOLVER, Some(&far)),
1207 (6, b"x\n", "echo", &id, PINNED_SOLVER, None),
1208 ];
1209 for (k, reply, cmd, solver, prov, effort) in puts {
1210 let r = disk.put(&QueryKey([*k; 32]), reply, cmd, solver, prov, *effort);
1211 assert!(r.is_ok());
1212 }
1213 assert!(
1214 disk.put_scoped(
1215 &QueryKey([7; 32]),
1216 b"unsat\n",
1217 "check-sat",
1218 &crate::StoreContext {
1219 solver: &id,
1220 provenance: PINNED_SOLVER,
1221 mode: "accept-first-proof"
1222 },
1223 None
1224 )
1225 .is_ok()
1226 );
1227 let policy = |e: Option<&Effort>| e.is_some_and(|e| e.used.unwrap_or(u64::MAX) * 2 <= 100);
1228 let opts = PublishOptions {
1229 commands: vec!["check-sat".to_owned()],
1230 ..PublishOptions::default()
1231 };
1232 let r = publish(&disk, &store, &sk, &opts, &policy);
1233 assert_eq!(
1234 (
1235 r.examined,
1236 r.published,
1237 r.from_shared,
1238 r.unattributed,
1239 r.unknown_held,
1240 r.filtered
1241 ),
1242 (7, 2, 1, 1, 1, 2)
1243 );
1244 let trusted = trusting(&sk);
1246 for k in [1u8, 5] {
1247 let key = QueryKey([k; 32]);
1248 let data = store
1249 .entry_path(&solver(), &key)
1250 .and_then(|p| SharedStore::read(&p).ok().flatten());
1251 let v = data.map(|d| verify_entry(&d, &key, &trusted, &solver()));
1252 assert!(matches!(v, Some(Ok(_))), "key {k}");
1253 }
1254 let again = publish(&disk, &store, &sk, &opts, &policy);
1256 assert_eq!((again.published, again.present), (0, 2));
1257 let _ = std::fs::remove_dir_all(&dir);
1258 }
1259}