Skip to main content

quilt/machine/
pin.rs

1//! Pinned machines: named by content, and run with nothing else.
2//!
3//! `py⟨M⟩` means "whatever `python3` this shell would run", which is the right
4//! default and the wrong thing to *record*: a cached answer, a logged run or a
5//! reproduced result has to say which Python answered, built how, with which
6//! libraries. A [`Pin`] is that answer. It names a Nix store path by the
7//! **content address** of its whole runtime closure, and [`qspawn_pinned`]
8//! starts the language's registered machine from that path with an empty
9//! environment, so the pin alone decides what runs. The machine then reports
10//! the address as its [`identity`](super::Machine::identity).
11//!
12//! # The address
13//!
14//! `nix store make-content-addressed` rewrites a store path, and everything it
15//! references, to paths whose names are functions of their contents. The
16//! rewritten path's name — `7r699cyp…-python3-3.14.10` — is the address. Nix
17//! computes it and can verify it, it covers the closure rather than one file,
18//! and it needs no experimental features.
19//!
20//! It is one address per platform: the same recipe built for another system is
21//! other bytes and another address. Relating the two is a claim about a build,
22//! which is somebody else's job.
23//!
24//! # What runs
25//!
26//! On Linux the rewritten path runs, so what runs is what was named. On macOS
27//! rewriting a store path inside a signed binary invalidates its signature and
28//! the kernel kills the process, and re-signing would change the content. So
29//! there the *original* path runs, after `make-content-addressed` has been seen
30//! to map it to the address. The gap is exactly the rewritten store paths
31//! inside the files, and nothing else.
32//!
33//! Computing an address takes tens of seconds for a large closure, so the
34//! mapping from original path to address is cached (`$QUILT_PIN_CACHE`, else
35//! `quilt/pins` under the user's cache directory).
36//!
37//! Pinning says *which* machine ran, not what it was allowed to touch: a
38//! pinned interpreter still runs with the caller's privileges.
39
40use super::{repl_spec, script_spec, Machine, ReplMachine, ScriptMachine};
41use crate::prelude::*;
42use miette::{bail, miette, IntoDiagnostic, WrapErr};
43use std::path::{Path, PathBuf};
44use std::process::Command;
45
46const STORE: &str = "/nix/store";
47
48/// A machine's interpreter, pinned: its content address and the store path
49/// that runs for it.
50#[derive(Clone, Debug, PartialEq, Eq)]
51pub struct Pin {
52    /// The content address: the name of the content-addressed store path,
53    /// such as `7r699cypjyibyji6c8l9yada8wbpv20a-python3-3.14.10`.
54    pub address: Box<str>,
55    /// The store path that runs: the content-addressed one, or on macOS the
56    /// original it was computed from (see the [module docs](self)).
57    pub path: PathBuf,
58}
59
60/// Whether `s` has the shape of a store path's name: a 32-character base-32
61/// hash, a dash, a name.
62#[must_use]
63pub fn is_address(s: &str) -> bool {
64    let Some((hash, name)) = s.split_once('-') else {
65        return false;
66    };
67    // Nix's base-32 alphabet omits `e`, `o`, `t` and `u`.
68    hash.len() == 32
69        && hash
70            .bytes()
71            .all(|b| b.is_ascii_digit() || (b.is_ascii_lowercase() && !b"eotu".contains(&b)))
72        && !name.is_empty()
73        && !name.contains('/')
74}
75
76fn nix(args: &[&str]) -> Result<String> {
77    let out = Command::new("nix")
78        .args(["--extra-experimental-features", "nix-command flakes"])
79        .args(args)
80        .output()
81        .into_diagnostic()
82        .wrap_err("failed to run `nix` (pinning a machine needs Nix)")?;
83    if !out.status.success() {
84        bail!(
85            "nix {}: {}",
86            args.join(" "),
87            String::from_utf8_lossy(&out.stderr).trim()
88        );
89    }
90    Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
91}
92
93fn name_of(path: &Path) -> Result<&str> {
94    path.file_name()
95        .and_then(|n| n.to_str())
96        .ok_or_else(|| miette!("{} is not a store path", path.display()))
97}
98
99fn cache_dir() -> PathBuf {
100    if let Some(dir) = std::env::var_os("QUILT_PIN_CACHE") {
101        return dir.into();
102    }
103    let base = std::env::var_os("XDG_CACHE_HOME").map_or_else(
104        || PathBuf::from(std::env::var_os("HOME").unwrap_or_default()).join(".cache"),
105        PathBuf::from,
106    );
107    base.join("quilt").join("pins")
108}
109
110/// The path `original` was rewritten to, read out of
111/// `make-content-addressed --json`'s `{"rewrites":{"<original>":"<rewritten>"}}`.
112/// Store paths hold no quotes or escapes, so this needs no JSON parser — which
113/// keeps one off the runtime-only build.
114fn rewritten<'j>(json: &'j str, original: &str) -> Option<&'j str> {
115    let key = format!("\"{original}\"");
116    let rest = json[json.find(&key)? + key.len()..].trim_start();
117    let rest = rest.strip_prefix(':')?.trim_start().strip_prefix('"')?;
118    rest.split('"').next()
119}
120
121/// The content address of an original store path, from the cache or from Nix.
122fn content_address(original: &Path) -> Result<Box<str>> {
123    let entry = cache_dir().join(name_of(original)?);
124    if let Ok(cached) = std::fs::read_to_string(&entry) {
125        if is_address(cached.trim()) {
126            return Ok(cached.trim().into());
127        }
128    }
129    let path = original.to_string_lossy();
130    let json = nix(&["store", "make-content-addressed", "--json", &path])?;
131    let address = rewritten(&json, &path)
132        .and_then(|p| Path::new(p).file_name()?.to_str())
133        .filter(|a| is_address(a))
134        .ok_or_else(|| miette!("nix rewrote nothing for {path}: {json}"))?;
135    // The cache is an optimization: a read-only home must not fail a pin.
136    if std::fs::create_dir_all(cache_dir()).is_ok() {
137        let _ = std::fs::write(&entry, format!("{address}\n"));
138    }
139    Ok(address.into())
140}
141
142impl Pin {
143    /// The path that runs for `address`, given the original it came from.
144    fn runnable(address: Box<str>, original: PathBuf) -> Pin {
145        let path = if cfg!(target_os = "macos") {
146            original
147        } else {
148            Path::new(STORE).join(&*address)
149        };
150        Pin { address, path }
151    }
152
153    /// Pin a path already in the Nix store: compute its content address.
154    ///
155    /// # Errors
156    /// If Nix is missing, or cannot rewrite the path.
157    pub fn of_store_path(original: &Path) -> Result<Pin> {
158        let address = content_address(original)?;
159        Ok(Pin::runnable(address, original.to_path_buf()))
160    }
161
162    /// Build `recipe` — an installable such as `nixpkgs#python3`, or better a
163    /// locked `github:NixOS/nixpkgs/<rev>#python3` — and pin what it builds.
164    ///
165    /// The recipe is only a way to *get* the machine. Two recipes that build
166    /// the same bytes give the same pin, and the address is what to record.
167    ///
168    /// # Errors
169    /// If Nix is missing, the recipe doesn't build, or it builds to more than
170    /// one path.
171    pub fn build(recipe: &str) -> Result<Pin> {
172        let out = nix(&["build", recipe, "--no-link", "--print-out-paths"])?;
173        let mut paths = out.lines();
174        let (Some(original), None) = (paths.next(), paths.next()) else {
175            bail!("{recipe} builds to {} paths, not one", out.lines().count());
176        };
177        Pin::of_store_path(Path::new(original))
178    }
179
180    /// Find what runs for a recorded `address`, and confirm it.
181    ///
182    /// With a recipe, build it and refuse it if it gives another address.
183    /// Without one, use what an earlier pin cached, or on Linux the
184    /// content-addressed path itself if the store has it.
185    ///
186    /// # Errors
187    /// If `address` is malformed, the recipe builds to another address, or
188    /// nothing in the local store realizes it.
189    pub fn check(address: &str, recipe: Option<&str>) -> Result<Pin> {
190        if !is_address(address) {
191            bail!("{address:?} is not a Nix content address");
192        }
193        if let Some(recipe) = recipe {
194            let pin = Pin::build(recipe)?;
195            if &*pin.address != address {
196                bail!("{recipe} builds to {}, not {address}", pin.address);
197            }
198            return Ok(pin);
199        }
200        // An original whose cached address is this one, if it is still there.
201        for entry in std::fs::read_dir(cache_dir())
202            .into_iter()
203            .flatten()
204            .flatten()
205        {
206            let original = Path::new(STORE).join(entry.file_name());
207            let cached = std::fs::read_to_string(entry.path()).unwrap_or_default();
208            if cached.trim() == address && original.exists() {
209                return Ok(Pin::runnable(address.into(), original));
210            }
211        }
212        let rewritten = Path::new(STORE).join(address);
213        if !cfg!(target_os = "macos") && rewritten.exists() {
214            // The store checked the name against the contents when it took
215            // the path, so its presence is the confirmation.
216            return Ok(Pin {
217                address: address.into(),
218                path: rewritten,
219            });
220        }
221        bail!("no machine with address {address} is realized here; pass the recipe that builds it")
222    }
223
224    /// The pinned spelling of an interpreter a spec names by bare name:
225    /// `<path>/bin/<program>`.
226    fn program(&self, program: &str) -> Result<Box<str>> {
227        let pinned = self.path.join("bin").join(program);
228        if !pinned.exists() {
229            bail!(
230                "the machine pinned at {} has no bin/{program}",
231                self.address
232            );
233        }
234        Ok(pinned.to_string_lossy().into())
235    }
236}
237
238/// Spawn `lang`'s registered machine from a [`Pin`]: the same provider
239/// [`qspawn`](super::qspawn) would choose, with its interpreter taken from the
240/// pinned path instead of `PATH`, an environment holding only what the spec
241/// sets, and the pin's address as its [`identity`](Machine::identity).
242///
243/// # Errors
244/// If `lang` has no subprocess machine (a native machine has no interpreter
245/// to pin), the pin holds no such interpreter, or it fails to start.
246pub fn qspawn_pinned(lang: &str, pin: &Pin) -> Result<Box<dyn Machine>> {
247    if let Some(mut spec) = repl_spec(lang) {
248        spec.program = pin.program(&spec.program)?;
249        spec.clear_env = true;
250        spec.identity = Some(pin.address.clone());
251        return Ok(Box::new(ReplMachine::spawn(lang, spec)?));
252    }
253    if let Some(mut spec) = script_spec(lang) {
254        spec.program = pin.program(&spec.program)?;
255        spec.clear_env = true;
256        spec.identity = Some(pin.address.clone());
257        return Ok(Box::new(ScriptMachine::new(lang, spec)));
258    }
259    bail!("no subprocess machine is registered for {lang:?}, so there is nothing to pin")
260}
261
262#[cfg(test)]
263mod tests {
264    use super::*;
265    use crate::lang::InnerKind;
266    use crate::qterm::qleaf;
267
268    #[test]
269    fn an_address_is_a_store_paths_name() {
270        assert!(is_address(
271            "7r699cypjyibyji6c8l9yada8wbpv20a-python3-3.14.10"
272        ));
273        assert!(!is_address("Python 3.14.10"));
274        assert!(!is_address("7r699cypjyibyji6c8l9yada8wbpv20a"));
275        // `e` is not in Nix's alphabet.
276        assert!(!is_address("7r699cypjyibyji6c8l9yada8wbpv20e-python3"));
277        assert!(!is_address(
278            "/nix/store/7r699cypjyibyji6c8l9yada8wbpv20a-python3"
279        ));
280    }
281
282    #[test]
283    fn the_rewrite_is_read_from_nixs_json() {
284        let json = r#"{"rewrites":{"/nix/store/aaa-x":"/nix/store/bbb-x"}}"#;
285        assert_eq!(
286            rewritten(json, "/nix/store/aaa-x"),
287            Some("/nix/store/bbb-x")
288        );
289        assert_eq!(rewritten(json, "/nix/store/ccc-x"), None);
290    }
291
292    #[test]
293    fn an_unknown_address_is_refused_before_anything_runs() {
294        let e = Pin::check("00000000000000000000000000000000-nothing", None).unwrap_err();
295        assert!(e.to_string().contains("recipe"), "{e}");
296        assert!(Pin::check("python3", None).is_err());
297    }
298
299    /// The whole path, against a real store: build, address, spawn, answer.
300    /// Run with `cargo test -p quiltlang pin -- --ignored`.
301    #[test]
302    #[ignore = "builds nixpkgs#python3 with Nix, which needs the network"]
303    fn a_pinned_python_answers_and_says_which_it_is() {
304        let pin = Pin::build("nixpkgs#python3").unwrap();
305        assert!(is_address(&pin.address));
306        // The address is a function of the contents, so it is stable, and a
307        // recorded address finds its machine again without the recipe.
308        assert_eq!(Pin::check(&pin.address, None).unwrap(), pin);
309        assert!(Pin::check(&pin.address, Some("nixpkgs#bash")).is_err());
310
311        let mut m = qspawn_pinned("py", &pin).unwrap();
312        assert_eq!(m.identity(), Some(&*pin.address));
313        m.feed(InnerKind::Item, &qleaf("code", "x = 20")).unwrap();
314        let answer = m.eval(&qleaf("code", "x + 22")).unwrap();
315        assert_eq!(answer.value.as_deref(), Some("42"));
316        // Nothing of the caller's environment reached it.
317        let path = m
318            .eval(&qleaf("code", "__import__('os').environ.get('PATH')"))
319            .unwrap();
320        assert_eq!(path.value.as_deref(), Some("None"));
321        // And it is the pinned interpreter, not the one on `PATH`.
322        let exe = m
323            .eval(&qleaf("code", "__import__('sys').executable"))
324            .unwrap();
325        assert!(exe.value.unwrap().contains(STORE));
326    }
327}