use super::{keys, paths, store};
use crate::error::Result;
use serde::Serialize;
use std::path::Path;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Kind {
Unreadable,
UnknownKey,
ValueOutsideDomain,
OpenToOtherUsers,
NotNarrowedByThisSystem,
}
#[derive(Debug, Clone, Serialize)]
pub struct Finding {
pub kind: Kind,
pub subject: String,
pub detail: String,
pub remedy: String,
}
#[derive(Debug, Clone, Serialize)]
pub struct Report {
pub file: String,
pub file_exists: bool,
pub findings: Vec<Finding>,
}
impl Report {
#[must_use]
pub fn is_clean(&self) -> bool {
self.findings.is_empty()
}
}
pub fn run(override_dir: Option<&Path>) -> Result<Report> {
let file = paths::config_file(override_dir)?;
let file_exists = file.exists();
let mut findings = Vec::new();
let settings = match store::load(&file) {
Ok(settings) => settings,
Err(failure) => {
findings.push(Finding {
kind: Kind::Unreadable,
subject: file.display().to_string(),
detail: failure.message().to_owned(),
remedy: "remove the file to start from the built-in values, or \
rewrite it as stored settings"
.to_owned(),
});
return Ok(Report {
file: file.display().to_string(),
file_exists,
findings,
});
}
};
for (name, raw) in &settings {
inspect(name, raw, &mut findings);
}
inspect_permissions(&file, file_exists, &mut findings);
Ok(Report {
file: file.display().to_string(),
file_exists,
findings,
})
}
fn inspect(name: &str, raw: &str, findings: &mut Vec<Finding>) {
let Some(entry) = keys::spec(name) else {
findings.push(Finding {
kind: Kind::UnknownKey,
subject: name.to_owned(),
detail: format!("`{name}` is not a setting of this product"),
remedy: format!("run `config unset {name}` to drop it"),
});
return;
};
if let Err(failure) = keys::validate(entry.name, raw) {
findings.push(Finding {
kind: Kind::ValueOutsideDomain,
subject: entry.name.to_owned(),
detail: failure.message().to_owned(),
remedy: format!("accepted: {}", entry.domain.described()),
});
}
}
#[cfg(unix)]
fn inspect_permissions(file: &Path, file_exists: bool, findings: &mut Vec<Finding>) {
use std::os::unix::fs::PermissionsExt as _;
if !file_exists {
return;
}
let Ok(metadata) = std::fs::metadata(file) else {
return;
};
let mode = metadata.permissions().mode() & 0o777;
if mode != store::OWNER_ONLY {
findings.push(Finding {
kind: Kind::OpenToOtherUsers,
subject: file.display().to_string(),
detail: format!(
"the settings file carries mode {mode:04o} instead of {:04o}",
store::OWNER_ONLY
),
remedy: "narrow the file to its owner alone".to_owned(),
});
}
}
#[cfg(not(unix))]
fn inspect_permissions(file: &Path, file_exists: bool, findings: &mut Vec<Finding>) {
if file_exists {
findings.push(not_narrowed_by_this_system(file));
}
}
#[cfg(any(not(unix), test))]
pub(crate) fn not_narrowed_by_this_system(file: &Path) -> Finding {
Finding {
kind: Kind::NotNarrowedByThisSystem,
subject: file.display().to_string(),
detail: "this system has no file permission bits, so the settings file was stored \
without being narrowed to its owner"
.to_owned(),
remedy: "keep this file where the account's own directory is already closed to other \
users, because the product cannot close it here"
.to_owned(),
}
}
#[cfg(test)]
mod tests {
use super::*;
fn scratch() -> tempfile::TempDir {
tempfile::tempdir().expect("scratch directory")
}
#[test]
fn a_system_without_permission_bits_reports_that_it_narrowed_nothing() {
let finding = not_narrowed_by_this_system(Path::new("/somewhere/config.toml"));
assert_eq!(finding.kind, Kind::NotNarrowedByThisSystem);
assert!(
finding.subject.contains("config.toml"),
"the finding names the file it is about: {}",
finding.subject
);
assert!(
!finding.remedy.is_empty(),
"a finding a caller can do nothing about is still owed a next step"
);
}
#[test]
fn not_being_narrowed_is_a_different_finding_from_being_open() {
let finding = not_narrowed_by_this_system(Path::new("/somewhere/config.toml"));
assert_ne!(finding.kind, Kind::OpenToOtherUsers);
}
#[test]
fn a_location_with_nothing_stored_is_clean() {
let dir = scratch();
let report = run(Some(dir.path())).expect("examines");
assert!(report.is_clean());
assert!(!report.file_exists);
}
#[test]
fn settings_written_by_the_product_are_clean() {
let dir = scratch();
let file = paths::config_file(Some(dir.path())).expect("location");
store::store(&file, "output.format", "ndjson").expect("writes");
let report = run(Some(dir.path())).expect("examines");
assert!(
report.is_clean(),
"unexpected findings: {:?}",
report.findings
);
}
#[test]
fn a_stored_name_outside_the_registry_is_pointed_out() {
let dir = scratch();
let file = paths::config_file(Some(dir.path())).expect("location");
std::fs::create_dir_all(dir.path()).expect("directory");
std::fs::write(&file, "\"output.nonsense\" = \"1\"\n").expect("writes");
let report = run(Some(dir.path())).expect("examines");
let found = report
.findings
.iter()
.find(|finding| finding.kind == Kind::UnknownKey)
.expect("the unknown name must be pointed out");
assert_eq!(found.subject, "output.nonsense");
}
#[test]
fn a_stored_value_outside_its_domain_is_pointed_out() {
let dir = scratch();
let file = paths::config_file(Some(dir.path())).expect("location");
std::fs::create_dir_all(dir.path()).expect("directory");
std::fs::write(&file, "\"limits.retries\" = \"many\"\n").expect("writes");
let report = run(Some(dir.path())).expect("examines");
assert_eq!(report.findings[0].kind, Kind::ValueOutsideDomain);
}
#[test]
fn a_file_that_does_not_parse_is_pointed_out_as_unreadable() {
let dir = scratch();
let file = paths::config_file(Some(dir.path())).expect("location");
std::fs::create_dir_all(dir.path()).expect("directory");
std::fs::write(&file, "not settings at all\n").expect("writes");
let report = run(Some(dir.path())).expect("examines");
assert_eq!(report.findings.len(), 1);
assert_eq!(report.findings[0].kind, Kind::Unreadable);
}
#[cfg(unix)]
#[test]
fn a_file_open_to_other_users_is_pointed_out() {
use std::os::unix::fs::PermissionsExt as _;
let dir = scratch();
let file = paths::config_file(Some(dir.path())).expect("location");
store::store(&file, "output.format", "json").expect("writes");
std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o644)).expect("widens");
let report = run(Some(dir.path())).expect("examines");
assert_eq!(report.findings[0].kind, Kind::OpenToOtherUsers);
}
#[test]
fn every_problem_is_reported_at_once() {
let dir = scratch();
let file = paths::config_file(Some(dir.path())).expect("location");
std::fs::create_dir_all(dir.path()).expect("directory");
std::fs::write(
&file,
"\"output.nonsense\" = \"1\"\n\"limits.retries\" = \"many\"\n",
)
.expect("writes");
let report = run(Some(dir.path())).expect("examines");
assert!(
report.findings.len() >= 2,
"the examination stopped at the first problem: {:?}",
report.findings
);
}
}