lockdocs-core 0.7.5

Lockfile resolution, local doc sources, symbol extraction and BM25 search for lockdocs.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
//! Opt-in network fetch of one exact package version from its registry
//! (npm tarball, PyPI wheel or sdist, crates.io .crate, Go module proxy zip),
//! unpacked into the disk cache. Nothing here runs unless fetching is enabled.

use crate::locate::{python_source, tilde, Source};
use crate::{Dep, Eco};
use anyhow::{bail, Context, Result};
use std::io::Read;
use std::path::{Component, Path, PathBuf};

const MAX_DOWNLOAD: u64 = 64 * 1024 * 1024;
const MAX_FILE: u64 = 8 * 1024 * 1024;

fn agent() -> ureq::Agent {
    ureq::Agent::config_builder()
        .timeout_global(Some(std::time::Duration::from_secs(60)))
        .user_agent(concat!("lockdocs/", env!("CARGO_PKG_VERSION"), " (+https://github.com/SylphxAI/lockdocs)"))
        .build()
        .into()
}

fn get_bytes(url: &str) -> Result<Vec<u8>> {
    let mut res = agent().get(url).call().with_context(|| format!("GET {url}"))?;
    let mut buf = Vec::new();
    res.body_mut().as_reader().take(MAX_DOWNLOAD + 1).read_to_end(&mut buf)?;
    if buf.len() as u64 > MAX_DOWNLOAD {
        bail!("{url} is larger than {} MB", MAX_DOWNLOAD / 1024 / 1024);
    }
    Ok(buf)
}

fn get_json(url: &str) -> Result<serde_json::Value> {
    Ok(serde_json::from_slice(&get_bytes(url)?)?)
}

/// Where a fetched copy of `dep` is stored, keyed by the resolved source so a
/// package pinned to a private registry never shares a directory with the
/// public one of the same `name@version` (nor with another private registry's).
/// Two registries publishing the same version otherwise yield whichever copy
/// was fetched first.
fn slot(dep: &Dep, source: &str) -> PathBuf {
    let safe = format!("{}@{}", dep.name, dep.version).replace(['/', '\\', ':'], "+");
    let key = crate::cache::hash(&[dep.eco.as_str(), &dep.name, &dep.version, source]);
    crate::cache::dir().join("src").join(dep.eco.as_str()).join(format!("{safe}-{key}"))
}

/// The public default registry for a package's ecosystem.
fn public_default(dep: &Dep) -> &'static str {
    match dep.eco {
        Eco::Npm => "registry.npmjs.org",
        Eco::PyPI => "pypi.org",
        Eco::Cargo => "crates.io",
        Eco::Go => "proxy.golang.org",
    }
}

/// The source identity a fetch would resolve to: the private candidate the
/// user's configuration and lockfiles select, else the public default. Offline
/// and cheap; the plan is already read by the private path.
fn source_identity(dep: &Dep, root: Option<&Path>) -> String {
    let Some(root) = root else { return public_default(dep).into() };
    let plan = crate::private::plan(dep, root, &crate::private::Env::process());
    plan.candidates
        .first()
        .filter(|c| c.private)
        .map(|c| c.base.clone())
        .unwrap_or_else(|| public_default(dep).into())
}

/// Directory for a fetched package, for the public default source. Callers
/// that resolved a private source use [`fetched_dir_for`].
pub fn fetched_dir(dep: &Dep) -> PathBuf {
    slot(dep, public_default(dep))
}

/// Directory for a fetched `dep` read from `root`'s resolved source.
pub fn fetched_dir_for(dep: &Dep, root: Option<&Path>) -> PathBuf {
    let id = source_identity(dep, root);
    slot(dep, &id)
}

/// A previously fetched copy, if any (never touches the network). `root` lets
/// the lookup see the project's configured source, so a cached public copy is
/// never returned for a package whose lockfile pins a private registry.
pub fn cached_for(dep: &Dep, root: Option<&Path>) -> Option<Source> {
    if is_git(dep) {
        return None;
    }
    let dir = fetched_dir_for(dep, root);
    if dir.join(".lockdocs-complete").is_file() {
        return Some(source_for(dep, &dir));
    }
    None
}

fn source_for(dep: &Dep, dir: &Path) -> Source {
    let origin = match dep.eco {
        Eco::Npm => "registry.npmjs.org",
        Eco::PyPI => "pypi.org",
        Eco::Cargo => "crates.io",
        Eco::Go => "proxy.golang.org",
    };
    source_from(dep, dir, origin)
}

fn source_from(dep: &Dep, dir: &Path, origin: &str) -> Source {
    if dep.eco == Eco::PyPI {
        // A wheel unpacks to a site-packages layout with a dist-info RECORD.
        if let Some(di) = std::fs::read_dir(dir)
            .ok()
            .and_then(|rd| rd.flatten().map(|e| e.path()).find(|p| p.extension().is_some_and(|e| e == "dist-info")))
        {
            let mut s = python_source(dir, &di, dep.version.clone());
            s.label = format!("fetched from {origin} ({})", tilde(dir));
            s.fetched = true;
            return s;
        }
    }
    Source {
        dir: dir.to_path_buf(),
        files: None,
        metadata: None,
        version: dep.version.clone(),
        label: format!("fetched from {origin} ({})", tilde(dir)),
        fetched: true,
    }
}

/// Download and unpack `dep` if it is not cached yet.
pub fn is_git(dep: &Dep) -> bool {
    dep.from.ends_with("(git)")
}

/// Shared guard: a git checkout is not interchangeable with a registry release tag.
pub fn require_registry_origin(dep: &Dep) -> Result<()> {
    if is_git(dep) {
        bail!(
            "{} is a git dependency; use its resolved checkout files, not registry/release-tag docs",
            dep.id()
        );
    }
    Ok(())
}

pub fn fetch(dep: &Dep) -> Result<Source> {
    fetch_for(dep, None, false)
}

/// `fetch`, reading the project's private-source configuration when `root` is
/// given. Without `private` (lockdocs Pro), a package that needs a private
/// source fails with `private::PrivateRequired` and nothing is sent anywhere.
pub fn fetch_for(dep: &Dep, root: Option<&Path>, private: bool) -> Result<Source> {
    require_registry_origin(dep)?;
    if let Some(s) = cached_for(dep, root) {
        return Ok(s);
    }
    let dir = fetched_dir_for(dep, root);
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir)?;
    let mut skipped = None;
    if let Some(root) = root {
        match crate::private::fetch_into(dep, root, private, &dir) {
            Ok(crate::private::Outcome::Done { host }) => {
                std::fs::write(dir.join(".lockdocs-complete"), b"")?;
                return Ok(source_from(dep, &dir, &format!("private source {host}")));
            }
            Ok(crate::private::Outcome::UsePublic { skipped: s }) => skipped = s,
            Err(e) => {
                let _ = std::fs::remove_dir_all(&dir);
                return Err(e);
            }
        }
    }
    let r = match dep.eco {
        Eco::Npm => {
            let meta = get_json(&format!("https://registry.npmjs.org/{}/{}", dep.name.replace('/', "%2F"), dep.version))?;
            let url = meta
                .pointer("/dist/tarball")
                .and_then(|t| t.as_str())
                .context("npm: no tarball for this version")?;
            untar_gz(&get_bytes(url)?, &dir)
        }
        Eco::Cargo => {
            let url = format!("https://static.crates.io/crates/{0}/{0}-{1}.crate", dep.name, dep.version);
            untar_gz(&get_bytes(&url)?, &dir)
        }
        Eco::Go => {
            let m = crate::locate::go_escape(&dep.name);
            let v = crate::locate::go_escape(&dep.version);
            let prefix = format!("{}@{}/", dep.name, dep.version);
            unzip(&get_bytes(&format!("https://proxy.golang.org/{m}/@v/{v}.zip"))?, &dir, false, Some(&prefix))
        }
        Eco::PyPI => {
            let meta = get_json(&format!("https://pypi.org/pypi/{}/{}/json", dep.name, dep.version))?;
            let urls = meta.get("urls").and_then(|u| u.as_array()).cloned().unwrap_or_default();
            let pick = |kind: &str, pure: bool| {
                urls.iter().find(|u| {
                    u.get("packagetype").and_then(|p| p.as_str()) == Some(kind)
                        && (!pure || u.get("filename").and_then(|f| f.as_str()).is_some_and(|f| f.ends_with("-none-any.whl")))
                })
            };
            let chosen = pick("bdist_wheel", true)
                .or_else(|| pick("bdist_wheel", false))
                .or_else(|| pick("sdist", false))
                .context("pypi: no files for this version")?;
            let url = chosen.get("url").and_then(|u| u.as_str()).context("pypi: no url")?;
            // The advertised filename, not the URL: pypi serves artifacts from
            // files.pythonhosted.org behind a `?`-signed query string.
            let filename = chosen.get("filename").and_then(|f| f.as_str()).unwrap_or(url);
            let bytes = get_bytes(url)?;
            crate::private::pypi::unpack(filename, &bytes, &dir)
        }
    };
    if let Err(e) = r {
        let _ = std::fs::remove_dir_all(&dir);
        // The public registry does not have it, and a private source was configured
        // for it: the answer is "that needs Pro", not "not found".
        return Err(match skipped {
            Some(req) => req.into(),
            None => e,
        });
    }
    std::fs::write(dir.join(".lockdocs-complete"), b"")?;
    Ok(source_for(dep, &dir))
}

/// Keep only paths that stay inside the target; drop the first component
/// (`package/`, `name-1.0/`) of tarballs.
pub(crate) fn safe_rel(p: &Path, strip_first: bool) -> Option<PathBuf> {
    let mut out = PathBuf::new();
    for (i, c) in p.components().enumerate() {
        match c {
            Component::Normal(s) => {
                if i == 0 && strip_first {
                    continue;
                }
                out.push(s)
            }
            Component::CurDir => {}
            _ => return None,
        }
    }
    if out.as_os_str().is_empty() {
        None
    } else {
        Some(out)
    }
}

pub(crate) fn wanted(p: &Path) -> bool {
    let s = p.to_string_lossy().to_ascii_lowercase();
    if s.contains("node_modules/") || s.contains("/test/") || s.contains("/tests/") {
        return false;
    }
    let ext = p.extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).unwrap_or_default();
    matches!(
        ext.as_str(),
        "md" | "mdx" | "markdown" | "rst" | "txt" | "ts" | "mts" | "cts" | "js" | "mjs" | "cjs" | "py" | "pyi" | "rs" | "go" | "json" | "toml" | "mod" | ""
    ) || s.ends_with("metadata")
        || s.ends_with("record")
}

/// Zip-bomb guards: per file, total unpacked bytes, and entries examined.
#[derive(Clone, Copy)]
pub(crate) struct Limits {
    pub file: u64,
    pub total: u64,
    pub entries: usize,
}

pub(crate) const LIMITS: Limits = Limits {
    file: MAX_FILE,
    total: 256 * 1024 * 1024,
    entries: 100_000,
};

struct Budget {
    limits: Limits,
    total: u64,
    entries: usize,
}

impl Budget {
    fn new(limits: Limits) -> Budget {
        Budget { limits, total: 0, entries: 0 }
    }
    fn entry(&mut self) -> Result<()> {
        self.entries += 1;
        if self.entries > self.limits.entries {
            bail!("archive has more than {} entries", self.limits.entries);
        }
        Ok(())
    }
    /// Read one member without trusting its declared size.
    fn read(&mut self, r: &mut dyn Read) -> Result<Option<Vec<u8>>> {
        let mut buf = Vec::new();
        r.take(self.limits.file + 1).read_to_end(&mut buf)?;
        if buf.len() as u64 > self.limits.file {
            return Ok(None);
        }
        self.total += buf.len() as u64;
        if self.total > self.limits.total {
            bail!("archive unpacks to more than {} MB", self.limits.total / 1024 / 1024);
        }
        Ok(Some(buf))
    }
}

fn write_member(dir: &Path, rel: PathBuf, buf: Vec<u8>) -> Result<()> {
    let out = dir.join(rel);
    if let Some(p) = out.parent() {
        std::fs::create_dir_all(p)?;
    }
    std::fs::write(out, buf)?;
    Ok(())
}

pub(crate) fn untar_gz(bytes: &[u8], dir: &Path) -> Result<()> {
    untar_gz_with(bytes, dir, LIMITS)
}

/// Like `untar_gz`, keeping only the files under `sub` (relative to the
/// archive's top folder) and unpacking them without that prefix.
pub(crate) fn untar_gz_sub(bytes: &[u8], dir: &Path, sub: Option<&str>) -> Result<()> {
    untar_gz_prefix(bytes, dir, LIMITS, sub)
}

fn untar_gz_with(bytes: &[u8], dir: &Path, limits: Limits) -> Result<()> {
    untar_gz_prefix(bytes, dir, limits, None)
}

fn untar_gz_prefix(bytes: &[u8], dir: &Path, limits: Limits, sub: Option<&str>) -> Result<()> {
    let mut budget = Budget::new(limits);
    let mut ar = tar::Archive::new(flate2::read::GzDecoder::new(bytes));
    for e in ar.entries()? {
        budget.entry()?;
        let mut e = e?;
        if !e.header().entry_type().is_file() || e.size() > limits.file {
            continue;
        }
        let path = e.path()?.to_path_buf();
        let Some(mut rel) = safe_rel(&path, true) else { continue };
        if let Some(sub) = sub {
            let Ok(inner) = rel.strip_prefix(sub) else { continue };
            rel = inner.to_path_buf();
            if rel.as_os_str().is_empty() {
                continue;
            }
        }
        if !wanted(&rel) {
            continue;
        }
        if let Some(buf) = budget.read(&mut e)? {
            write_member(dir, rel, buf)?;
        }
    }
    Ok(())
}

pub(crate) fn unzip(bytes: &[u8], dir: &Path, strip_first: bool, prefix: Option<&str>) -> Result<()> {
    unzip_with(bytes, dir, strip_first, prefix, LIMITS)
}

pub(crate) fn unzip_with(bytes: &[u8], dir: &Path, strip_first: bool, prefix: Option<&str>, limits: Limits) -> Result<()> {
    let mut budget = Budget::new(limits);
    let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes))?;
    if z.len() > limits.entries {
        bail!("archive has more than {} entries", limits.entries);
    }
    for i in 0..z.len() {
        budget.entry()?;
        let mut f = z.by_index(i)?;
        if !f.is_file() || f.size() > limits.file {
            continue;
        }
        let Some(mut name) = f.enclosed_name() else { continue };
        if let Some(pre) = prefix {
            let Some(rest) = f.name().strip_prefix(pre) else { continue };
            name = PathBuf::from(rest);
        }
        let Some(rel) = safe_rel(&name, strip_first) else { continue };
        if !wanted(&rel) {
            continue;
        }
        if let Some(buf) = budget.read(&mut f)? {
            write_member(dir, rel, buf)?;
        }
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    fn write(p: &Path, text: &str) {
        std::fs::create_dir_all(p.parent().unwrap()).unwrap();
        std::fs::write(p, text).unwrap();
    }

    #[test]
    fn rejects_escaping_paths() {
        assert_eq!(safe_rel(Path::new("package/README.md"), true), Some(PathBuf::from("README.md")));
        assert_eq!(safe_rel(Path::new("package/../../etc/passwd"), true), None);
        assert_eq!(safe_rel(Path::new("/abs/x"), false), None);
    }

    #[test]
    fn two_sources_publishing_the_same_version_do_not_share_a_cache_dir() {
        // The public default and each configured private registry are distinct
        // sources: two registries publishing the same name@version must not
        // return the copy fetched first. Keying on the resolved source keeps
        // them apart, and a cache written for one source is invisible to another.
        let dep = Dep {
            eco: Eco::PyPI,
            name: "acme-lib".into(),
            version: "2.0.0".into(),
            direct: true,
            from: "uv.lock".into(),
        };
        let craft = tempfile::tempdir().unwrap();
        write(
            &craft.path().join("uv.lock"),
            "version = 1\n[[package]]\nname = \"acme-lib\"\nversion = \"2.0.0\"\nsource = { registry = \"https://craft.example/simple\" }\n",
        );
        let npm = tempfile::tempdir().unwrap();
        write(
            &npm.path().join("uv.lock"),
            "version = 1\n[[package]]\nname = \"acme-lib\"\nversion = \"2.0.0\"\nsource = { registry = \"https://npm.example/simple\" }\n",
        );
        let a = fetched_dir_for(&dep, Some(craft.path()));
        let b = fetched_dir_for(&dep, Some(npm.path()));
        let public = fetched_dir(&dep);
        assert_ne!(a, b, "two private registries shared a cache directory");
        assert_ne!(a, public, "a private registry shared the public cache directory");
        assert_ne!(b, public);
        // The public slot is the same whenever no private source applies.
        assert_eq!(fetched_dir(&dep), fetched_dir_for(&dep, None));
        // The same source resolves to the same directory across projects.
        let craft_again = tempfile::tempdir().unwrap();
        write(
            &craft_again.path().join("uv.lock"),
            &std::fs::read_to_string(craft.path().join("uv.lock")).unwrap(),
        );
        assert_eq!(a, fetched_dir_for(&dep, Some(craft_again.path())));
        // A cache written for one source is not returned for another.
        std::fs::create_dir_all(&a).unwrap();
        std::fs::write(a.join(".lockdocs-complete"), b"").unwrap();
        assert!(cached_for(&dep, Some(craft.path())).is_some());
        assert!(cached_for(&dep, Some(npm.path())).is_none());
        assert!(cached_for(&dep, None).is_none());
    }

    fn zip_of(files: &[(&str, Vec<u8>)]) -> Vec<u8> {
        let files: Vec<(&str, &[u8])> = files.iter().map(|(n, d)| (*n, d.as_slice())).collect();
        crate::private::testutil::zip(&files)
    }

    #[test]
    fn archive_bombs_are_rejected() {
        let dir = std::env::temp_dir().join(format!("lockdocs-bomb-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        let tiny = Limits {
            file: 1000,
            total: 2500,
            entries: 5,
        };
        // Highly compressible members: total unpacked size is capped.
        let big: Vec<(&str, Vec<u8>)> = vec![("a.md", vec![b'x'; 900]), ("b.md", vec![b'x'; 900]), ("c.md", vec![b'x'; 900])];
        let err = unzip_with(&zip_of(&big), &dir, false, None, tiny).unwrap_err();
        assert!(err.to_string().contains("unpacks to more than"), "{err}");
        // Entry count is capped.
        let many: Vec<(String, Vec<u8>)> = (0..6).map(|i| (format!("f{i}.md"), b"x".to_vec())).collect();
        let many: Vec<(&str, Vec<u8>)> = many.iter().map(|(n, d)| (n.as_str(), d.clone())).collect();
        let err = unzip_with(&zip_of(&many), &dir, false, None, tiny).unwrap_err();
        assert!(err.to_string().contains("more than 5 entries"), "{err}");
        // An oversized member is skipped, the rest unpacks.
        let mixed: Vec<(&str, Vec<u8>)> = vec![("huge.md", vec![b'x'; 5000]), ("ok.md", b"hello".to_vec())];
        unzip_with(&zip_of(&mixed), &dir, false, None, tiny).unwrap();
        assert!(dir.join("ok.md").is_file() && !dir.join("huge.md").exists());
        // tar.gz: the same total cap.
        let mut tar = tar::Builder::new(flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default()));
        for n in ["package/a.md", "package/b.md", "package/c.md"] {
            let data = vec![b'y'; 900];
            let mut h = tar::Header::new_gnu();
            h.set_size(data.len() as u64);
            h.set_mode(0o644);
            h.set_cksum();
            tar.append_data(&mut h, n, &data[..]).unwrap();
        }
        let gz = tar.into_inner().unwrap().finish().unwrap();
        let err = untar_gz_with(&gz, &dir.join("t"), tiny).unwrap_err();
        assert!(err.to_string().contains("unpacks to more than"), "{err}");
        let _ = std::fs::remove_dir_all(&dir);
    }
}