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 let edits: &[(&str, serde_json::Value)] = &[
974 ("command", "get-model".into()),
975 ("mode", "opt-in".into()),
976 ("published_unix", 10.into()),
977 (
978 "effort",
979 serde_json::json!({"limit": 100, "used": 99, "reason": null}),
980 ),
981 ("effort", serde_json::Value::Null),
982 ];
983 for (name, value) in edits {
984 let mut h = header.clone();
985 h[*name] = value.clone();
986 let mut forged = serde_json::to_vec(&h).unwrap_or_default();
987 forged.push(b'\n');
988 forged.extend_from_slice(reply);
989 assert_eq!(
990 verify_entry(&forged, &KEY, &trusted, &solver()),
991 Err(Rejection::BadSignature),
992 "{name}"
993 );
994 }
995 for (field, value) in [
996 ("name", "cvc5"),
997 ("version", "4.16.1"),
998 ("platform", "linux-x86_64"),
999 ] {
1000 let mut h = header.clone();
1001 h["solver"][field] = value.into();
1002 let mut forged = serde_json::to_vec(&h).unwrap_or_default();
1003 forged.push(b'\n');
1004 forged.extend_from_slice(reply);
1005 assert_eq!(
1006 verify_entry(&forged, &KEY, &trusted, &solver()),
1007 Err(Rejection::BadSignature),
1008 "{field}"
1009 );
1010 }
1011 }
1012
1013 #[test]
1014 fn forged_untrusted_corrupt_and_foreign_entries_are_rejected() {
1015 let sk = SecretKey::from_seed([1; 32]);
1016 let other = SecretKey::from_seed([2; 32]);
1017 let trusted = trusting(&sk);
1018 let good = sign_entry(&sk, &KEY, b"unsat\n", "check-sat", &solver(), None, 1);
1019 let end = good.iter().position(|&b| b == b'\n').unwrap_or(0);
1021 let mut old_header: Header = serde_json::from_slice(&good[..end])
1022 .unwrap_or_else(|e| unreachable!("valid fixture: {e}"));
1023 old_header.entry_version = 1;
1024 old_header.signature = hex(&sk.sign(&old_header.signed_bytes()).to_bytes());
1025 let mut old = serde_json::to_vec(&old_header).unwrap_or_default();
1026 old.extend_from_slice(&good[end..]);
1027 assert_eq!(
1028 verify_entry(&old, &KEY, &trusted, &solver()),
1029 Err(Rejection::WrongFormat)
1030 );
1031
1032 let mut forged = sign_entry(&other, &KEY, b"sat\n", "check-sat", &solver(), None, 1);
1034 assert_eq!(
1035 verify_entry(&forged, &KEY, &trusted, &solver()),
1036 Err(Rejection::UntrustedSigner)
1037 );
1038 let text =
1040 String::from_utf8_lossy(&forged).replace(&other.public().id(), &sk.public().id());
1041 forged = text.into_bytes();
1042 assert_eq!(
1043 verify_entry(&forged, &KEY, &trusted, &solver()),
1044 Err(Rejection::BadSignature)
1045 );
1046 let swapped = String::from_utf8_lossy(&good).replace("\nunsat\n", "\nsat\n");
1048 assert_eq!(
1049 verify_entry(swapped.as_bytes(), &KEY, &trusted, &solver()),
1050 Err(Rejection::HashMismatch)
1051 );
1052 let half = good.get(..good.len() / 2).unwrap_or_default();
1054 assert_eq!(
1055 verify_entry(half, &KEY, &trusted, &solver()),
1056 Err(Rejection::BadHeader)
1057 );
1058 assert_eq!(
1059 verify_entry(b"", &KEY, &trusted, &solver()),
1060 Err(Rejection::BadHeader)
1061 );
1062 assert!(verify_entry(b"\x00\xff garbage\nunsat\n", &KEY, &trusted, &solver()).is_err());
1063 assert_eq!(
1065 verify_entry(&good, &QueryKey([8; 32]), &trusted, &solver()),
1066 Err(Rejection::KeyMismatch)
1067 );
1068 let mut s = solver();
1070 s.binary_sha256 = "cd".repeat(32);
1071 assert_eq!(
1072 verify_entry(&good, &KEY, &trusted, &s),
1073 Err(Rejection::OtherSolver)
1074 );
1075 let mut p = solver();
1076 p.platform = "linux-x86_64".to_owned();
1077 assert_eq!(
1078 verify_entry(&good, &KEY, &trusted, &p),
1079 Err(Rejection::OtherPlatform)
1080 );
1081 let bad = sign_entry(
1083 &sk,
1084 &KEY,
1085 b"(error \"x\")\n",
1086 "check-sat",
1087 &solver(),
1088 None,
1089 1,
1090 );
1091 assert_eq!(
1092 verify_entry(&bad, &KEY, &trusted, &solver()),
1093 Err(Rejection::BadShape)
1094 );
1095 assert_eq!(
1097 verify_entry(&good, &KEY, &TrustedKeys::default(), &solver()),
1098 Err(Rejection::UntrustedSigner)
1099 );
1100 }
1101
1102 #[test]
1103 fn keys_round_trip_through_text_and_files() {
1104 let sk = SecretKey::from_seed([3; 32]);
1105 let parsed = SecretKey::parse(&sk.to_text()).map(|k| k.public());
1106 assert_eq!(parsed, Some(sk.public()));
1107 assert_eq!(PublicKey::parse(&sk.public().to_text()), Some(sk.public()));
1108 assert_eq!(
1109 PublicKey::parse(&format!("{} ci release", sk.public().to_text().trim())),
1110 Some(sk.public())
1111 );
1112 assert!(PublicKey::parse(&sk.to_text()).is_none());
1113 assert!(SecretKey::parse(&sk.public().to_text()).is_none());
1114 assert!(PublicKey::parse("sail-ed25519-public-v1 zz").is_none());
1115 let weak = format!("{PUBLIC_TAG} 01{}", "00".repeat(31));
1117 assert!(PublicKey::parse(&weak).is_none());
1118 assert!(!format!("{sk:?}").contains(&hex(&[3; 32])));
1119 assert_eq!(sk.public().id().len(), 16);
1120
1121 let dir = std::env::temp_dir().join(format!("sail-shared-keys-{}", std::process::id()));
1122 let _ = std::fs::remove_dir_all(&dir);
1123 assert!(std::fs::create_dir_all(&dir).is_ok());
1124 let generated = SecretKey::generate();
1125 assert!(generated.is_ok());
1126 if let Ok(g) = generated {
1127 let file = dir.join("ci.key");
1128 let public = g.write_files(&file);
1129 assert!(public.is_ok());
1130 assert!(g.write_files(&file).is_err(), "never overwrites a key");
1131 assert_eq!(
1132 SecretKey::read_file(&file).map(|k| k.public()),
1133 Ok(g.public())
1134 );
1135 #[cfg(unix)]
1136 {
1137 use std::os::unix::fs::PermissionsExt as _;
1138 let mode = std::fs::metadata(&file).map(|m| m.permissions().mode() & 0o777);
1139 assert_eq!(mode.ok(), Some(0o600));
1140 }
1141 let root = dir.join("cache");
1142 assert!(add_trusted(&root, &g.public()).is_ok());
1143 assert!(std::fs::write(trust_dir(&root).join("junk.pub"), "nope").is_ok());
1144 let (keys, problems) = TrustedKeys::load_dir(&trust_dir(&root));
1145 assert_eq!(keys.ids(), vec![g.public().id()]);
1146 assert_eq!(problems.len(), 1);
1147 }
1148 let _ = std::fs::remove_dir_all(&dir);
1149 }
1150
1151 #[test]
1152 fn solver_summaries_round_trip_and_unsafe_ones_are_refused() {
1153 assert_eq!(Solver::parse_summary(&solver().summary()), Some(solver()));
1154 assert_eq!(Solver::parse_summary(""), None);
1155 assert_eq!(Solver::parse_summary("z3 4.16.0 abc macos"), None);
1156 let mut s = solver();
1157 s.platform = "../etc".to_owned();
1158 assert!(!s.well_formed());
1159 assert!(SharedStore::new("/s").entry_path(&s, &KEY).is_none());
1160 }
1161
1162 #[test]
1163 fn publish_exports_only_local_pinned_solver_entries() {
1164 let dir = std::env::temp_dir().join(format!("sail-shared-pub-{}", std::process::id()));
1165 let _ = std::fs::remove_dir_all(&dir);
1166 let disk = DiskCache::new(dir.join("cache"));
1167 let store = SharedStore::new(dir.join("store"));
1168 let sk = SecretKey::from_seed([4; 32]);
1169 let id = solver().summary();
1170 let far = Effort {
1171 limit: Some(100),
1172 used: Some(1),
1173 reason: Some("(:reason-unknown \"incomplete quantifiers\")".to_owned()),
1174 };
1175 let near = Effort {
1176 used: Some(90),
1177 ..far.clone()
1178 };
1179 let puts: &[Put] = &[
1180 (1, b"unsat\n", "check-sat", &id, PINNED_SOLVER, None),
1181 (
1182 2,
1183 b"sat\n",
1184 "check-sat",
1185 &id,
1186 "shared:0123456789abcdef",
1187 None,
1188 ),
1189 (3, b"unsat\n", "check-sat", "", PINNED_SOLVER, None),
1190 (
1191 4,
1192 b"unknown\n",
1193 "check-sat",
1194 &id,
1195 PINNED_SOLVER,
1196 Some(&near),
1197 ),
1198 (5, b"unknown\n", "check-sat", &id, PINNED_SOLVER, Some(&far)),
1199 (6, b"x\n", "echo", &id, PINNED_SOLVER, None),
1200 ];
1201 for (k, reply, cmd, solver, prov, effort) in puts {
1202 let r = disk.put(&QueryKey([*k; 32]), reply, cmd, solver, prov, *effort);
1203 assert!(r.is_ok());
1204 }
1205 assert!(
1206 disk.put_scoped(
1207 &QueryKey([7; 32]),
1208 b"unsat\n",
1209 "check-sat",
1210 &crate::StoreContext {
1211 solver: &id,
1212 provenance: PINNED_SOLVER,
1213 mode: "accept-first-proof"
1214 },
1215 None
1216 )
1217 .is_ok()
1218 );
1219 let policy = |e: Option<&Effort>| e.is_some_and(|e| e.used.unwrap_or(u64::MAX) * 2 <= 100);
1220 let opts = PublishOptions {
1221 commands: vec!["check-sat".to_owned()],
1222 ..PublishOptions::default()
1223 };
1224 let r = publish(&disk, &store, &sk, &opts, &policy);
1225 assert_eq!(
1226 (
1227 r.examined,
1228 r.published,
1229 r.from_shared,
1230 r.unattributed,
1231 r.unknown_held,
1232 r.filtered
1233 ),
1234 (7, 2, 1, 1, 1, 2)
1235 );
1236 let trusted = trusting(&sk);
1238 for k in [1u8, 5] {
1239 let key = QueryKey([k; 32]);
1240 let data = store
1241 .entry_path(&solver(), &key)
1242 .and_then(|p| SharedStore::read(&p).ok().flatten());
1243 let v = data.map(|d| verify_entry(&d, &key, &trusted, &solver()));
1244 assert!(matches!(v, Some(Ok(_))), "key {k}");
1245 }
1246 let again = publish(&disk, &store, &sk, &opts, &policy);
1248 assert_eq!((again.published, again.present), (0, 2));
1249 let _ = std::fs::remove_dir_all(&dir);
1250 }
1251}