noctis 0.6.0

Open-source black-box vulnerability scanner: readable YAML checks that prove each bug on the live service, QoD-graded findings, REST API.
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
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
//! Local feed set: where it lives and how `noctis feeds update` installs it.
//!
//! The crates.io package is the engine only. Every GitHub Release carries the
//! repository's `tests/` tree as `noctis-feeds.tar.gz` (+ `.sha256`), with the
//! same layout as `/feeds` in the container image (`vulnerabilities/`, `common/`).
//! `noctis feeds update` downloads it, checks the digest and swaps it into the
//! feeds directory; `serve` then resolves relative `tests` entries against it.

use std::io::Read;
use std::path::{Component, Path, PathBuf};

use sha2::{Digest, Sha256};

/// Release asset holding the feed set.
pub const ARCHIVE_NAME: &str = "noctis-feeds.tar.gz";
const RELEASES_URL: &str = "https://github.com/fDarkShadow/noctis/releases";
/// Refuse archives that inflate past this (the feed set is ~10 MB unpacked).
const MAX_UNPACKED_BYTES: u64 = 512 * 1024 * 1024;
/// File written at the root of an installed feed set: the release it came from.
pub const STAMP_FILE: &str = ".noctis-feeds";

/// The release whose feeds match this binary.
pub fn own_tag() -> String {
    format!("v{}", env!("CARGO_PKG_VERSION"))
}

/// Feeds directory: `--feeds-dir`, else a non-empty `NOCTIS_FEEDS_DIR`, else
/// `$XDG_DATA_HOME/noctis/feeds`, `~/.local/share/noctis/feeds`, or
/// `%LOCALAPPDATA%\noctis\feeds` on Windows.
pub fn resolve_dir(explicit: Option<PathBuf>) -> Option<PathBuf> {
    explicit
        .filter(|p| !p.as_os_str().is_empty())
        .or_else(|| default_dir(|k| std::env::var_os(k)))
}

fn default_dir(env: impl Fn(&str) -> Option<std::ffi::OsString>) -> Option<PathBuf> {
    let non_empty = |k: &str| env(k).filter(|v| !v.is_empty()).map(PathBuf::from);
    if let Some(dir) = non_empty("NOCTIS_FEEDS_DIR") {
        return Some(dir);
    }
    let base = if cfg!(windows) {
        non_empty("LOCALAPPDATA")?
    } else if let Some(xdg) = non_empty("XDG_DATA_HOME") {
        xdg
    } else {
        non_empty("HOME")?.join(".local").join("share")
    };
    Some(base.join("noctis").join("feeds"))
}

fn archive_url(tag: &str, file: &str) -> String {
    if tag == "latest" {
        format!("{RELEASES_URL}/latest/download/{file}")
    } else {
        format!("{RELEASES_URL}/download/{tag}/{file}")
    }
}

/// What `update` installed.
#[derive(Debug)]
pub struct Installed {
    pub dir: PathBuf,
    pub tag: String,
    pub sha256: String,
    pub feeds: usize,
}

/// Download the feed archive of release `tag` (`vX.Y.Z` or `latest`) and install
/// it into `dir`, replacing what was there.
pub async fn update(dir: &Path, tag: &str) -> Result<Installed, String> {
    let client = reqwest::Client::builder()
        .user_agent(concat!("noctis/", env!("CARGO_PKG_VERSION")))
        .timeout(std::time::Duration::from_secs(120))
        .build()
        .map_err(|e| e.to_string())?;

    let fetch = |file: String| {
        let client = client.clone();
        let url = archive_url(tag, &file);
        async move {
            let resp = client
                .get(&url)
                .send()
                .await
                .map_err(|e| format!("{url}: {e}"))?;
            if resp.status() == reqwest::StatusCode::NOT_FOUND {
                return Err(format!(
                    "release {tag} has no {file} ({url} returned 404). Feed archives are \
                     attached to releases from the one that introduced `noctis feeds update` on; \
                     try `--tag latest`, or clone the repository and use its tests/ directory"
                ));
            }
            let resp = resp.error_for_status().map_err(|e| format!("{url}: {e}"))?;
            resp.bytes()
                .await
                .map(|b| b.to_vec())
                .map_err(|e| format!("{url}: {e}"))
        }
    };

    let archive = fetch(ARCHIVE_NAME.to_string()).await?;
    let digest_file = fetch(format!("{ARCHIVE_NAME}.sha256")).await?;
    let expected = parse_sha256_file(&String::from_utf8_lossy(&digest_file))
        .ok_or_else(|| format!("{ARCHIVE_NAME}.sha256 holds no sha256 digest"))?;
    let actual = hex_sha256(&archive);
    if actual != expected {
        return Err(format!(
            "{ARCHIVE_NAME} digest mismatch: expected {expected}, got {actual}"
        ));
    }

    // The tag the `latest` redirect resolved to is not known here; record what was asked.
    install(&archive, dir, tag, &actual)
}

/// Install a feed archive already on disk (offline / air-gapped hosts). When
/// `<archive>.sha256` sits next to it, the digest is checked against it.
pub fn update_from_file(dir: &Path, archive_path: &Path) -> Result<Installed, String> {
    let archive =
        std::fs::read(archive_path).map_err(|e| format!("{}: {e}", archive_path.display()))?;
    let actual = hex_sha256(&archive);
    let mut digest_path = archive_path.as_os_str().to_owned();
    digest_path.push(".sha256");
    let digest = match std::fs::read(&digest_path) {
        Ok(bytes) => Some(String::from_utf8_lossy(&bytes).into_owned()),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
        Err(e) => return Err(format!("{}: {e}", Path::new(&digest_path).display())),
    };
    if let Some(text) = digest {
        let expected = parse_sha256_file(&text)
            .ok_or_else(|| format!("{}: no sha256 digest", Path::new(&digest_path).display()))?;
        if actual != expected {
            return Err(format!(
                "{} digest mismatch: expected {expected}, got {actual}",
                archive_path.display()
            ));
        }
    }
    let label = archive_path
        .file_name()
        .map(|n| n.to_string_lossy().into_owned())
        .unwrap_or_else(|| "local archive".into());
    install(&archive, dir, &label, &actual)
}

const STAGING_PREFIX: &str = ".noctis-new-";
const BACKUP_PREFIX: &str = ".noctis-old-";

/// Unpack a verified archive into a staging directory inside `dir`, then swap
/// each of its top-level entries (`vulnerabilities/`, `common/`, …) into place.
///
/// Working inside `dir` rather than renaming `dir` itself keeps a mount point,
/// a symlinked directory and any other top-level entry the archive doesn't
/// carry (e.g. `custom/`) intact.
fn install(archive: &[u8], dir: &Path, tag: &str, sha256: &str) -> Result<Installed, String> {
    let io = |p: &Path, e: std::io::Error| format!("{}: {e}", p.display());
    std::fs::create_dir_all(dir).map_err(|e| io(dir, e))?;
    // Old backups stay until an install succeeds: after a crash between two
    // renames they may hold the only copy of an entry.
    remove_leftovers(dir, STAGING_PREFIX);

    let suffix = uuid::Uuid::new_v4().simple().to_string();
    let staging = dir.join(format!("{STAGING_PREFIX}{suffix}"));
    let backup = dir.join(format!("{BACKUP_PREFIX}{suffix}"));

    let unpacked = unpack(archive, &staging).and_then(|()| {
        let feeds = count_feeds(&staging.join("vulnerabilities"));
        if feeds == 0 {
            return Err(format!(
                "{ARCHIVE_NAME} holds no vulnerabilities/*.yaml feed"
            ));
        }
        std::fs::write(
            staging.join(STAMP_FILE),
            format!("{tag}\nsha256 {sha256}\n"),
        )
        .map_err(|e| e.to_string())?;
        Ok(feeds)
    });
    let feeds = match unpacked {
        Ok(n) => n,
        Err(e) => {
            let _ = std::fs::remove_dir_all(&staging);
            return Err(e);
        }
    };

    let swapped = swap_in(&staging, dir, &backup);
    let _ = std::fs::remove_dir_all(&staging);
    if let Err(e) = swapped {
        // A failed restore leaves an old entry parked in `backup`: keep it.
        let parked = std::fs::read_dir(&backup).map(|mut r| r.next().is_some());
        if matches!(parked, Ok(false)) {
            let _ = std::fs::remove_dir_all(&backup);
            return Err(e);
        }
        return Err(format!(
            "{e} (the previous feed set is kept in {})",
            backup.display()
        ));
    }
    // Success: this run's backup and any an interrupted run left behind.
    remove_leftovers(dir, BACKUP_PREFIX);

    Ok(Installed {
        dir: dir.to_path_buf(),
        tag: tag.to_string(),
        sha256: sha256.to_string(),
        feeds,
    })
}

/// Move every top-level entry of `staging` into `dir`, parking the entry it
/// replaces under `backup`. On failure, entries already swapped are put back.
fn swap_in(staging: &Path, dir: &Path, backup: &Path) -> Result<(), String> {
    let io = |p: &Path, e: std::io::Error| format!("{}: {e}", p.display());
    std::fs::create_dir_all(backup).map_err(|e| io(backup, e))?;
    let mut names: Vec<_> = std::fs::read_dir(staging)
        .map_err(|e| io(staging, e))?
        .filter_map(|e| e.ok().map(|e| e.file_name()))
        .collect();
    names.sort();

    // (name, whether an old entry was parked under `backup`)
    let mut done: Vec<(std::ffi::OsString, bool)> = Vec::new();
    let mut result = Ok(());
    for name in names {
        let live = dir.join(&name);
        let parked = backup.join(&name);
        let had_old = live.symlink_metadata().is_ok();
        if had_old {
            if let Err(e) = std::fs::rename(&live, &parked) {
                result = Err(io(&live, e));
                break;
            }
        }
        if let Err(e) = std::fs::rename(staging.join(&name), &live) {
            if had_old {
                let _ = std::fs::rename(&parked, &live);
            }
            result = Err(io(&live, e));
            break;
        }
        done.push((name, had_old));
    }
    if result.is_err() {
        for (name, had_old) in done.into_iter().rev() {
            let live = dir.join(&name);
            let _ = std::fs::rename(&live, staging.join(&name));
            if had_old {
                let _ = std::fs::rename(backup.join(&name), &live);
            }
        }
    }
    result
}

/// Remove the entries of `dir` whose name starts with `prefix` (staging or
/// backup directories, this run's or an interrupted earlier run's).
fn remove_leftovers(dir: &Path, prefix: &str) {
    let Ok(rd) = std::fs::read_dir(dir) else {
        return;
    };
    for e in rd.filter_map(|e| e.ok()) {
        let name = e.file_name().to_string_lossy().into_owned();
        if name.starts_with(prefix) {
            let _ = std::fs::remove_dir_all(e.path());
        }
    }
}

/// Extract a gzipped tarball into `dest`, accepting only plain files and
/// directories under relative, `..`-free paths.
fn unpack(archive: &[u8], dest: &Path) -> Result<(), String> {
    std::fs::create_dir_all(dest).map_err(|e| format!("{}: {e}", dest.display()))?;
    let gz = flate2::read::GzDecoder::new(archive);
    let mut tar = tar::Archive::new(gz.take(MAX_UNPACKED_BYTES + 1));
    let mut total: u64 = 0;
    for entry in tar.entries().map_err(|e| format!("{ARCHIVE_NAME}: {e}"))? {
        let mut entry = entry.map_err(|e| format!("{ARCHIVE_NAME}: {e}"))?;
        let path = entry
            .path()
            .map_err(|e| format!("{ARCHIVE_NAME}: {e}"))?
            .into_owned();
        let rel = safe_relative(&path)
            .ok_or_else(|| format!("{ARCHIVE_NAME}: refusing entry {}", path.display()))?;
        let kind = entry.header().entry_type();
        if rel.as_os_str().is_empty() {
            continue; // "./" itself
        }
        let target = dest.join(&rel);
        if kind.is_dir() {
            std::fs::create_dir_all(&target).map_err(|e| format!("{}: {e}", target.display()))?;
        } else if kind.is_file() {
            total += entry.header().size().unwrap_or(0);
            if total > MAX_UNPACKED_BYTES {
                return Err(format!(
                    "{ARCHIVE_NAME}: unpacks past {MAX_UNPACKED_BYTES} bytes"
                ));
            }
            if let Some(p) = target.parent() {
                std::fs::create_dir_all(p).map_err(|e| format!("{}: {e}", p.display()))?;
            }
            let mut out =
                std::fs::File::create(&target).map_err(|e| format!("{}: {e}", target.display()))?;
            std::io::copy(&mut entry, &mut out)
                .map_err(|e| format!("{}: {e}", target.display()))?;
        } else if matches!(
            kind,
            tar::EntryType::XGlobalHeader | tar::EntryType::XHeader
        ) {
            continue;
        } else {
            return Err(format!(
                "{ARCHIVE_NAME}: refusing non-regular entry {}",
                path.display()
            ));
        }
    }
    Ok(())
}

/// `path` with `.` components dropped, or `None` when it is absolute or climbs.
fn safe_relative(path: &Path) -> Option<PathBuf> {
    let mut out = PathBuf::new();
    for c in path.components() {
        match c {
            Component::Normal(p) => out.push(p),
            Component::CurDir => {}
            Component::ParentDir | Component::RootDir | Component::Prefix(_) => return None,
        }
    }
    Some(out)
}

fn count_feeds(dir: &Path) -> usize {
    let Ok(rd) = std::fs::read_dir(dir) else {
        return 0;
    };
    rd.filter_map(|e| e.ok())
        .map(|e| e.path())
        .map(|p| {
            if p.is_dir() {
                count_feeds(&p)
            } else {
                usize::from(matches!(
                    p.extension().and_then(|e| e.to_str()),
                    Some("yaml" | "yml")
                ))
            }
        })
        .sum()
}

/// First token of a `sha256sum` line, if it is a 64-char hex digest.
fn parse_sha256_file(text: &str) -> Option<String> {
    let tok = text.split_whitespace().next()?.to_ascii_lowercase();
    (tok.len() == 64 && tok.bytes().all(|b| b.is_ascii_hexdigit())).then_some(tok)
}

fn hex_sha256(data: &[u8]) -> String {
    Sha256::digest(data)
        .iter()
        .map(|b| format!("{b:02x}"))
        .collect()
}

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

    fn tmp() -> PathBuf {
        let d = std::env::temp_dir().join(format!("noctis-feeds-{}", uuid::Uuid::new_v4()));
        std::fs::create_dir_all(&d).unwrap();
        d
    }

    /// Build a .tar.gz from (path, Some(content) = file | None = dir) entries,
    /// writing raw header names so unsafe paths can be produced.
    fn targz(entries: &[(&str, Option<&str>)]) -> Vec<u8> {
        let gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::fast());
        let mut b = tar::Builder::new(gz);
        for (path, content) in entries {
            let mut h = tar::Header::new_gnu();
            let name = path.as_bytes();
            h.as_old_mut().name[..name.len()].copy_from_slice(name);
            match content {
                Some(c) => {
                    h.set_entry_type(tar::EntryType::Regular);
                    h.set_size(c.len() as u64);
                    h.set_mode(0o644);
                    h.set_cksum();
                    b.append(&h, c.as_bytes()).unwrap();
                }
                None => {
                    h.set_entry_type(tar::EntryType::Directory);
                    h.set_size(0);
                    h.set_mode(0o755);
                    h.set_cksum();
                    b.append(&h, &[][..]).unwrap();
                }
            }
        }
        b.into_inner().unwrap().finish().unwrap()
    }

    #[test]
    fn default_dir_prefers_xdg_then_home() {
        if cfg!(windows) {
            return;
        }
        let env = |pairs: Vec<(&'static str, &'static str)>| {
            move |k: &str| {
                pairs
                    .iter()
                    .find(|(n, _)| *n == k)
                    .map(|(_, v)| OsString::from(v))
            }
        };
        assert_eq!(
            default_dir(env(vec![("XDG_DATA_HOME", "/x"), ("HOME", "/h")])),
            Some(PathBuf::from("/x/noctis/feeds"))
        );
        assert_eq!(
            default_dir(env(vec![("XDG_DATA_HOME", ""), ("HOME", "/h")])),
            Some(PathBuf::from("/h/.local/share/noctis/feeds"))
        );
        assert_eq!(default_dir(env(vec![])), None);
    }

    #[test]
    fn noctis_feeds_dir_env_unless_empty() {
        let env = |v: &'static str| {
            move |k: &str| match k {
                "NOCTIS_FEEDS_DIR" => Some(OsString::from(v)),
                "HOME" => Some(OsString::from("/h")),
                "LOCALAPPDATA" => Some(OsString::from("/h")),
                _ => None,
            }
        };
        assert_eq!(default_dir(env("/f")), Some(PathBuf::from("/f")));
        assert_ne!(default_dir(env("")), Some(PathBuf::from("")));
    }

    #[test]
    fn explicit_dir_wins() {
        assert_eq!(
            resolve_dir(Some(PathBuf::from("/opt/feeds"))),
            Some(PathBuf::from("/opt/feeds"))
        );
    }

    #[test]
    fn archive_urls() {
        assert_eq!(
            archive_url("v0.5.0", ARCHIVE_NAME),
            "https://github.com/fDarkShadow/noctis/releases/download/v0.5.0/noctis-feeds.tar.gz"
        );
        assert_eq!(
            archive_url("latest", "x.sha256"),
            "https://github.com/fDarkShadow/noctis/releases/latest/download/x.sha256"
        );
    }

    #[test]
    fn sha256_file_parsing() {
        let d = "a".repeat(64);
        assert_eq!(
            parse_sha256_file(&format!("{d}  noctis-feeds.tar.gz\n")),
            Some(d.clone())
        );
        assert_eq!(parse_sha256_file(&d.to_uppercase()), Some(d));
        assert_eq!(parse_sha256_file("nothex"), None);
        assert_eq!(parse_sha256_file(""), None);
    }

    #[test]
    fn safe_relative_rejects_escapes() {
        assert_eq!(
            safe_relative(Path::new("./vulnerabilities/a.yaml")),
            Some(PathBuf::from("vulnerabilities/a.yaml"))
        );
        assert_eq!(safe_relative(Path::new("../etc/passwd")), None);
        assert_eq!(safe_relative(Path::new("a/../../b")), None);
        assert_eq!(safe_relative(Path::new("/etc/passwd")), None);
    }

    #[test]
    fn install_replaces_previous_set() {
        let root = tmp();
        let dir = root.join("feeds");
        std::fs::create_dir_all(dir.join("vulnerabilities")).unwrap();
        std::fs::write(dir.join("vulnerabilities/stale.yaml"), "old").unwrap();

        let archive = targz(&[
            ("./", None),
            ("./vulnerabilities/", None),
            ("./vulnerabilities/p/a.yaml", Some("uid: a")),
            ("./common/http_base.yaml", Some("steps: []")),
        ]);
        let got = install(&archive, &dir, "v9.9.9", "abc").unwrap();
        assert_eq!(got.feeds, 1);
        assert!(dir.join("vulnerabilities/p/a.yaml").is_file());
        assert!(dir.join("common/http_base.yaml").is_file());
        assert!(!dir.join("vulnerabilities/stale.yaml").exists());
        let stamp = std::fs::read_to_string(dir.join(STAMP_FILE)).unwrap();
        assert!(stamp.starts_with("v9.9.9\n"));
        // No staging / backup directory left behind.
        assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 3);
        std::fs::remove_dir_all(root).unwrap();
    }

    #[test]
    fn install_refuses_traversal_and_keeps_previous_set() {
        let root = tmp();
        let dir = root.join("feeds");
        std::fs::create_dir_all(dir.join("vulnerabilities")).unwrap();
        std::fs::write(dir.join("vulnerabilities/keep.yaml"), "old").unwrap();

        let archive = targz(&[
            ("vulnerabilities/p/a.yaml", Some("uid: a")),
            ("../escape.yaml", Some("x")),
        ]);
        let err = install(&archive, &dir, "v9.9.9", "abc").unwrap_err();
        assert!(err.contains("refusing entry"), "{err}");
        assert!(!root.join("escape.yaml").exists());
        assert!(!dir.join("escape.yaml").exists());
        assert!(dir.join("vulnerabilities/keep.yaml").is_file());
        assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 1);
        std::fs::remove_dir_all(root).unwrap();
    }

    #[test]
    fn install_keeps_foreign_entries_and_clears_leftovers() {
        let root = tmp();
        let dir = root.join("feeds");
        std::fs::create_dir_all(dir.join("custom")).unwrap();
        std::fs::write(dir.join("custom/mine.yaml"), "uid: mine").unwrap();
        std::fs::create_dir_all(dir.join(".noctis-new-deadbeef/x")).unwrap();
        std::fs::create_dir_all(dir.join(".noctis-old-deadbeef")).unwrap();

        let archive = targz(&[("vulnerabilities/p/a.yaml", Some("uid: a"))]);
        install(&archive, &dir, "v1", "abc").unwrap();
        assert!(dir.join("custom/mine.yaml").is_file());
        assert!(dir.join("vulnerabilities/p/a.yaml").is_file());
        let mut names: Vec<_> = std::fs::read_dir(&dir)
            .unwrap()
            .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
            .collect();
        names.sort();
        assert_eq!(names, [STAMP_FILE, "custom", "vulnerabilities"]);
        std::fs::remove_dir_all(root).unwrap();
    }

    #[cfg(unix)]
    #[test]
    fn install_through_a_symlinked_dir_writes_into_its_target() {
        let root = tmp();
        let target = root.join("data");
        std::fs::create_dir_all(&target).unwrap();
        let link = root.join("feeds");
        std::os::unix::fs::symlink(&target, &link).unwrap();
        let archive = targz(&[("vulnerabilities/p/a.yaml", Some("uid: a"))]);
        install(&archive, &link, "v1", "abc").unwrap();
        assert!(link.symlink_metadata().unwrap().file_type().is_symlink());
        assert!(target.join("vulnerabilities/p/a.yaml").is_file());
        std::fs::remove_dir_all(root).unwrap();
    }

    #[test]
    fn install_refuses_symlinks() {
        let root = tmp();
        let gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::fast());
        let mut b = tar::Builder::new(gz);
        let mut h = tar::Header::new_gnu();
        h.set_entry_type(tar::EntryType::Symlink);
        h.set_size(0);
        b.append_link(&mut h, "vulnerabilities/x.yaml", "/etc/passwd")
            .unwrap();
        let archive = b.into_inner().unwrap().finish().unwrap();
        let err = install(&archive, &root.join("feeds"), "v1", "abc").unwrap_err();
        assert!(err.contains("non-regular"), "{err}");
        std::fs::remove_dir_all(root).unwrap();
    }

    #[test]
    fn install_refuses_archive_without_feeds() {
        let root = tmp();
        let archive = targz(&[("README.md", Some("hi"))]);
        let err = install(&archive, &root.join("feeds"), "v1", "abc").unwrap_err();
        assert!(err.contains("no vulnerabilities"), "{err}");
        assert_eq!(std::fs::read_dir(root.join("feeds")).unwrap().count(), 0);
        std::fs::remove_dir_all(root).unwrap();
    }
}