Skip to main content

bynk/
fetch.rs

1//! Packaging slice 2b (#2240): fetching git dependencies and writing
2//! `bynk.lock` — the one place the toolchain touches the network (track
3//! `design/tracks/packaging.md` §6.4, decision A).
4//!
5//! Before `check`, `test`, `dev` or `deploy` compiles, [`prepare`] resolves
6//! the project's (or its workspace's) dependencies against `bynk.lock`:
7//!
8//! - a locked git dependency whose manifest entry is unchanged keeps its
9//!   locked commit; one missing from the store is fetched at that commit;
10//! - a new or changed one (or every one named by `bynk update`) is resolved
11//!   from its `rev`, fetched, and hashed;
12//! - every git package's store entry is re-hashed against the lock, so a
13//!   tampered or corrupted entry fails the build (`checksum_mismatch`);
14//! - the lock is rewritten when the graph changed — or, under `--locked`,
15//!   the command fails instead (`lock_out_of_date`). Under `--offline`, any
16//!   needed fetch fails.
17//!
18//! Git runs as the user's own `git`, hardened per track §6.3 (decision B):
19//! only `https` and `ssh` transports (plus `file` from the project's own
20//! manifests), no hooks, no submodules, `--` before positional arguments,
21//! and no URL or revision that looks like an option. Bynk passes no
22//! credentials: a private repository works through the user's git setup.
23//!
24//! The compile never fetches: `bynk`, the language server and the
25//! playground read the lock and the store ([`bynk_driver::project`]'s graph
26//! resolution reports `not_fetched` for a missing entry).
27
28use std::collections::{BTreeMap, BTreeSet};
29use std::path::{Path, PathBuf};
30use std::process::Command;
31
32use bynk_driver::project::{is_workspace_root, load_workspace};
33use sha2::{Digest, Sha256};
34
35use bynk_project::lock::{
36    LOCK_FILE, Lock, LockedNpm, LockedPackage, adapter_requires, bynk_home, checksum_hex,
37    checksum_of, git_source, lock_root, parse_lock, path_source, store_dir,
38};
39use bynk_project::manifest::{
40    DependencySource, DependencySpec, dependencies_from, package_config_from,
41};
42
43/// How a `bynk` command may change the lock and the store.
44#[derive(Debug, Clone, Default)]
45pub struct FetchOptions {
46    /// Fail instead of changing `bynk.lock`.
47    pub locked: bool,
48    /// Fail instead of fetching.
49    pub offline: bool,
50    /// `bynk update`: re-resolve these packages' revisions (`Some(empty)`
51    /// means every git dependency).
52    pub update: Option<Vec<String>>,
53}
54
55/// A failure, as one diagnostic line: its code and message.
56#[derive(Debug, Clone, PartialEq, Eq)]
57pub struct FetchError {
58    pub code: &'static str,
59    pub message: String,
60}
61
62impl std::fmt::Display for FetchError {
63    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
64        write!(f, "error[{}]: {}", self.code, self.message)
65    }
66}
67
68const NOT_FETCHED: &str = "bynk.package.not_fetched";
69const LOCK_OUT_OF_DATE: &str = "bynk.package.lock_out_of_date";
70pub(crate) const CHECKSUM_MISMATCH: &str = "bynk.package.checksum_mismatch";
71const VERSION_CONFLICT: &str = "bynk.package.version_conflict";
72const LOCK_INVALID: &str = "bynk.package.lock_invalid";
73const GIT_FAILED: &str = "bynk.package.git_failed";
74const UNSAFE_SOURCE: &str = "bynk.package.unsafe_source";
75const PATH_OUTSIDE_ROOT: &str = "bynk.dependency.path_outside_root";
76
77pub(crate) fn fail(code: &'static str, message: impl Into<String>) -> FetchError {
78    FetchError {
79        code,
80        message: message.into(),
81    }
82}
83
84/// What [`prepare`] did.
85#[derive(Debug, Clone, Default, PartialEq, Eq)]
86pub struct Prepared {
87    /// Whether `bynk.lock` was written.
88    pub wrote_lock: bool,
89    /// The git packages fetched into the store, as `org/package@commit`.
90    pub fetched: Vec<String>,
91    /// Things worth saying that aren't failures: a `bynk update` name that
92    /// matched no git dependency.
93    pub warnings: Vec<String>,
94    /// #2296: the lock's npm requirements awaiting approval — each needed by
95    /// a fetched package's adapter, and not yet approved.
96    pub pending: Vec<LockedNpm>,
97}
98
99/// Resolve, fetch and lock the dependencies of the project at `project_dir`
100/// (and of every member of its workspace, which shares one lock). A project
101/// with no dependencies and no lock is untouched.
102pub fn prepare(project_dir: &Path, opts: &FetchOptions) -> Result<Prepared, FetchError> {
103    let root = lock_root(project_dir);
104    let members: Vec<PathBuf> = if is_workspace_root(&root) {
105        // A workspace that doesn't load is the command's own to report, in
106        // the words it always has.
107        match load_workspace(&root) {
108            Ok(w) => w.members.iter().map(|m| root.join(m)).collect(),
109            Err(_) => return Ok(Prepared::default()),
110        }
111    } else {
112        vec![project_dir.to_path_buf()]
113    };
114    let lock_path = root.join(LOCK_FILE);
115    let existing = match std::fs::read_to_string(&lock_path) {
116        Ok(text) => Some(parse_lock(&text).map_err(|e| fail(LOCK_INVALID, e.0))?),
117        Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
118        // Any other failure must not read as "no lock" and re-resolve.
119        Err(e) => {
120            return Err(fail(
121                LOCK_INVALID,
122                format!("could not read `{}`: {e}", lock_path.display()),
123            ));
124        }
125    };
126    // #2274: registry versions are chosen against every range that reaches a
127    // package, and a choice's own dependencies add ranges — so resolution
128    // repeats until no new range appears (decision C; no backtracking).
129    let mut client = crate::registry::Client::new(
130        crate::registry::commands::registries_of(&root),
131        existing.as_ref(),
132    );
133    let mut ranges: BTreeMap<String, BTreeSet<(String, String)>> = BTreeMap::new();
134    let mut prepared = Prepared::default();
135    let mut any;
136    let mut pass = 0;
137    let mut walk = loop {
138        pass += 1;
139        let before = ranges.clone();
140        let mut walk = Walk {
141            root: root.clone(),
142            opts,
143            existing: existing.clone().unwrap_or_default(),
144            home: None,
145            resolved: BTreeMap::new(),
146            prepared: std::mem::take(&mut prepared),
147            updated: BTreeSet::new(),
148            dirs: BTreeMap::new(),
149            client,
150            ranges,
151            used_registries: BTreeSet::new(),
152        };
153        any = false;
154        for member in &members {
155            let Some(doc) = read_manifest(member) else {
156                continue;
157            };
158            let mut declared = specs(&doc, "dependencies");
159            declared.extend(specs(&doc, "dev-dependencies"));
160            any |= !declared.is_empty();
161            for spec in declared {
162                walk.resolve(member, Declarer::Own, &spec)?;
163            }
164        }
165        if walk.ranges == before || pass >= MAX_PASSES {
166            break walk;
167        }
168        client = walk.client;
169        ranges = walk.ranges;
170        prepared = walk.prepared;
171    };
172    walk.prepared.warnings.append(&mut walk.client.notices);
173    if let Some(names) = &opts.update {
174        for n in names.iter().filter(|n| !walk.updated.contains(*n)) {
175            walk.prepared.warnings.push(format!(
176                "`{n}` names no git dependency, so nothing was updated for it"
177            ));
178        }
179    }
180    if !any && existing.is_none() {
181        return Ok(walk.prepared);
182    }
183    // A registry this resolution read is recorded with the trust it used; one
184    // only reached through the lock keeps its locked record.
185    let registries = walk
186        .used_registries
187        .iter()
188        .filter_map(|name| {
189            walk.client
190                .trust
191                .get(name)
192                .cloned()
193                .or_else(|| walk.existing.registry(name).cloned())
194        })
195        .collect();
196    let npm = approvals(
197        npm_requirements(&walk.dirs, &members),
198        &walk.resolved,
199        &walk.existing,
200        &mut walk.prepared,
201    );
202    let lock = Lock {
203        packages: walk.resolved.values().cloned().collect(),
204        registries,
205        npm,
206    };
207    let rendered = lock.render();
208    let current = existing.as_ref().map(Lock::render);
209    if current.as_deref() != Some(rendered.as_str()) {
210        if opts.locked {
211            return Err(fail(
212                LOCK_OUT_OF_DATE,
213                format!(
214                    "`{}` is out of date with the manifests, and `--locked` was given",
215                    lock_path.display()
216                ),
217            ));
218        }
219        write_atomically(&lock_path, &rendered).map_err(|e| {
220            fail(
221                LOCK_INVALID,
222                format!("could not write `{}`: {e}", lock_path.display()),
223            )
224        })?;
225        walk.prepared.wrote_lock = true;
226    }
227    Ok(walk.prepared)
228}
229
230/// Who declared a dependency: the project (or a workspace member, or a path
231/// package — the author's own files), or a fetched package.
232#[derive(Clone, Copy, PartialEq, Eq)]
233enum Declarer {
234    Own,
235    Fetched,
236}
237
238struct Walk<'o> {
239    root: PathBuf,
240    opts: &'o FetchOptions,
241    existing: Lock,
242    home: Option<PathBuf>,
243    /// Resolved packages by name.
244    resolved: BTreeMap<String, LockedPackage>,
245    prepared: Prepared,
246    /// The `bynk update` names some git dependency matched.
247    updated: BTreeSet<String>,
248    /// #2255: each resolved package's directory (its working copy, or its
249    /// store entry), by name, for its adapters' npm requirements.
250    dirs: BTreeMap<String, PathBuf>,
251    /// #2274: the registries in use, and every range reaching each registry
252    /// package, as `(requirer, range)`.
253    client: crate::registry::Client,
254    ranges: BTreeMap<String, BTreeSet<(String, String)>>,
255    used_registries: BTreeSet<String>,
256}
257
258/// #2274: resolution passes before a growing set of ranges is reported as is.
259const MAX_PASSES: usize = 8;
260
261impl Walk<'_> {
262    fn home(&mut self) -> Result<PathBuf, FetchError> {
263        if let Some(h) = &self.home {
264            return Ok(h.clone());
265        }
266        let h = bynk_home().ok_or_else(|| {
267            fail(
268                NOT_FETCHED,
269                "can't find a cache directory for the store: set `BYNK_HOME`",
270            )
271        })?;
272        self.home = Some(h.clone());
273        Ok(h)
274    }
275
276    /// Resolve one dependency of a package in `dir`, then its own.
277    fn resolve(
278        &mut self,
279        dir: &Path,
280        declarer: Declarer,
281        spec: &DependencySpec,
282    ) -> Result<(), FetchError> {
283        match &spec.source {
284            DependencySource::Version(range) => self.resolve_registry(dir, spec, range),
285            DependencySource::Path(p) => {
286                if declarer == Declarer::Fetched {
287                    return Err(fail(
288                        PATH_OUTSIDE_ROOT,
289                        format!(
290                            "the fetched package declaring `{}` names the path dependency `{p}`, and a fetched package's path dependencies are never honoured",
291                            spec.alias
292                        ),
293                    ));
294                }
295                let target = dir.join(p);
296                let Some(doc) = read_manifest(&target) else {
297                    return Ok(()); // the graph reports a missing directory
298                };
299                let source = path_source(&relative(&self.root, &target));
300                let version = package_version(&doc);
301                let deps = specs(&doc, "dependencies");
302                if !self.record(spec, source, None, version, &deps)? {
303                    return Ok(());
304                }
305                self.dirs.insert(spec.package.clone(), target.clone());
306                for d in deps {
307                    self.resolve(&target, Declarer::Own, &d)?;
308                }
309                Ok(())
310            }
311            DependencySource::Git { url, rev } => {
312                check_source(url, rev, declarer)?;
313                let allow_file = declarer == Declarer::Own;
314                let refresh = self.opts.update.as_ref().is_some_and(|names| {
315                    names.is_empty() || names.iter().any(|n| *n == spec.alias || *n == spec.package)
316                });
317                if let Some(names) = &self.opts.update {
318                    for n in names {
319                        if *n == spec.alias || *n == spec.package {
320                            self.updated.insert(n.clone());
321                        }
322                    }
323                }
324                let locked = (!refresh)
325                    .then(|| self.existing.git(&spec.package, url, rev))
326                    .flatten()
327                    .map(|(p, commit)| (p.checksum.clone(), commit));
328                if let Some((_, commit)) = &locked
329                    && !(commit.len() >= 40 && commit.chars().all(|c| c.is_ascii_hexdigit()))
330                {
331                    return Err(fail(
332                        LOCK_INVALID,
333                        format!(
334                            "`bynk.lock` locks `{}` to `{commit}`, which isn't a commit id",
335                            spec.package
336                        ),
337                    ));
338                }
339                if matches!(&locked, Some((None, _))) {
340                    return Err(fail(
341                        LOCK_INVALID,
342                        format!(
343                            "`bynk.lock` locks the git package `{}` without a `checksum`",
344                            spec.package
345                        ),
346                    ));
347                }
348                let home = self.home()?;
349                let (commit, checksum) = match locked {
350                    Some((Some(checksum), commit)) => {
351                        let entry = store_dir(&home, &checksum).ok_or_else(|| {
352                            fail(
353                                LOCK_INVALID,
354                                format!(
355                                    "`bynk.lock`'s checksum for `{}` is malformed",
356                                    spec.package
357                                ),
358                            )
359                        })?;
360                        if !entry.is_dir() {
361                            if self.opts.offline {
362                                return Err(fail(
363                                    NOT_FETCHED,
364                                    format!(
365                                        "`{}` ({url} at {commit}) isn't in the store, and `--offline` was given",
366                                        spec.package
367                                    ),
368                                ));
369                            }
370                            let got = fetch_into_store(&home, url, &commit, allow_file)?;
371                            if got != checksum {
372                                return Err(fail(
373                                    CHECKSUM_MISMATCH,
374                                    format!(
375                                        "`{}` at {commit} hashes to {got}, but `bynk.lock` says {checksum}",
376                                        spec.package
377                                    ),
378                                ));
379                            }
380                            self.prepared
381                                .fetched
382                                .push(format!("{}@{commit}", spec.package));
383                        }
384                        (commit, checksum)
385                    }
386                    _ => {
387                        if self.opts.locked {
388                            return Err(fail(
389                                LOCK_OUT_OF_DATE,
390                                format!(
391                                    "`{}` ({url} at {rev}) isn't locked, and `--locked` was given",
392                                    spec.package
393                                ),
394                            ));
395                        }
396                        if self.opts.offline {
397                            return Err(fail(
398                                NOT_FETCHED,
399                                format!(
400                                    "`{}` ({url} at {rev}) needs fetching, and `--offline` was given",
401                                    spec.package
402                                ),
403                            ));
404                        }
405                        let commit = resolve_rev(&home, url, rev, allow_file)?;
406                        let checksum = fetch_into_store(&home, url, &commit, allow_file)?;
407                        self.prepared
408                            .fetched
409                            .push(format!("{}@{commit}", spec.package));
410                        (commit, checksum)
411                    }
412                };
413                let entry = store_dir(&home, &checksum).expect("a checksum this module wrote");
414                verify(&entry, &checksum, &spec.package)?;
415                let Some(doc) = read_manifest(&entry) else {
416                    return Err(fail(
417                        NOT_FETCHED,
418                        format!("`{url}` at {commit} has no `bynk.toml`"),
419                    ));
420                };
421                let version = package_version(&doc);
422                let deps = specs(&doc, "dependencies");
423                let source = git_source(url, rev, &commit);
424                if !self.record(spec, source, Some(checksum), version, &deps)? {
425                    return Ok(());
426                }
427                self.dirs.insert(spec.package.clone(), entry.clone());
428                for d in deps {
429                    self.resolve(&entry, Declarer::Fetched, &d)?;
430                }
431                Ok(())
432            }
433        }
434    }
435
436    /// #2274: a registry dependency — chosen against every range reaching it,
437    /// fetched into the store, verified, recorded, and its own dependencies
438    /// walked.
439    fn resolve_registry(
440        &mut self,
441        dir: &Path,
442        spec: &DependencySpec,
443        range: &str,
444    ) -> Result<(), FetchError> {
445        use bynk_project::lock::{parse_registry_source, registry_source};
446        let requirer = read_manifest(dir)
447            .and_then(|doc| {
448                doc.get("package")
449                    .and_then(|v| v.as_table())
450                    .and_then(|t| package_config_from(t).ok())
451            })
452            .map_or_else(
453                || "this project".to_string(),
454                |p| format!("{}/{}", p.org, p.package),
455            );
456        self.ranges
457            .entry(spec.package.clone())
458            .or_default()
459            .insert((requirer, range.to_string()));
460        let org = spec.package.split('/').next().unwrap_or_default();
461        let registry = self.client.route(org);
462        self.used_registries.insert(registry.clone());
463        let locked = self.existing.package(&spec.package).cloned();
464        if let Some(other) = locked
465            .as_ref()
466            .and_then(|p| parse_registry_source(&p.source))
467            && other != registry
468        {
469            return Err(fail(
470                crate::registry::SOURCE_MISMATCH,
471                format!(
472                    "`bynk.lock` locks `{}` to the registry `{other}`, but its organisation `{org}` now routes to `{registry}`",
473                    spec.package
474                ),
475            ));
476        }
477        if self.resolved.contains_key(&spec.package) {
478            // Chosen already this pass; a new range shows up in `ranges`, and
479            // the next pass chooses against it.
480            return Ok(());
481        }
482        let all: Vec<String> = self.ranges[&spec.package]
483            .iter()
484            .map(|(_, r)| r.clone())
485            .collect();
486        let refresh = self.opts.update.as_ref().is_some_and(|names| {
487            names.is_empty() || names.iter().any(|n| *n == spec.alias || *n == spec.package)
488        });
489        if let Some(names) = &self.opts.update {
490            for n in names {
491                if *n == spec.alias || *n == spec.package {
492                    self.updated.insert(n.clone());
493                }
494            }
495        }
496        let locked = locked.filter(|p| !refresh && parse_registry_source(&p.source).is_some());
497        let home = self.home()?;
498        let satisfies = |version: &str| {
499            semver::Version::parse(version).is_ok_and(|v| {
500                all.iter()
501                    .filter_map(|r| semver::VersionReq::parse(r).ok())
502                    .all(|r| r.matches(&v))
503            })
504        };
505        // The locked version, while it still satisfies every range and its
506        // tree is in the store: no network at all.
507        let fast = locked.as_ref().and_then(|p| {
508            let version = p.version.clone()?;
509            let checksum = p.checksum.clone()?;
510            let entry = store_dir(&home, &checksum)?;
511            (satisfies(&version) && entry.is_dir()).then_some((version, checksum, entry))
512        });
513        let (version, checksum, entry) = match fast {
514            Some(hit) => hit,
515            None => {
516                if self.opts.offline {
517                    return Err(fail(
518                        NOT_FETCHED,
519                        format!(
520                            "`{}` ({range} from `{registry}`) needs fetching, and `--offline` was given",
521                            spec.package
522                        ),
523                    ));
524                }
525                let lines = self.client.lines(&registry, &spec.package)?;
526                let toolchain = semver::Version::parse(crate::DRIVER_VERSION)
527                    .unwrap_or(semver::Version::new(0, 0, 0));
528                let locked_version = locked.as_ref().and_then(|p| p.version.clone());
529                let chosen = crate::registry::select::choose(
530                    &lines,
531                    &all,
532                    locked_version.as_deref(),
533                    &toolchain,
534                )
535                .map_err(|why| match why {
536                    crate::registry::select::NoVersion::Conflict => fail(
537                        VERSION_CONFLICT,
538                        format!(
539                            "no version of `{}` on `{registry}` satisfies every range: {}",
540                            spec.package,
541                            self.ranges[&spec.package]
542                                .iter()
543                                .map(|(who, r)| format!("`{r}` (from {who})"))
544                                .collect::<Vec<_>>()
545                                .join(", ")
546                        ),
547                    ),
548                    crate::registry::select::NoVersion::Toolchain(min) => fail(
549                        VERSION_CONFLICT,
550                        format!(
551                            "every version of `{}` matching {} requires bynk ≥ {min}",
552                            spec.package,
553                            all.join(", ")
554                        ),
555                    ),
556                    // #2330 (B): the lock names a version the registry took
557                    // down, and its tree isn't in the store (that took the
558                    // no-network path above and still builds).
559                    crate::registry::select::NoVersion::Withdrawn(version, reason) => self
560                        .client
561                        .withdrawn(&registry, &spec.package, &version, &reason, &spec.alias),
562                })?
563                .clone();
564                // The lock pins the locked version's tree: a line for that
565                // version naming another checksum (re-signed contents) is
566                // refused, with or without `--locked`.
567                if let Some(p) = &locked
568                    && p.version.as_deref() == Some(chosen.version.as_str())
569                    && let Some(pinned) = &p.checksum
570                    && *pinned != chosen.checksum
571                {
572                    return Err(fail(
573                        CHECKSUM_MISMATCH,
574                        format!(
575                            "`{}` {} on `{registry}` now names the tree {}, but `bynk.lock` pins {pinned} — a published version's contents changed",
576                            spec.package, chosen.version, chosen.checksum
577                        ),
578                    ));
579                }
580                if self.opts.locked && locked_version.as_deref() != Some(chosen.version.as_str()) {
581                    return Err(fail(
582                        LOCK_OUT_OF_DATE,
583                        format!(
584                            "`{}` would resolve to {} on `{registry}`, which isn't what `bynk.lock` says, and `--locked` was given",
585                            spec.package, chosen.version
586                        ),
587                    ));
588                }
589                let fresh = !store_dir(&home, &chosen.checksum).is_some_and(|d| d.is_dir());
590                let entry = self.client.fetch(&registry, &chosen, &home)?;
591                if fresh {
592                    self.prepared
593                        .fetched
594                        .push(format!("{}@{}", spec.package, chosen.version));
595                }
596                (chosen.version.clone(), chosen.checksum.clone(), entry)
597            }
598        };
599        verify(&entry, &checksum, &spec.package)?;
600        let Some(doc) = read_manifest(&entry) else {
601            return Err(fail(
602                NOT_FETCHED,
603                format!("`{}` {version} has no `bynk.toml`", spec.package),
604            ));
605        };
606        let deps = specs(&doc, "dependencies");
607        if !self.record(
608            spec,
609            registry_source(&registry),
610            Some(checksum),
611            Some(version),
612            &deps,
613        )? {
614            return Ok(());
615        }
616        self.dirs.insert(spec.package.clone(), entry.clone());
617        for d in deps {
618            self.resolve(&entry, Declarer::Fetched, &d)?;
619        }
620        Ok(())
621    }
622
623    /// Record a resolved package. `Ok(false)` when it was already resolved
624    /// identically (its dependencies are walked once); a different source for
625    /// the same package is a version conflict.
626    fn record(
627        &mut self,
628        spec: &DependencySpec,
629        source: String,
630        checksum: Option<String>,
631        version: Option<String>,
632        deps: &[DependencySpec],
633    ) -> Result<bool, FetchError> {
634        if let Some(seen) = self.resolved.get(&spec.package) {
635            // Two directories for one path package is the compile's
636            // `duplicate_source` to report, with its fuller context.
637            if seen.source == source
638                || !(seen.source.starts_with("git+") || source.starts_with("git+"))
639            {
640                return Ok(false);
641            }
642            return Err(fail(
643                VERSION_CONFLICT,
644                format!(
645                    "the package `{}` is reached from two sources: `{}` and `{source}`",
646                    spec.package, seen.source
647                ),
648            ));
649        }
650        let mut dependencies: Vec<String> = deps
651            .iter()
652            .filter(|d| !matches!(d.source, DependencySource::Version(_)))
653            .map(|d| d.package.clone())
654            .collect::<BTreeSet<_>>()
655            .into_iter()
656            .collect();
657        dependencies.sort();
658        self.resolved.insert(
659            spec.package.clone(),
660            LockedPackage {
661                name: spec.package.clone(),
662                version,
663                source,
664                checksum,
665                dependencies,
666            },
667        );
668        Ok(true)
669    }
670}
671
672/// #2255: the npm packages every resolved dependency's adapters require, as
673/// the lock's `[[npm]]` rows: one row per `(package, range)`, its
674/// `required-by` the `org/package:adapter`s naming it. Every adapter counts,
675/// reached or not — the lock records what *could* enter a build.
676fn npm_requirements(dirs: &BTreeMap<String, PathBuf>, members: &[PathBuf]) -> Vec<LockedNpm> {
677    let mut rows: BTreeMap<(String, String), BTreeSet<String>> = BTreeMap::new();
678    for (name, dir) in dirs {
679        let Some(doc) = read_manifest(dir) else {
680            continue;
681        };
682        for root in bynk_project::packages::package_source_roots(dir, &doc) {
683            // The compile's own walker, so the lock sees exactly the files a
684            // build compiles.
685            let mut files = bynk_project::discover_bynk_files(&root, &[]).unwrap_or_default();
686            files.sort();
687            for file in files {
688                let Ok(text) = std::fs::read_to_string(&file) else {
689                    continue;
690                };
691                let Some((adapter, requires)) = adapter_requires(&text) else {
692                    continue;
693                };
694                for (package, range) in requires {
695                    rows.entry((package, range))
696                        .or_default()
697                        .insert(format!("{name}:{adapter}"));
698                }
699            }
700        }
701    }
702    let mut out: Vec<LockedNpm> = rows
703        .into_iter()
704        .map(|((package, range), by)| LockedNpm {
705            package,
706            range,
707            required_by: by.into_iter().collect(),
708            approved: false,
709            first_party: false,
710        })
711        .collect();
712    out.extend(first_party_rows(members));
713    out
714}
715
716/// Whether a project's manifest reaches `reach`: the opt-in a test double is
717/// chosen by, which no source declares (#3321).
718fn manifest_reaches(manifest: &toml::Table, reach: &bynk_check::firstparty::Reach) -> bool {
719    matches!(reach, bynk_check::firstparty::Reach::TestPostgresDouble)
720        && bynk_project::test_postgres_of(manifest) == bynk_project::TestPostgres::Pglite
721}
722
723/// ADR 0799 C: the toolchain's own npm dependencies a project uses, one
724/// `first-party` row each, required by `bynk-std`: those whose binding the
725/// project's own contexts reach ([`bynk_check::firstparty::FirstPartyNpm::reached_by`]).
726/// They never need approval. Like an adapter's, a row records what *could* enter
727/// a build.
728fn first_party_rows(members: &[PathBuf]) -> Vec<LockedNpm> {
729    let mut units = Vec::new();
730    let mut manifests = Vec::new();
731    for member in members {
732        let Some(doc) = read_manifest(member) else {
733            continue;
734        };
735        manifests.push(doc.clone());
736        for root in bynk_project::packages::package_source_roots(member, &doc) {
737            for file in bynk_project::discover_bynk_files(&root, &[]).unwrap_or_default() {
738                let text = std::fs::read_to_string(file).unwrap_or_default();
739                // A file that does not parse reaches nothing; the build reports it.
740                if let Ok(tokens) = bynk_syntax::lexer::tokenize(&text)
741                    && let Ok(unit) = bynk_syntax::parser::parse_unit(&tokens, &text)
742                {
743                    units.push(unit);
744                }
745            }
746        }
747    }
748    bynk_check::firstparty::FIRST_PARTY_NPM
749        .iter()
750        .filter(|d| {
751            units
752                .iter()
753                .any(|u| bynk_check::firstparty::unit_reaches(u, &d.reached_by))
754                || manifests.iter().any(|m| manifest_reaches(m, &d.reached_by))
755        })
756        .map(|d| LockedNpm {
757            package: d.package.to_string(),
758            range: d.version.to_string(),
759            required_by: vec!["bynk-std".to_string()],
760            approved: false,
761            first_party: true,
762        })
763        .collect()
764}
765
766/// #2296 (decisions A, C): settle each row's approval. A row the lock already
767/// approved, by `(package, range)`, stays approved — saying so when another
768/// adapter now requires it too. A row only path packages require is the
769/// author's own: it needs no approval and is left as it was, so a lock written
770/// before approvals existed reads back unchanged (and `--locked` still holds).
771/// Anything else is pending.
772fn approvals(
773    mut rows: Vec<LockedNpm>,
774    resolved: &BTreeMap<String, LockedPackage>,
775    existing: &Lock,
776    prepared: &mut Prepared,
777) -> Vec<LockedNpm> {
778    let own = |by: &str| {
779        let package = by.split(':').next().unwrap_or_default();
780        resolved
781            .get(package)
782            .is_some_and(|p| p.source.starts_with("path+"))
783    };
784    for row in &mut rows {
785        if row.first_party {
786            // The toolchain's own: visible in the lock, never gated.
787            continue;
788        }
789        let before = existing
790            .npm
791            .iter()
792            .find(|n| n.package == row.package && n.range == row.range);
793        if let Some(before) = before.filter(|b| b.approved) {
794            row.approved = true;
795            let added: Vec<&str> = row
796                .required_by
797                .iter()
798                .filter(|by| !before.required_by.contains(by))
799                .map(String::as_str)
800                .collect();
801            if !added.is_empty() {
802                prepared.warnings.push(format!(
803                    "the approved npm package `{}` {} is now also required by {}",
804                    row.package,
805                    row.range,
806                    added
807                        .iter()
808                        .map(|a| format!("`{a}`"))
809                        .collect::<Vec<_>>()
810                        .join(", ")
811                ));
812            }
813        } else if row.required_by.iter().all(|by| own(by)) {
814            // Never gated: the compile checks only fetched packages' adapters.
815        } else {
816            prepared.pending.push(row.clone());
817        }
818    }
819    rows
820}
821
822/// Refuse a git source that could run a command or reach outside the
823/// project (track §6.3): an option-shaped URL or revision, a transport that
824/// isn't `https`/`ssh` (or `file`, from the author's own manifests).
825fn check_source(url: &str, rev: &str, declarer: Declarer) -> Result<(), FetchError> {
826    if url.starts_with('-') || rev.starts_with('-') {
827        return Err(fail(
828            UNSAFE_SOURCE,
829            format!("the git source `{url}` at `{rev}` looks like a command-line option"),
830        ));
831    }
832    let lower = url.to_ascii_lowercase();
833    // `user@host:path` (scp-like) is git's rule: no `://`, and the first `:`
834    // comes before any `/`. Anything else with a scheme must be https or ssh.
835    let scp_like = !lower.contains("://")
836        && !lower.contains("::")
837        && lower.contains('@')
838        && lower
839            .find(':')
840            .is_some_and(|colon| lower.find('/').is_none_or(|slash| colon < slash));
841    let scheme_ok = lower.starts_with("https://") || lower.starts_with("ssh://") || scp_like;
842    let file = lower.starts_with("file://");
843    if file && declarer == Declarer::Fetched {
844        return Err(fail(
845            PATH_OUTSIDE_ROOT,
846            format!(
847                "a fetched package names the local git repository `{url}`, and a fetched package can't reach one"
848            ),
849        ));
850    }
851    if !(scheme_ok || file) {
852        return Err(fail(
853            UNSAFE_SOURCE,
854            format!("the git source `{url}` isn't an `https://`, `ssh://` or `user@host:path` URL"),
855        ));
856    }
857    Ok(())
858}
859
860/// `git` with the hardening every invocation carries.
861fn git(allow_file: bool) -> Command {
862    let mut cmd = bynk_driver::tools::git_command();
863    cmd.args(["-c", "protocol.allow=never"])
864        .args(["-c", "protocol.https.allow=always"])
865        .args(["-c", "protocol.ssh.allow=always"])
866        .args(["-c", "core.hooksPath=/dev/null"])
867        .args(["-c", "core.autocrlf=false"])
868        .args(["-c", "core.symlinks=false"])
869        .args(["-c", "submodule.recurse=false"])
870        .env("GIT_TERMINAL_PROMPT", "0")
871        .env_remove("GIT_DIR")
872        .env_remove("GIT_WORK_TREE");
873    if allow_file {
874        cmd.args(["-c", "protocol.file.allow=always"]);
875    }
876    cmd
877}
878
879fn run_git(mut cmd: Command, what: &str) -> Result<String, FetchError> {
880    let out = cmd.output().map_err(|e| {
881        fail(
882            GIT_FAILED,
883            format!("couldn't run `git` to {what}: {e} — is git installed? (`bynk doctor` checks)"),
884        )
885    })?;
886    if !out.status.success() {
887        return Err(fail(
888            GIT_FAILED,
889            format!(
890                "`git` failed to {what}: {}",
891                String::from_utf8_lossy(&out.stderr).trim()
892            ),
893        ));
894    }
895    Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
896}
897
898/// The bare clone of `url` in the cache, created or brought up to date.
899fn bare_clone(home: &Path, url: &str, allow_file: bool) -> Result<PathBuf, FetchError> {
900    let digest: [u8; 32] = Sha256::digest(url.as_bytes()).into();
901    let hex: String = digest.iter().map(|b| format!("{b:02x}")).collect();
902    let dir = home.join("git").join(hex);
903    if dir.join("HEAD").is_file() {
904        let mut cmd = git(allow_file);
905        cmd.arg("--git-dir")
906            .arg(&dir)
907            .args(["fetch", "--quiet", "--tags", "--force", "--"])
908            .arg(url)
909            .arg("+refs/heads/*:refs/heads/*");
910        run_git(cmd, &format!("fetch `{url}`"))?;
911        return Ok(dir);
912    }
913    std::fs::create_dir_all(dir.parent().unwrap())
914        .map_err(|e| fail(GIT_FAILED, format!("could not create the git cache: {e}")))?;
915    let tmp = dir.with_extension(format!("partial.{}", std::process::id()));
916    let _ = std::fs::remove_dir_all(&tmp);
917    let mut cmd = git(allow_file);
918    cmd.args([
919        "clone",
920        "--bare",
921        "--quiet",
922        "--no-recurse-submodules",
923        "--",
924    ])
925    .arg(url)
926    .arg(&tmp);
927    run_git(cmd, &format!("clone `{url}`"))?;
928    if let Err(e) = std::fs::rename(&tmp, &dir) {
929        // Another `bynk` placed it first: theirs is as good as ours.
930        let _ = std::fs::remove_dir_all(&tmp);
931        if !dir.join("HEAD").is_file() {
932            return Err(fail(
933                GIT_FAILED,
934                format!("could not place the clone of `{url}`: {e}"),
935            ));
936        }
937    }
938    Ok(dir)
939}
940
941/// The commit `rev` names in `url`.
942fn resolve_rev(home: &Path, url: &str, rev: &str, allow_file: bool) -> Result<String, FetchError> {
943    let dir = bare_clone(home, url, allow_file)?;
944    let mut cmd = git(allow_file);
945    cmd.arg("--git-dir")
946        .arg(&dir)
947        .args(["rev-parse", "--verify", "--quiet"])
948        .arg(format!("{rev}^{{commit}}"));
949    run_git(cmd, &format!("find `{rev}` in `{url}`")).map_err(|_| {
950        fail(
951            GIT_FAILED,
952            format!("`{url}` has no tag, branch or commit `{rev}`"),
953        )
954    })
955}
956
957/// Check `commit` of `url` out into the store, returning its checksum. An
958/// entry already there is left alone.
959fn fetch_into_store(
960    home: &Path,
961    url: &str,
962    commit: &str,
963    allow_file: bool,
964) -> Result<String, FetchError> {
965    let dir = bare_clone(home, url, allow_file)?;
966    // Per process, so two `bynk` runs fetching one commit never share (or
967    // delete) each other's checkout mid-hash.
968    let staging = staging_dir(home, commit);
969    std::fs::create_dir_all(&staging)
970        .map_err(|e| fail(GIT_FAILED, format!("could not stage `{url}`: {e}")))?;
971    let index = home
972        .join("store")
973        .join("staging")
974        .join(format!("{commit}.{}.index", std::process::id()));
975    let mut read = git(allow_file);
976    read.arg("--git-dir")
977        .arg(&dir)
978        .arg("--work-tree")
979        .arg(&staging)
980        .env("GIT_INDEX_FILE", &index)
981        .args(["read-tree", commit]);
982    run_git(read, &format!("read `{url}` at {commit}"))?;
983    let mut checkout = git(allow_file);
984    checkout
985        .arg("--git-dir")
986        .arg(&dir)
987        .arg("--work-tree")
988        .arg(&staging)
989        .env("GIT_INDEX_FILE", &index)
990        .args(["checkout-index", "--all", "--force"]);
991    run_git(checkout, &format!("check out `{url}` at {commit}"))?;
992    let _ = std::fs::remove_file(&index);
993    place_in_store(home, &staging, &format!("`{url}` at {commit}"), GIT_FAILED)
994}
995
996/// Remove a store entry (its files are read-only).
997pub(crate) fn remove_entry(dir: &Path) -> std::io::Result<()> {
998    let _ = make_writable(dir);
999    std::fs::remove_dir_all(dir)
1000}
1001
1002/// A fresh, per-process staging directory under the store for `tag`.
1003pub(crate) fn staging_dir(home: &Path, tag: &str) -> PathBuf {
1004    let staging = home
1005        .join("store")
1006        .join("staging")
1007        .join(format!("{tag}.{}", std::process::id()));
1008    let _ = make_writable(&staging);
1009    let _ = std::fs::remove_dir_all(&staging);
1010    staging
1011}
1012
1013/// Hash a staged tree and move it into the store under its checksum (made
1014/// read-only), returning the checksum. An identical entry already there —
1015/// placed by an earlier run, or by a concurrent one that won the rename — is
1016/// kept, and the staging copy discarded.
1017pub(crate) fn place_in_store(
1018    home: &Path,
1019    staging: &Path,
1020    what: &str,
1021    code: &'static str,
1022) -> Result<String, FetchError> {
1023    let checksum =
1024        tree_checksum(staging).map_err(|e| fail(code, format!("could not hash {what}: {e}")))?;
1025    let entry = store_dir(home, &checksum).expect("a checksum this module wrote");
1026    if entry.is_dir() {
1027        let _ = std::fs::remove_dir_all(staging);
1028    } else {
1029        std::fs::create_dir_all(entry.parent().unwrap())
1030            .map_err(|e| fail(code, format!("could not create the store: {e}")))?;
1031        match std::fs::rename(staging, &entry) {
1032            Ok(()) => {
1033                let _ = make_read_only(&entry);
1034            }
1035            // Another `bynk` placed the same tree first.
1036            Err(_) if entry.is_dir() => {
1037                let _ = std::fs::remove_dir_all(staging);
1038            }
1039            Err(e) => {
1040                return Err(fail(
1041                    code,
1042                    format!("could not place {what} in the store: {e}"),
1043                ));
1044            }
1045        }
1046    }
1047    Ok(checksum)
1048}
1049
1050/// Re-hash a store entry against its locked checksum.
1051fn verify(entry: &Path, checksum: &str, package: &str) -> Result<(), FetchError> {
1052    let got = tree_checksum(entry).map_err(|e| {
1053        fail(
1054            CHECKSUM_MISMATCH,
1055            format!("could not read the store entry for `{package}`: {e}"),
1056        )
1057    })?;
1058    if got != checksum {
1059        return Err(fail(
1060            CHECKSUM_MISMATCH,
1061            format!(
1062                "the store entry for `{package}` (`{}`) hashes to {got}, but `bynk.lock` says {checksum} — delete it and run `bynk fetch` (its files are read-only: clear that first, with `chmod -R u+w` or `attrib -r /s`)",
1063                entry.display()
1064            ),
1065        ));
1066    }
1067    Ok(())
1068}
1069
1070/// The canonical-tree checksum (decision C): every regular file under `dir`
1071/// except `.git`, in byte-wise sorted `/`-separated path order, each
1072/// contributing `path \0 length \0 bytes`. Symbolic links aren't files and
1073/// contribute nothing.
1074pub fn tree_checksum(dir: &Path) -> std::io::Result<String> {
1075    let mut files: Vec<(String, PathBuf)> = Vec::new();
1076    collect(dir, dir, &mut files)?;
1077    files.sort();
1078    let mut hasher = Sha256::new();
1079    for (rel, path) in files {
1080        let bytes = std::fs::read(&path)?;
1081        hasher.update(rel.as_bytes());
1082        hasher.update([0]);
1083        hasher.update(bytes.len().to_string().as_bytes());
1084        hasher.update([0]);
1085        hasher.update(&bytes);
1086    }
1087    let digest: [u8; 32] = hasher.finalize().into();
1088    Ok(checksum_of(&digest))
1089}
1090
1091/// #2274: every regular file under `dir` except `.git`, as `(/-separated
1092/// relative path, path)`, sorted byte-wise — what [`tree_checksum`] hashes,
1093/// and what a registry archive carries.
1094pub(crate) fn tree_files(dir: &Path) -> std::io::Result<Vec<(String, PathBuf)>> {
1095    let mut files = Vec::new();
1096    collect(dir, dir, &mut files)?;
1097    files.sort();
1098    Ok(files)
1099}
1100
1101fn collect(root: &Path, dir: &Path, out: &mut Vec<(String, PathBuf)>) -> std::io::Result<()> {
1102    for entry in std::fs::read_dir(dir)? {
1103        let entry = entry?;
1104        let path = entry.path();
1105        let kind = entry.file_type()?;
1106        if kind.is_dir() {
1107            if entry.file_name() == ".git" {
1108                continue;
1109            }
1110            collect(root, &path, out)?;
1111        } else if kind.is_file() {
1112            let rel: Vec<String> = path
1113                .strip_prefix(root)
1114                .unwrap_or(&path)
1115                .components()
1116                .map(|c| c.as_os_str().to_string_lossy().into_owned())
1117                .collect();
1118            out.push((rel.join("/"), path));
1119        }
1120    }
1121    Ok(())
1122}
1123
1124fn make_read_only(dir: &Path) -> std::io::Result<()> {
1125    for entry in std::fs::read_dir(dir)? {
1126        let entry = entry?;
1127        let path = entry.path();
1128        if entry.file_type()?.is_dir() {
1129            make_read_only(&path)?;
1130        } else {
1131            let mut perms = std::fs::metadata(&path)?.permissions();
1132            perms.set_readonly(true);
1133            std::fs::set_permissions(&path, perms)?;
1134        }
1135    }
1136    Ok(())
1137}
1138
1139#[allow(clippy::permissions_set_readonly_false)]
1140fn make_writable(dir: &Path) -> std::io::Result<()> {
1141    for entry in std::fs::read_dir(dir)? {
1142        let entry = entry?;
1143        let path = entry.path();
1144        if entry.file_type()?.is_dir() {
1145            make_writable(&path)?;
1146        } else {
1147            let mut perms = std::fs::metadata(&path)?.permissions();
1148            perms.set_readonly(false);
1149            std::fs::set_permissions(&path, perms)?;
1150        }
1151    }
1152    Ok(())
1153}
1154
1155pub(crate) fn read_manifest(dir: &Path) -> Option<toml::Table> {
1156    std::fs::read_to_string(dir.join("bynk.toml"))
1157        .ok()?
1158        .parse()
1159        .ok()
1160}
1161
1162pub(crate) fn specs(doc: &toml::Table, table: &'static str) -> Vec<DependencySpec> {
1163    doc.get(table)
1164        .and_then(|v| v.as_table())
1165        .and_then(|t| dependencies_from(table, t).ok())
1166        .unwrap_or_default()
1167}
1168
1169pub(crate) fn package_version(doc: &toml::Table) -> Option<String> {
1170    doc.get("package")
1171        .and_then(|v| v.as_table())
1172        .and_then(|t| package_config_from(t).ok())
1173        .and_then(|c| c.version)
1174}
1175
1176/// `target` relative to `base`, both made absolute first; `target` itself
1177/// when they share no root.
1178fn relative(base: &Path, target: &Path) -> PathBuf {
1179    let abs = |p: &Path| {
1180        let p = p.canonicalize().unwrap_or_else(|_| p.to_path_buf());
1181        std::path::absolute(&p).unwrap_or(p)
1182    };
1183    let (b, t) = (abs(base), abs(target));
1184    let bc: Vec<_> = b.components().collect();
1185    let tc: Vec<_> = t.components().collect();
1186    let common = bc.iter().zip(&tc).take_while(|(x, y)| x == y).count();
1187    if common == 0 {
1188        return t;
1189    }
1190    let mut out = PathBuf::new();
1191    for _ in common..bc.len() {
1192        out.push("..");
1193    }
1194    for c in &tc[common..] {
1195        out.push(c.as_os_str());
1196    }
1197    if out.as_os_str().is_empty() {
1198        out.push(".");
1199    }
1200    out
1201}
1202
1203pub(crate) fn write_atomically(path: &Path, text: &str) -> std::io::Result<()> {
1204    let tmp = path.with_extension("lock.tmp");
1205    std::fs::write(&tmp, text)?;
1206    std::fs::rename(&tmp, path)
1207}
1208
1209/// The checksum's store directory name, for messages and tests.
1210pub fn store_hex(checksum: &str) -> Option<String> {
1211    checksum_hex(checksum)
1212}
1213
1214#[cfg(test)]
1215mod tests {
1216    use super::*;
1217
1218    #[test]
1219    fn option_shaped_and_exotic_sources_are_refused() {
1220        for (url, rev) in [
1221            ("-uhttps://x", "v1"),
1222            ("https://x", "--upload-pack=evil"),
1223            ("ext::sh -c touch% /tmp/pwned", "v1"),
1224            ("fd::17", "v1"),
1225            ("http://plain.example/x", "v1"),
1226            ("http://u@h:80/x", "v1"),
1227            ("git://u@h:9418/x", "v1"),
1228        ] {
1229            assert_eq!(
1230                check_source(url, rev, Declarer::Own).unwrap_err().code,
1231                UNSAFE_SOURCE,
1232                "{url} {rev}"
1233            );
1234        }
1235        assert!(check_source("https://github.com/acme/x", "v1", Declarer::Own).is_ok());
1236        assert!(check_source("[email protected]:acme/x.git", "main", Declarer::Fetched).is_ok());
1237        assert!(check_source("file:///tmp/repo", "main", Declarer::Own).is_ok());
1238        assert_eq!(
1239            check_source("file:///tmp/repo", "main", Declarer::Fetched)
1240                .unwrap_err()
1241                .code,
1242            PATH_OUTSIDE_ROOT
1243        );
1244    }
1245
1246    #[test]
1247    fn the_tree_checksum_is_pinned() {
1248        let dir = std::env::temp_dir().join(format!("bynk-tree-hash-{}", std::process::id()));
1249        let _ = std::fs::remove_dir_all(&dir);
1250        std::fs::create_dir_all(dir.join("src")).unwrap();
1251        std::fs::create_dir_all(dir.join(".git")).unwrap();
1252        std::fs::write(dir.join("bynk.toml"), "[package]\nname = \"a/b\"\n").unwrap();
1253        std::fs::write(dir.join("src/x.bynk"), "commons x\n").unwrap();
1254        std::fs::write(dir.join(".git/HEAD"), "ignored").unwrap();
1255        // sha256 of `path \0 length \0 bytes`, per file, in path order.
1256        let mut h = Sha256::new();
1257        h.update(b"bynk.toml\x0023\x00[package]\nname = \"a/b\"\n");
1258        h.update(b"src/x.bynk\x0010\x00commons x\n");
1259        let want: [u8; 32] = h.finalize().into();
1260        assert_eq!(tree_checksum(&dir).unwrap(), checksum_of(&want));
1261        let _ = std::fs::remove_dir_all(&dir);
1262    }
1263}