Skip to main content

vanta_resolve/
lib.rs

1//! `vanta-resolve` — turn a [`Request`] into a deterministic [`Resolution`].
2//!
3//! Resolution reads the registry, filters versions by the request's constraint,
4//! picks the maximum satisfying version by SemVer ordering, and renders a
5//! per-platform artifact for every requested target. The result is fully pinned
6//! and lockable. See `docs/06-resolution.md`.
7//!
8//! Most tools are independent leaves; inter-tool dependency graphs are resolved
9//! where a provider declares them.
10#![forbid(unsafe_code)]
11
12use std::cmp::Ordering;
13use vanta_core::{Area, Checksum, Platform, Request, Resolution, VersionReq, VtaError, VtaResult};
14use vanta_registry::{Registry, VersionEntry};
15
16/// Resolves requests against a registry.
17pub struct Resolver<'a> {
18    registry: &'a Registry,
19}
20
21impl<'a> Resolver<'a> {
22    pub fn new(registry: &'a Registry) -> Resolver<'a> {
23        Resolver { registry }
24    }
25
26    /// Resolve `request` for every platform in `targets`.
27    pub fn resolve(&self, request: &Request, targets: &[Platform]) -> VtaResult<Resolution> {
28        let entry = self
29            .registry
30            .tool(&request.tool)
31            .ok_or_else(|| self.unknown_tool_error(&request.tool))?;
32
33        let candidates: Vec<&VersionEntry> = entry
34            .versions
35            .iter()
36            .filter(|v| !v.yanked && satisfies(&request.version, v))
37            .collect();
38
39        let chosen = candidates
40            .iter()
41            .copied()
42            .max_by(|a, b| cmp_version(&a.version, &b.version))
43            .ok_or_else(|| {
44                self.no_matching_version_error(&request.tool, &request.version.to_string(), entry)
45            })?;
46
47        let mut per_platform = Vec::new();
48        for platform in targets {
49            if let Some(pc) = chosen.platforms.get(&platform.token()) {
50                let checksum = Checksum {
51                    algo: "sha256".to_string(),
52                    value: pc.sha256.clone(),
53                };
54                let mut artifact =
55                    entry
56                        .provider
57                        .render_artifact(&chosen.version, platform, checksum, pc.size);
58                artifact.signature = pc.signature.clone();
59                // C1: the per-artifact signing key is only trusted if the index
60                // that carried it was authenticated against a pinned root
61                // (transitive trust), or the key is itself pinned. Otherwise it
62                // is attacker-influenceable, so we drop it (`None`) — the install
63                // engine then treats the artifact as unsigned and, under a
64                // signature-requiring policy, refuses it (fail-closed).
65                artifact.signature_key = entry
66                    .public_key
67                    .as_deref()
68                    .filter(|k| {
69                        vanta_security::trust::artifact_key_is_trusted(
70                            k,
71                            self.registry.index_verified,
72                            &self.registry.trusted_root_keys,
73                        )
74                    })
75                    .map(str::to_string);
76                per_platform.push((*platform, artifact));
77            }
78        }
79
80        if per_platform.is_empty() {
81            return Err(VtaError::new(
82                Area::Res,
83                5,
84                format!(
85                    "no artifact for `{}` {} on any requested platform",
86                    request.tool, chosen.version
87                ),
88            ));
89        }
90
91        Ok(Resolution {
92            tool: request.tool.clone(),
93            version: chosen.version.clone(),
94            provider: entry.provider.id.clone(),
95            per_platform,
96        })
97    }
98
99    /// Build the `unknown tool` error, enriched with close-match suggestions and
100    /// the list of tools the registry actually knows, so a typo or a
101    /// not-yet-supported tool produces an actionable message instead of a
102    /// dead end.
103    fn unknown_tool_error(&self, requested: &str) -> VtaError {
104        let names: Vec<&str> = self.registry.tools.keys().map(String::as_str).collect();
105
106        // "Did you mean": names within a small edit distance (scaled to the
107        // requested length) or that contain the request as a substring, best
108        // first, capped to a few.
109        let want = requested.to_lowercase();
110        let budget = (want.len() / 3).max(2);
111        let mut scored: Vec<(usize, &str)> = names
112            .iter()
113            .filter_map(|n| {
114                let d = levenshtein(&want, &n.to_lowercase());
115                let contains = n.to_lowercase().contains(&want) || want.contains(&n.to_lowercase());
116                if d <= budget || contains {
117                    Some((if contains { 0 } else { d }, *n))
118                } else {
119                    None
120                }
121            })
122            .collect();
123        scored.sort_by(|a, b| a.0.cmp(&b.0).then_with(|| a.1.cmp(b.1)));
124        let suggestions: Vec<&str> = scored.into_iter().take(3).map(|(_, n)| n).collect();
125
126        let mut msg = format!("unknown tool `{requested}`");
127        // Tools people ask for that have no official prebuilt binaries: point
128        // at the canonical installer instead of a dead end.
129        let hint = match requested {
130            "rust" | "rustc" | "cargo" => {
131                Some("rust is distributed via rustup (https://rustup.rs); a vanta source-build provider is planned")
132            }
133            "ruby" => Some(
134                "ruby publishes no official prebuilt binaries; a vanta source-build provider is planned",
135            ),
136            "java" | "jdk" => Some("try `vanta search` for a packaged JDK, or use SDKMAN meanwhile"),
137            _ => None,
138        };
139        if let Some(h) = hint {
140            msg.push_str(&format!("\n  note: {h}"));
141        }
142        if !suggestions.is_empty() {
143            msg.push_str(&format!("\n  did you mean: {}?", suggestions.join(", ")));
144        }
145        if names.is_empty() {
146            msg.push_str(
147                "\n  the registry index is empty (offline, or no registry configured)",
148            );
149        } else {
150            // Cap the listing so a large future registry stays readable.
151            let shown = 20;
152            let list = names
153                .iter()
154                .take(shown)
155                .copied()
156                .collect::<Vec<_>>()
157                .join(", ");
158            msg.push_str(&format!("\n  available tools: {list}"));
159            if names.len() > shown {
160                msg.push_str(&format!(", … (+{} more)", names.len() - shown));
161            }
162            msg.push_str("\n  run `vanta search <term>` to search the registry");
163        }
164        VtaError::new(Area::Res, 3, msg)
165    }
166
167    /// Build the `no version satisfies` error, listing the versions the registry
168    /// actually carries (newest first) so the user can pick a real one instead
169    /// of guessing. A stale index (e.g. asking for `24` when only `22`/`20` are
170    /// seeded) then reads as an obvious mismatch.
171    fn no_matching_version_error(
172        &self,
173        tool: &str,
174        want: &str,
175        entry: &vanta_registry::ToolEntry,
176    ) -> VtaError {
177        let mut available: Vec<&str> = entry
178            .versions
179            .iter()
180            .filter(|v| !v.yanked)
181            .map(|v| v.version.as_str())
182            .collect();
183        available.sort_by(|a, b| cmp_version(b, a)); // newest first
184
185        let mut msg = format!("no version of `{tool}` satisfies `{want}`");
186        if available.is_empty() {
187            msg.push_str("\n  the registry lists no (non-yanked) versions for this tool");
188        } else {
189            let shown = 10;
190            let list = available
191                .iter()
192                .take(shown)
193                .copied()
194                .collect::<Vec<_>>()
195                .join(", ");
196            msg.push_str(&format!("\n  available: {list}"));
197            if available.len() > shown {
198                msg.push_str(&format!(", … (+{} more)", available.len() - shown));
199            }
200            msg.push_str(&format!(
201                "\n  try `vanta add {tool}@{}` or widen the constraint",
202                available[0]
203            ));
204        }
205        VtaError::new(Area::Res, 1, msg)
206    }
207}
208
209/// Levenshtein edit distance between two strings (for "did you mean").
210fn levenshtein(a: &str, b: &str) -> usize {
211    let a: Vec<char> = a.chars().collect();
212    let b: Vec<char> = b.chars().collect();
213    if a.is_empty() {
214        return b.len();
215    }
216    if b.is_empty() {
217        return a.len();
218    }
219    let mut prev: Vec<usize> = (0..=b.len()).collect();
220    let mut curr = vec![0usize; b.len() + 1];
221    for (i, ca) in a.iter().enumerate() {
222        curr[0] = i + 1;
223        for (j, cb) in b.iter().enumerate() {
224            let cost = if ca == cb { 0 } else { 1 };
225            curr[j + 1] = (prev[j + 1] + 1).min(curr[j] + 1).min(prev[j] + cost);
226        }
227        std::mem::swap(&mut prev, &mut curr);
228    }
229    prev[b.len()]
230}
231
232/// Pick the artifact for a specific platform out of a resolution.
233pub fn artifact_for<'r>(
234    resolution: &'r Resolution,
235    platform: &Platform,
236) -> Option<&'r vanta_core::Artifact> {
237    resolution
238        .per_platform
239        .iter()
240        .find(|(p, _)| p == platform)
241        .map(|(_, a)| a)
242}
243
244/// Whether a version entry satisfies a request's constraint.
245fn satisfies(req: &VersionReq, entry: &VersionEntry) -> bool {
246    match req {
247        VersionReq::Exact(s) => &entry.version == s,
248        VersionReq::Prefix(p) => &entry.version == p || entry.version.starts_with(&format!("{p}.")),
249        VersionReq::Latest => is_stable(entry),
250        VersionReq::Lts => entry.lts,
251        VersionReq::Channel(c) => entry.channel.as_deref() == Some(c.as_str()),
252        VersionReq::Range(r) => sem_match(r, &entry.version),
253        VersionReq::System => false,
254        _ => false, // `VersionReq` is #[non_exhaustive]
255    }
256}
257
258fn is_stable(entry: &VersionEntry) -> bool {
259    let channel_ok = matches!(entry.channel.as_deref(), None | Some("stable"));
260    let pre_ok = semver::Version::parse(&entry.version)
261        .map(|v| v.pre.is_empty())
262        .unwrap_or(true);
263    channel_ok && pre_ok
264}
265
266fn sem_match(range: &str, version: &str) -> bool {
267    match (
268        semver::VersionReq::parse(range),
269        semver::Version::parse(version),
270    ) {
271        (Ok(req), Ok(ver)) => req.matches(&ver),
272        _ => false,
273    }
274}
275
276/// Order two version strings: SemVer where both parse, else lexical.
277fn cmp_version(a: &str, b: &str) -> Ordering {
278    match (semver::Version::parse(a), semver::Version::parse(b)) {
279        (Ok(x), Ok(y)) => x.cmp(&y),
280        _ => a.cmp(b),
281    }
282}
283
284#[cfg(test)]
285mod tests {
286    use super::*;
287    use vanta_core::{Arch, Libc, Os};
288
289    const SAMPLE: &str = r#"
290[tools.node.provider]
291id = "official/node"
292tool = "node"
293url_template = "https://nodejs.org/dist/v{version}/node-v{version}-{os}-{arch}.{ext}"
294archive = "tar.gz"
295bin = ["bin/node"]
296
297[[tools.node.version]]
298version = "24.5.0"
299channel = "stable"
300[tools.node.version.platforms."macos/aarch64"]
301sha256 = "55"
302
303[[tools.node.version]]
304version = "24.6.0"
305channel = "stable"
306[tools.node.version.platforms."macos/aarch64"]
307sha256 = "66"
308
309[[tools.node.version]]
310version = "25.0.0"
311channel = "stable"
312[tools.node.version.platforms."macos/aarch64"]
313sha256 = "00"
314"#;
315
316    fn mac() -> Platform {
317        Platform {
318            os: Os::Macos,
319            arch: Arch::Aarch64,
320            libc: Libc::None,
321        }
322    }
323
324    fn resolve(spec: &str) -> VtaResult<Resolution> {
325        let reg = Registry::from_toml(SAMPLE).unwrap();
326        let resolver = Resolver::new(&reg);
327        resolver.resolve(&Request::parse(spec).unwrap(), &[mac()])
328    }
329
330    #[test]
331    fn prefix_picks_newest_in_series() {
332        assert_eq!(resolve("node@24").unwrap().version, "24.6.0");
333    }
334
335    #[test]
336    fn two_component_prefix_pins_series() {
337        assert_eq!(resolve("node@24.5").unwrap().version, "24.5.0");
338    }
339
340    #[test]
341    fn latest_picks_global_newest() {
342        assert_eq!(resolve("node@latest").unwrap().version, "25.0.0");
343    }
344
345    #[test]
346    fn exact_pins() {
347        assert_eq!(resolve("node@24.5.0").unwrap().version, "24.5.0");
348    }
349
350    #[test]
351    fn range_constraint() {
352        // >=24, <25 → newest is 24.6.0
353        assert_eq!(resolve("node@>=24, <25").unwrap().version, "24.6.0");
354    }
355
356    #[test]
357    fn renders_artifact_for_target() {
358        let res = resolve("node@24").unwrap();
359        let art = artifact_for(&res, &mac()).unwrap();
360        assert_eq!(
361            art.url,
362            "https://nodejs.org/dist/v24.6.0/node-v24.6.0-macos-aarch64.tar.gz"
363        );
364        assert_eq!(art.checksum.value, "66");
365    }
366
367    #[test]
368    fn unknown_tool_errors() {
369        assert_eq!(resolve("python@3").unwrap_err().area, Area::Res);
370    }
371
372    #[test]
373    fn no_match_errors() {
374        let err = resolve("node@99").unwrap_err();
375        assert_eq!(err.area, Area::Res);
376        assert_eq!(err.number, 1);
377    }
378
379    // C1: a registry index carries a per-tool `public_key`. It must only be
380    // propagated as a trusted signing key when the index was authenticated
381    // against a pinned root (or the key is itself pinned).
382    const SIGNED_SAMPLE: &str = r#"
383[tools.node]
384public_key = "untrusted comment: attacker\nRWQfattackerkeytext=="
385
386[tools.node.provider]
387id = "official/node"
388tool = "node"
389url_template = "https://nodejs.org/dist/v{version}/node-v{version}-{os}-{arch}.{ext}"
390archive = "tar.gz"
391bin = ["bin/node"]
392
393[[tools.node.version]]
394version = "24.6.0"
395channel = "stable"
396[tools.node.version.platforms."macos/aarch64"]
397sha256 = "66"
398signature = "untrusted comment: sig\nRWQfsig=="
399"#;
400
401    #[test]
402    fn attacker_key_with_unsigned_index_is_dropped() {
403        // Index NOT verified against a pinned root → the attacker-supplied
404        // signing key must not be trusted.
405        let reg = Registry::from_toml(SIGNED_SAMPLE).unwrap();
406        assert!(!reg.index_verified);
407        let resolver = Resolver::new(&reg);
408        let res = resolver
409            .resolve(&Request::parse("node@24.6.0").unwrap(), &[mac()])
410            .unwrap();
411        let art = artifact_for(&res, &mac()).unwrap();
412        assert_eq!(art.signature_key, None); // untrusted key rejected
413    }
414
415    #[test]
416    fn key_from_verified_index_is_trusted() {
417        // Index verified against a pinned root → its key is trusted transitively.
418        let mut reg = Registry::from_toml(SIGNED_SAMPLE).unwrap();
419        reg.index_verified = true;
420        let resolver = Resolver::new(&reg);
421        let res = resolver
422            .resolve(&Request::parse("node@24.6.0").unwrap(), &[mac()])
423            .unwrap();
424        let art = artifact_for(&res, &mac()).unwrap();
425        assert!(art.signature_key.is_some());
426    }
427}