use std::io::Read;
use std::path::{Component, Path, PathBuf};
use sha2::{Digest, Sha256};
pub const ARCHIVE_NAME: &str = "noctis-feeds.tar.gz";
const RELEASES_URL: &str = "https://github.com/fDarkShadow/noctis/releases";
const MAX_UNPACKED_BYTES: u64 = 512 * 1024 * 1024;
pub const STAMP_FILE: &str = ".noctis-feeds";
pub fn own_tag() -> String {
format!("v{}", env!("CARGO_PKG_VERSION"))
}
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}")
}
}
#[derive(Debug)]
pub struct Installed {
pub dir: PathBuf,
pub tag: String,
pub sha256: String,
pub feeds: usize,
}
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}"
));
}
install(&archive, dir, tag, &actual)
}
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-";
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))?;
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 {
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()
));
}
remove_leftovers(dir, BACKUP_PREFIX);
Ok(Installed {
dir: dir.to_path_buf(),
tag: tag.to_string(),
sha256: sha256.to_string(),
feeds,
})
}
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();
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
}
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());
}
}
}
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; }
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(())
}
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()
}
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
}
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"));
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();
}
}