use std::collections::BTreeMap;
use std::fmt;
use std::io::{self, Read as _};
use std::os::unix::fs::MetadataExt;
use std::path::{Path, PathBuf};
use std::time::Duration;
use rustix::fs::{Mode, OFlags};
use serde::Deserialize;
use crate::name::{GroupId, Name};
use crate::template::Template;
pub const DEFAULT_CONFIG_FILE: &str = "/etc/byssus/byssus.toml";
pub const DEFAULT_CONFIG_DIR: &str = "/etc/byssus/conf.d";
pub const DEFAULT_STATE_DIR: &str = "/var/lib/byssus";
pub const DEFAULT_RESYNC_INTERVAL_SECS: u64 = 60;
pub const MAX_RESYNC_INTERVAL_SECS: u64 = 86_400;
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct AbsPath(PathBuf);
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum AbsPathError {
#[error("path must be absolute")]
NotAbsolute,
#[error("path contains an empty component")]
EmptyComponent,
#[error("path contains a '{0}' component")]
DotComponent(String),
#[error("path contains a NUL byte")]
Nul,
}
impl AbsPath {
pub fn new(raw: &str) -> Result<Self, AbsPathError> {
if raw.contains('\0') {
return Err(AbsPathError::Nul);
}
let Some(rest) = raw.strip_prefix('/') else {
return Err(AbsPathError::NotAbsolute);
};
if rest.is_empty() {
return Ok(Self(PathBuf::from("/")));
}
let rest = rest.strip_suffix('/').unwrap_or(rest);
for component in rest.split('/') {
match component {
"" => return Err(AbsPathError::EmptyComponent),
"." | ".." => return Err(AbsPathError::DotComponent(component.to_owned())),
_ => {}
}
}
Ok(Self(PathBuf::from(format!("/{rest}"))))
}
#[must_use]
pub fn as_path(&self) -> &Path {
&self.0
}
#[must_use]
pub fn is_at_or_beneath(&self, other: &Self) -> bool {
self.0.starts_with(&other.0)
}
}
impl AbsPath {
#[must_use]
pub fn join_name(&self, name: &Name) -> Self {
Self(self.0.join(name.as_str()))
}
}
impl fmt::Display for AbsPath {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.display().fmt(f)
}
}
impl serde::Serialize for AbsPath {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(&self.0.to_string_lossy())
}
}
impl<'de> Deserialize<'de> for AbsPath {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let s = String::deserialize(deserializer)?;
Self::new(&s).map_err(serde::de::Error::custom)
}
}
impl AsRef<Path> for AbsPath {
fn as_ref(&self) -> &Path {
&self.0
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[allow(clippy::struct_excessive_bools)]
pub struct MountAttrs {
pub read_only: bool,
pub noexec: bool,
pub nosymfollow: bool,
}
impl Default for MountAttrs {
fn default() -> Self {
Self {
read_only: true,
noexec: true,
nosymfollow: false,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DaemonConfig {
pub user: Option<String>,
pub state_dir: AbsPath,
pub resync_interval: Option<Duration>,
}
impl Default for DaemonConfig {
fn default() -> Self {
Self {
user: None,
state_dir: AbsPath(PathBuf::from(DEFAULT_STATE_DIR)),
resync_interval: Some(Duration::from_secs(DEFAULT_RESYNC_INTERVAL_SECS)),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GroupConfig {
pub name: GroupId,
pub source_root: AbsPath,
pub source: Template,
pub target_root: AbsPath,
pub target: Template,
pub membership: AbsPath,
pub attrs: MountAttrs,
pub origin: PathBuf,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GroupSetConfig {
pub name: Name,
pub membership_root: AbsPath,
pub source_root: AbsPath,
pub source: Template,
pub target_root: AbsPath,
pub target: Template,
pub depth: usize,
pub attrs: MountAttrs,
pub origin: PathBuf,
}
impl GroupSetConfig {
pub fn group(&self, path: &[Name]) -> Result<GroupConfig, crate::template::InterpolateError> {
assert_eq!(
path.len(),
self.depth,
"group path does not match set depth"
);
let membership = path
.iter()
.fold(self.membership_root.clone(), |dir, level| {
dir.join_name(level)
});
Ok(GroupConfig {
name: GroupId::in_set(self.name.clone(), path.to_vec()),
source_root: self.source_root.clone(),
source: self.source.bind_levels(path)?,
target_root: self.target_root.clone(),
target: self.target.bind_levels(path)?,
membership,
attrs: self.attrs,
origin: self.origin.clone(),
})
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Config {
pub daemon: DaemonConfig,
pub groups: BTreeMap<Name, GroupConfig>,
pub group_sets: BTreeMap<Name, GroupSetConfig>,
pub files: Vec<PathBuf>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum Severity {
Warning,
Error,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Issue {
pub severity: Severity,
pub file: Option<PathBuf>,
pub group: Option<String>,
pub message: String,
}
impl fmt::Display for Issue {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if let Some(file) = &self.file {
write!(f, "{}: ", file.display())?;
}
if let Some(group) = &self.group {
write!(f, "group '{group}': ")?;
}
f.write_str(&self.message)
}
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("invalid configuration ({} error(s))", self.errors().count())]
pub struct LoadError {
pub issues: Vec<Issue>,
}
impl LoadError {
pub fn errors(&self) -> impl Iterator<Item = &Issue> {
self.issues.iter().filter(|i| i.severity == Severity::Error)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Loaded {
pub config: Config,
pub warnings: Vec<Issue>,
}
#[derive(Debug, Default)]
struct Issues(Vec<Issue>);
impl Issues {
fn push(
&mut self,
severity: Severity,
file: Option<&Path>,
group: Option<&str>,
message: impl Into<String>,
) {
self.0.push(Issue {
severity,
file: file.map(Path::to_path_buf),
group: group.map(str::to_owned),
message: message.into(),
});
}
fn error(&mut self, file: Option<&Path>, group: Option<&str>, message: impl Into<String>) {
self.push(Severity::Error, file, group, message);
}
fn warn(&mut self, file: Option<&Path>, group: Option<&str>, message: impl Into<String>) {
self.push(Severity::Warning, file, group, message);
}
fn has_errors(&self) -> bool {
self.0.iter().any(|i| i.severity == Severity::Error)
}
}
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct RawFile {
daemon: Option<RawDaemon>,
#[serde(default)]
groups: BTreeMap<String, RawGroup>,
#[serde(default)]
group_sets: BTreeMap<String, RawGroupSet>,
}
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct RawGroupSet {
membership_root: String,
source_root: String,
source: String,
target_root: String,
target: String,
read_only: Option<bool>,
noexec: Option<bool>,
nosymfollow: Option<bool>,
}
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct RawDaemon {
user: Option<String>,
state_dir: Option<String>,
resync_interval_secs: Option<u64>,
}
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct RawGroup {
source_root: String,
source: String,
target_root: String,
target: String,
membership: String,
read_only: Option<bool>,
noexec: Option<bool>,
nosymfollow: Option<bool>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OwnershipPolicy {
Enforce,
Warn,
}
#[derive(Debug, Clone)]
pub struct LoadOptions {
pub main_file: PathBuf,
pub main_file_required: bool,
pub config_dir: PathBuf,
pub config_dir_required: bool,
pub ownership: OwnershipPolicy,
pub trusted_uid: u32,
pub check_paths: bool,
pub fragment_changes: FragmentChanges,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct FragmentChanges {
pub add: Vec<PathBuf>,
pub remove: Vec<String>,
}
impl Default for LoadOptions {
fn default() -> Self {
Self {
main_file: PathBuf::from(DEFAULT_CONFIG_FILE),
main_file_required: false,
config_dir: PathBuf::from(DEFAULT_CONFIG_DIR),
config_dir_required: false,
ownership: OwnershipPolicy::Enforce,
trusted_uid: 0,
check_paths: true,
fragment_changes: FragmentChanges::default(),
}
}
}
pub fn load(options: &LoadOptions) -> Result<Loaded, LoadError> {
let mut issues = Issues::default();
let mut sources: Vec<(PathBuf, String, bool)> = Vec::new();
match read_checked(&options.main_file, options, true, &mut issues) {
Ok(Some(content)) => sources.push((options.main_file.clone(), content, true)),
Ok(None) if options.main_file_required => {
issues.error(Some(&options.main_file), None, "file does not exist");
}
Ok(None) => {}
Err(e) => issues.error(Some(&options.main_file), None, format!("cannot read: {e}")),
}
let changes = &options.fragment_changes;
let candidate_names = validate_candidates(changes, &mut issues);
let installed = match list_fragments(&options.config_dir) {
Ok(Some(paths)) => paths,
Ok(None) if options.config_dir_required => {
issues.error(Some(&options.config_dir), None, "directory does not exist");
Vec::new()
}
Ok(None) => Vec::new(),
Err(e) => {
issues.error(
Some(&options.config_dir),
None,
format!("cannot list directory: {e}"),
);
Vec::new()
}
};
for name in &changes.remove {
if !installed.iter().any(|p| file_name_of(p) == name.as_str()) {
issues.error(
Some(&options.config_dir),
None,
format!("cannot remove '{name}': no such installed fragment"),
);
}
}
let mut fragments: Vec<(PathBuf, bool)> = installed
.into_iter()
.filter(|p| {
let name = file_name_of(p);
!changes.remove.iter().any(|r| r == name) && !candidate_names.contains(&name.to_owned())
})
.map(|p| (p, false))
.collect();
fragments.extend(changes.add.iter().map(|p| (p.clone(), true)));
fragments.sort_by(|a, b| file_name_of(&a.0).cmp(file_name_of(&b.0)));
for (path, is_candidate) in fragments {
match read_checked(&path, options, !is_candidate, &mut issues) {
Ok(Some(content)) => sources.push((path, content, false)),
Ok(None) if is_candidate => issues.error(Some(&path), None, "file does not exist"),
Ok(None) => {}
Err(e) => issues.error(Some(&path), None, format!("cannot read: {e}")),
}
}
if sources.iter().any(|(_, _, main)| !main) {
check_ownership(&options.config_dir, options, true, &mut issues);
}
let parsed: Vec<(PathBuf, RawFile, bool)> = sources
.into_iter()
.filter_map(
|(path, content, main)| match toml::from_str::<RawFile>(&content) {
Ok(raw) => Some((path, raw, main)),
Err(e) => {
issues.error(Some(&path), None, format!("invalid TOML: {e}"));
None
}
},
)
.collect();
if parsed.is_empty() && !issues.has_errors() {
issues.warn(
None,
None,
"no configuration files found; no groups are defined",
);
}
let config = assemble(parsed, &mut issues);
if options.check_paths && !issues.has_errors() {
check_paths_exist(&config, &mut issues);
}
if issues.has_errors() {
Err(LoadError { issues: issues.0 })
} else {
Ok(Loaded {
config,
warnings: issues.0,
})
}
}
pub fn load_from_strs(documents: &[(&Path, &str, bool)]) -> Result<Loaded, LoadError> {
let mut issues = Issues::default();
let parsed = documents
.iter()
.filter_map(
|&(path, content, main)| match toml::from_str::<RawFile>(content) {
Ok(raw) => Some((path.to_path_buf(), raw, main)),
Err(e) => {
issues.error(Some(path), None, format!("invalid TOML: {e}"));
None
}
},
)
.collect();
let config = assemble(parsed, &mut issues);
if issues.has_errors() {
Err(LoadError { issues: issues.0 })
} else {
Ok(Loaded {
config,
warnings: issues.0,
})
}
}
fn read_checked(
path: &Path,
options: &LoadOptions,
include_parent: bool,
issues: &mut Issues,
) -> io::Result<Option<String>> {
let resolved = match std::fs::canonicalize(path) {
Ok(p) => p,
Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(None),
Err(e) => return Err(e),
};
let (Some(parent), Some(file_name)) = (resolved.parent(), resolved.file_name()) else {
return Err(io::Error::new(io::ErrorKind::InvalidInput, "not a file"));
};
let dir = rustix::fs::open(
parent,
OFlags::PATH | OFlags::DIRECTORY | OFlags::CLOEXEC,
Mode::empty(),
)?;
let flags =
OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::NONBLOCK | OFlags::NOCTTY | OFlags::CLOEXEC;
let mut file = match rustix::fs::openat(&dir, file_name, flags, Mode::empty()) {
Ok(fd) => std::fs::File::from(fd),
Err(rustix::io::Errno::NOENT) => return Ok(None),
Err(e) => return Err(e.into()),
};
let meta = file.metadata()?;
if !meta.is_file() {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"not a regular file",
));
}
check_owner_and_mode(path, options, "file", &meta, issues);
if include_parent {
let dir_meta = std::fs::File::from(dir).metadata()?;
let what = format!("containing directory {}", parent.display());
check_owner_and_mode(path, options, &what, &dir_meta, issues);
}
let mut content = String::new();
file.read_to_string(&mut content)?;
Ok(Some(content))
}
fn list_fragments(dir: &Path) -> io::Result<Option<Vec<PathBuf>>> {
let entries = match std::fs::read_dir(dir) {
Ok(entries) => entries,
Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(None),
Err(e) => return Err(e),
};
let mut paths = Vec::new();
for entry in entries {
let entry = entry?;
let file_name = entry.file_name();
let bytes = file_name.as_encoded_bytes();
if bytes.starts_with(b".") || !bytes.ends_with(b".toml") {
continue;
}
paths.push(entry.path());
}
paths.sort();
Ok(Some(paths))
}
fn file_name_of(path: &Path) -> &str {
path.file_name().and_then(|n| n.to_str()).unwrap_or("")
}
fn validate_candidates(changes: &FragmentChanges, issues: &mut Issues) -> Vec<String> {
let mut names = Vec::new();
for path in &changes.add {
let name = file_name_of(path);
#[allow(clippy::case_sensitive_file_extension_comparisons)]
let ignored_by_daemon =
name.is_empty() || name.starts_with('.') || !name.ends_with(".toml");
if ignored_by_daemon {
issues.error(
Some(path),
None,
"a drop-in fragment must be named <name>.toml and must not begin with '.'; otherwise the daemon ignores it",
);
}
if names.iter().any(|n| n == name) {
issues.error(
Some(path),
None,
format!("more than one candidate is named '{name}'"),
);
}
names.push(name.to_owned());
}
names
}
fn check_ownership(path: &Path, options: &LoadOptions, include_parent: bool, issues: &mut Issues) {
let severity = match options.ownership {
OwnershipPolicy::Enforce => Severity::Error,
OwnershipPolicy::Warn => Severity::Warning,
};
let resolved = match std::fs::canonicalize(path) {
Ok(p) => p,
Err(e) => {
issues.push(
severity,
Some(path),
None,
format!("cannot resolve path: {e}"),
);
return;
}
};
let mut to_check = vec![resolved.clone()];
if let Some(parent) = resolved.parent().filter(|_| include_parent) {
to_check.push(parent.to_path_buf());
}
for p in to_check {
let what = if p == resolved {
"file".to_owned()
} else {
format!("containing directory {}", p.display())
};
match std::fs::metadata(&p) {
Ok(meta) => check_owner_and_mode(path, options, &what, &meta, issues),
Err(e) => issues.push(
severity,
Some(path),
None,
format!("cannot stat {what}: {e}"),
),
}
}
}
fn check_owner_and_mode(
path: &Path,
options: &LoadOptions,
what: &str,
meta: &std::fs::Metadata,
issues: &mut Issues,
) {
let severity = match options.ownership {
OwnershipPolicy::Enforce => Severity::Error,
OwnershipPolicy::Warn => Severity::Warning,
};
if meta.uid() != options.trusted_uid {
issues.push(
severity,
Some(path),
None,
format!(
"{what} is owned by uid {}, expected uid {}",
meta.uid(),
options.trusted_uid
),
);
}
if meta.mode() & 0o022 != 0 {
issues.push(
severity,
Some(path),
None,
format!(
"{what} is group- or world-writable (mode {:04o})",
meta.mode() & 0o7777
),
);
}
}
fn assemble(files: Vec<(PathBuf, RawFile, bool)>, issues: &mut Issues) -> Config {
let mut config = Config::default();
let mut origins: BTreeMap<Name, PathBuf> = BTreeMap::new();
let mut set_origins: BTreeMap<Name, PathBuf> = BTreeMap::new();
for (path, raw, is_main) in files {
config.files.push(path.clone());
if let Some(daemon) = raw.daemon {
if is_main {
config.daemon = validate_daemon(daemon, &path, issues);
} else {
issues.error(
Some(&path),
None,
"[daemon] settings are only allowed in the main configuration file",
);
}
}
for (group_name, raw_group) in raw.groups {
let name = match Name::new(&group_name) {
Ok(n) => n,
Err(e) => {
issues.error(
Some(&path),
Some(&group_name),
format!("invalid group name: {e}"),
);
continue;
}
};
if let Some(first) = origins.get(&name) {
issues.error(
Some(&path),
Some(&group_name),
format!("group is already defined in {}", first.display()),
);
continue;
}
origins.insert(name.clone(), path.clone());
if let Some(group) = validate_group(name, &raw_group, &path, issues) {
config.groups.insert(group.name.path()[0].clone(), group);
}
}
for (set_name, raw_set) in raw.group_sets {
let label = format!("{set_name}/*");
let name = match Name::new(&set_name) {
Ok(n) => n,
Err(e) => {
issues.error(
Some(&path),
Some(&label),
format!("invalid group set name: {e}"),
);
continue;
}
};
if let Some(first) = set_origins.get(&name) {
issues.error(
Some(&path),
Some(&label),
format!("group set is already defined in {}", first.display()),
);
continue;
}
set_origins.insert(name.clone(), path.clone());
if let Some(set) = validate_group_set(name, &raw_set, &path, issues) {
config.group_sets.insert(set.name.clone(), set);
}
}
}
check_cross_group(&config, issues);
config
}
fn validate_daemon(raw: RawDaemon, path: &Path, issues: &mut Issues) -> DaemonConfig {
let mut daemon = DaemonConfig::default();
if let Some(user) = raw.user {
if is_valid_user_name(&user) {
daemon.user = Some(user);
} else {
issues.error(
Some(path),
None,
format!("daemon.user: invalid user name '{}'", user.escape_debug()),
);
}
}
if let Some(dir) = raw.state_dir {
match AbsPath::new(&dir) {
Ok(p) => daemon.state_dir = p,
Err(e) => issues.error(Some(path), None, format!("daemon.state_dir: {e}")),
}
}
if let Some(secs) = raw.resync_interval_secs {
if secs > MAX_RESYNC_INTERVAL_SECS {
issues.error(
Some(path),
None,
format!("daemon.resync_interval_secs: {secs} exceeds the maximum of {MAX_RESYNC_INTERVAL_SECS}"),
);
} else {
daemon.resync_interval = (secs != 0).then(|| Duration::from_secs(secs));
}
}
daemon
}
fn is_valid_user_name(user: &str) -> bool {
let body = user.strip_suffix('$').unwrap_or(user);
!body.is_empty()
&& user.len() <= 32
&& !body.starts_with('-')
&& body
.bytes()
.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'.' | b'-'))
}
fn validate_group(
name: Name,
raw: &RawGroup,
path: &Path,
issues: &mut Issues,
) -> Option<GroupConfig> {
let g = Some(name.as_str());
let abs = |issues: &mut Issues, field: &str, value: &str| {
AbsPath::new(value)
.map_err(|e| issues.error(Some(path), g, format!("{field}: {e}")))
.ok()
};
let source_root = abs(issues, "source_root", &raw.source_root);
let target_root = abs(issues, "target_root", &raw.target_root);
let membership = abs(issues, "membership", &raw.membership);
let template = |issues: &mut Issues, field: &str, value: &str| {
Template::parse(value)
.map_err(|e| issues.error(Some(path), g, format!("{field}: {e}")))
.ok()
};
let source = template(issues, "source", &raw.source);
let target = template(issues, "target", &raw.target);
let defaults = MountAttrs::default();
Some(GroupConfig {
source_root: source_root?,
source: source?,
target_root: target_root?,
target: target?,
membership: membership?,
attrs: MountAttrs {
read_only: raw.read_only.unwrap_or(defaults.read_only),
noexec: raw.noexec.unwrap_or(defaults.noexec),
nosymfollow: raw.nosymfollow.unwrap_or(defaults.nosymfollow),
},
origin: path.to_path_buf(),
name: GroupId::statically(name),
})
}
fn validate_group_set(
name: Name,
raw: &RawGroupSet,
path: &Path,
issues: &mut Issues,
) -> Option<GroupSetConfig> {
let label = format!("{name}/*");
let g = Some(label.as_str());
let abs = |issues: &mut Issues, field: &str, value: &str| {
AbsPath::new(value)
.map_err(|e| issues.error(Some(path), g, format!("{field}: {e}")))
.ok()
};
let membership_root = abs(issues, "membership_root", &raw.membership_root);
let source_root = abs(issues, "source_root", &raw.source_root);
let target_root = abs(issues, "target_root", &raw.target_root);
let template = |issues: &mut Issues, field: &str, value: &str| {
Template::parse_for_set(value)
.map_err(|e| issues.error(Some(path), g, format!("{field}: {e}")))
.ok()
};
let source = template(issues, "source", &raw.source);
let target = template(issues, "target", &raw.target);
let depth = match (&source, &target) {
(Some(source), Some(target)) => source.depth().max(target.depth()).max(1),
_ => 1,
};
if let Some(target) = &target {
for level in 0..depth {
if !target.has_level(level) {
issues.error(
Some(path),
g,
format!(
"target: {}",
crate::template::TemplateError::MissingLevel(Template::level_placeholder(
level
))
),
);
return None;
}
}
}
let defaults = MountAttrs::default();
Some(GroupSetConfig {
membership_root: membership_root?,
source_root: source_root?,
source: source?,
target_root: target_root?,
target: target?,
depth,
attrs: MountAttrs {
read_only: raw.read_only.unwrap_or(defaults.read_only),
noexec: raw.noexec.unwrap_or(defaults.noexec),
nosymfollow: raw.nosymfollow.unwrap_or(defaults.nosymfollow),
},
origin: path.to_path_buf(),
name,
})
}
struct MembershipArea<'a> {
label: String,
origin: &'a Path,
path: &'a AbsPath,
target_root: &'a AbsPath,
is_set: bool,
}
fn check_cross_group(config: &Config, issues: &mut Issues) {
let mut areas: Vec<MembershipArea<'_>> = config
.groups
.values()
.map(|g| MembershipArea {
label: g.name.to_string(),
origin: &g.origin,
path: &g.membership,
target_root: &g.target_root,
is_set: false,
})
.collect();
areas.extend(config.group_sets.values().map(|set| MembershipArea {
label: format!("{}/*", set.name),
origin: &set.origin,
path: &set.membership_root,
target_root: &set.target_root,
is_set: true,
}));
for area in &areas {
for other in &areas {
if area.path.is_at_or_beneath(other.target_root) {
let message = if area.label == other.label {
format!(
"membership directory {} must not be at or beneath target_root {}",
area.path, other.target_root
)
} else {
format!(
"membership directory {} must not be at or beneath target_root {} of group '{}'",
area.path, other.target_root, other.label
)
};
issues.error(Some(area.origin), Some(&area.label), message);
}
if area.label != other.label
&& other.is_set
&& (area.path.is_at_or_beneath(other.path)
|| other.path.is_at_or_beneath(area.path))
{
issues.error(
Some(area.origin),
Some(&area.label),
format!(
"membership directory {} overlaps membership_root {} of group set '{}'",
area.path, other.path, other.label
),
);
}
}
}
}
#[must_use]
pub fn check_paths(config: &Config) -> Vec<Issue> {
let mut issues = Issues::default();
check_paths_exist(config, &mut issues);
issues.0
}
fn check_paths_exist(config: &Config, issues: &mut Issues) {
let mut check = |owner: Option<(&Path, String)>, field: &str, path: &AbsPath| {
let origin = owner.as_ref().map_or_else(
|| config.files.first().map(PathBuf::as_path),
|(o, _)| Some(*o),
);
let name = owner.as_ref().map(|(_, label)| label.as_str());
match std::fs::metadata(path.as_path()) {
Ok(meta) if meta.is_dir() => {}
Ok(_) => issues.error(origin, name, format!("{field}: {path} is not a directory")),
Err(e) if e.kind() == io::ErrorKind::NotFound => {
issues.error(origin, name, format!("{field}: {path} does not exist"));
}
Err(e) if e.kind() == io::ErrorKind::PermissionDenied => {
issues.warn(origin, name, format!("{field}: cannot verify {path}: {e}"));
}
Err(e) => issues.error(origin, name, format!("{field}: cannot access {path}: {e}")),
}
};
check(None, "daemon.state_dir", &config.daemon.state_dir);
for group in config.groups.values() {
let owner = || Some((group.origin.as_path(), group.name.to_string()));
check(owner(), "source_root", &group.source_root);
check(owner(), "target_root", &group.target_root);
check(owner(), "membership", &group.membership);
}
for set in config.group_sets.values() {
let owner = || Some((set.origin.as_path(), format!("{}/*", set.name)));
check(owner(), "membership_root", &set.membership_root);
check(owner(), "source_root", &set.source_root);
check(owner(), "target_root", &set.target_root);
}
}
#[cfg(test)]
mod tests {
use std::fs;
use std::os::unix::fs::PermissionsExt;
use super::*;
const GROUP: &str = r#"
[groups.research]
source_root = "/srv/example/projects"
source = "{name}/workspace"
target_root = "/srv/example/groups/research/view"
target = "{name}"
membership = "/srv/example/membership/research"
"#;
fn main_only(content: &str) -> Result<Loaded, LoadError> {
load_from_strs(&[(Path::new("/etc/byssus/byssus.toml"), content, true)])
}
fn messages(err: &LoadError) -> Vec<String> {
err.errors().map(ToString::to_string).collect()
}
fn assert_error_contains(result: Result<Loaded, LoadError>, needle: &str) {
let err = result.expect_err("expected configuration to be rejected");
let msgs = messages(&err);
assert!(
msgs.iter().any(|m| m.contains(needle)),
"no error containing {needle:?} in {msgs:#?}"
);
}
#[test]
fn abs_path_validation() {
assert_eq!(AbsPath::new("/").unwrap().as_path(), Path::new("/"));
assert_eq!(AbsPath::new("/a/b/").unwrap().as_path(), Path::new("/a/b"));
assert_eq!(AbsPath::new("a"), Err(AbsPathError::NotAbsolute));
assert_eq!(AbsPath::new(""), Err(AbsPathError::NotAbsolute));
assert_eq!(AbsPath::new("/a//b"), Err(AbsPathError::EmptyComponent));
assert_eq!(AbsPath::new("/a//"), Err(AbsPathError::EmptyComponent));
assert_eq!(
AbsPath::new("/a/./b"),
Err(AbsPathError::DotComponent(".".into()))
);
assert_eq!(
AbsPath::new("/a/.."),
Err(AbsPathError::DotComponent("..".into()))
);
assert_eq!(AbsPath::new("/a\0"), Err(AbsPathError::Nul));
}
#[test]
fn abs_path_beneath_is_component_based() {
let a = AbsPath::new("/srv/view").unwrap();
assert!(AbsPath::new("/srv/view").unwrap().is_at_or_beneath(&a));
assert!(AbsPath::new("/srv/view/x").unwrap().is_at_or_beneath(&a));
assert!(!AbsPath::new("/srv/viewer").unwrap().is_at_or_beneath(&a));
assert!(!AbsPath::new("/srv").unwrap().is_at_or_beneath(&a));
}
#[test]
fn minimal_group_uses_defaults() {
let loaded = main_only(GROUP).unwrap();
assert!(loaded.warnings.is_empty());
let config = loaded.config;
assert_eq!(config.daemon, DaemonConfig::default());
let group = &config.groups[&Name::new("research").unwrap()];
assert_eq!(group.source.as_str(), "{name}/workspace");
assert_eq!(
group.source_root.as_path(),
Path::new("/srv/example/projects")
);
assert_eq!(group.attrs, MountAttrs::default());
assert!(group.attrs.read_only && group.attrs.noexec && !group.attrs.nosymfollow);
}
#[test]
fn full_configuration() {
let content = format!(
r#"
[daemon]
user = "byssus"
state_dir = "/var/lib/byssus-test"
resync_interval_secs = 0
{GROUP}
read_only = false
noexec = false
nosymfollow = true
"#
);
let config = main_only(&content).unwrap().config;
assert_eq!(config.daemon.user.as_deref(), Some("byssus"));
assert_eq!(
config.daemon.state_dir.as_path(),
Path::new("/var/lib/byssus-test")
);
assert_eq!(config.daemon.resync_interval, None);
let group = config.groups.values().next().unwrap();
assert_eq!(
group.attrs,
MountAttrs {
read_only: false,
noexec: false,
nosymfollow: true
}
);
}
#[test]
fn rejects_unknown_keys() {
assert_error_contains(main_only("[daemon]\nfoo = 1\n"), "unknown field");
assert_error_contains(
main_only(&format!("{GROUP}\nextra = true\n")),
"unknown field",
);
assert_error_contains(main_only("[other]\n"), "unknown field");
}
#[test]
fn rejects_missing_required_fields() {
assert_error_contains(
main_only("[groups.g]\nsource_root = \"/a\"\n"),
"missing field",
);
}
#[test]
fn rejects_invalid_values() {
let replace = |from: &str, to: &str| main_only(&GROUP.replace(from, to));
assert_error_contains(
replace("\"/srv/example/projects\"", "\"srv/example\""),
"source_root: path must be absolute",
);
assert_error_contains(
replace("\"{name}/workspace\"", "\"workspace\""),
"source: template must contain {name}",
);
assert_error_contains(
replace("target = \"{name}\"", "target = \"../{name}\""),
"target: template contains a '..' path component",
);
assert_error_contains(
replace("[groups.research]", "[groups.\".bad\"]"),
"invalid group name",
);
assert_error_contains(
main_only("[daemon]\nuser = \"bad:user\"\n"),
"invalid user name",
);
assert_error_contains(
main_only("[daemon]\nresync_interval_secs = 100000\n"),
"exceeds the maximum",
);
assert_error_contains(
main_only("[daemon]\nstate_dir = \"relative\"\n"),
"daemon.state_dir",
);
}
const SET: &str = r#"
[group_sets.research]
membership_root = "/var/lib/platform/membership/research"
source_root = "/data/orgs"
source = "{group}/projects/{name}/workspace"
target_root = "/data/orgs"
target = "{group}/groups/research/view/{name}"
"#;
#[test]
fn group_set_parses_and_binds_groups() {
let loaded = main_only(SET).unwrap();
let set = &loaded.config.group_sets[&Name::new("research").unwrap()];
assert_eq!(set.attrs, MountAttrs::default());
assert_eq!(set.depth, 1);
let group = set.group(&[Name::new("acme").unwrap()]).unwrap();
assert_eq!(group.name.to_string(), "research/acme");
assert_eq!(group.source.as_str(), "acme/projects/{name}/workspace");
assert_eq!(group.target.as_str(), "acme/groups/research/view/{name}");
assert_eq!(
group.membership.as_path(),
Path::new("/var/lib/platform/membership/research/acme")
);
assert_eq!(group.source_root, set.source_root);
}
#[test]
fn group_set_validation() {
assert_error_contains(
main_only(&SET.replace("{group}/groups/research/view/{name}", "groups/{name}")),
"target: template must contain {group}",
);
assert_error_contains(
main_only(&SET.replace("{group}/projects/{name}/workspace", "{group}/projects")),
"source: template must contain {name}",
);
assert_error_contains(
main_only(&GROUP.replace("\"{name}/workspace\"", "\"{group}/{name}\"")),
"{group} and {subgroup} are only allowed in group set templates",
);
assert_error_contains(
main_only(&SET.replace("[group_sets.research]", "[group_sets.\"a/b\"]")),
"invalid group set name",
);
assert_error_contains(main_only(&format!("{SET}\nextra = 1\n")), "unknown field");
assert_error_contains(
main_only(&SET.replace(
"\"/var/lib/platform/membership/research\"",
"\"/data/orgs/membership\"",
)),
"must not be at or beneath target_root",
);
let err = load_from_strs(&[
(Path::new("/a.toml"), SET, false),
(Path::new("/b.toml"), SET, false),
])
.unwrap_err();
assert!(messages(&err)[0].contains("group set is already defined in /a.toml"));
}
const SUBGROUP_SET: &str = r#"
[group_sets.projects]
membership_root = "/var/lib/platform/membership"
source_root = "/data/orgs"
source = "{group}/projects/{name}/workspace"
target_root = "/data/orgs"
target = "{group}/groups/{subgroup}/view/{name}"
"#;
#[test]
fn subgroup_set_parses_and_binds() {
let loaded = main_only(SUBGROUP_SET).unwrap();
let set = &loaded.config.group_sets[&Name::new("projects").unwrap()];
assert_eq!(set.depth, 2);
let path = [Name::new("acme").unwrap(), Name::new("research").unwrap()];
let group = set.group(&path).unwrap();
assert_eq!(group.name.to_string(), "projects/acme/research");
assert_eq!(group.source.as_str(), "acme/projects/{name}/workspace");
assert_eq!(group.target.as_str(), "acme/groups/research/view/{name}");
assert_eq!(
group.membership.as_path(),
Path::new("/var/lib/platform/membership/acme/research")
);
}
#[test]
fn subgroup_set_target_must_use_every_level() {
assert_error_contains(
main_only(
&SUBGROUP_SET
.replace(
"{group}/projects/{name}/workspace",
"{group}/{subgroup}/{name}",
)
.replace(
"{group}/groups/{subgroup}/view/{name}",
"{group}/view/{name}",
),
),
"target: template must contain {subgroup}",
);
assert_error_contains(
main_only(&SUBGROUP_SET.replace(
"{group}/groups/{subgroup}/view/{name}",
"groups/{subgroup}/view/{name}",
)),
"target: template must contain {group}",
);
}
#[test]
fn group_set_membership_root_must_not_overlap() {
let static_inside = GROUP.replace(
"\"/srv/example/membership/research\"",
"\"/var/lib/platform/membership/research/acme\"",
);
assert_error_contains(
main_only(&format!("{SET}{static_inside}")),
"overlaps membership_root /var/lib/platform/membership/research of group set 'research/*'",
);
let other_set = SET
.replace("[group_sets.research]", "[group_sets.builds]")
.replace("membership/research\"", "membership\"");
assert_error_contains(
main_only(&format!("{SET}{other_set}")),
"overlaps membership_root",
);
let builds = SET
.replace("[group_sets.research]", "[group_sets.builds]")
.replace("membership/research\"", "membership/builds\"");
let named_like_set = GROUP;
assert!(main_only(&format!("{SET}{builds}{named_like_set}")).is_ok());
}
#[test]
fn user_names() {
for ok in ["byssus", "_byssus", "svc-byssus", "a.b", "machine$", "u1"] {
assert!(is_valid_user_name(ok), "{ok}");
}
for bad in ["", "-x", "a b", "a:b", "$", &"a".repeat(33)] {
assert!(!is_valid_user_name(bad), "{bad}");
}
}
#[test]
fn reports_all_errors_at_once() {
let content = GROUP
.replace("\"/srv/example/projects\"", "\"x\"")
.replace("\"{name}\"", "\"y\"");
let err = main_only(&content).unwrap_err();
assert_eq!(err.errors().count(), 2, "{:#?}", err.issues);
}
#[test]
fn membership_beneath_target_root_rejected() {
let content = GROUP.replace(
"\"/srv/example/membership/research\"",
"\"/srv/example/groups/research/view/members\"",
);
assert_error_contains(main_only(&content), "must not be at or beneath target_root");
let other = r#"
[groups.other]
source_root = "/a"
source = "{name}"
target_root = "/srv/example/membership"
target = "{name}"
membership = "/b"
"#;
assert_error_contains(main_only(&format!("{GROUP}{other}")), "of group 'other'");
}
#[test]
fn fragments_and_duplicates() {
let frag_group = GROUP.replace("research", "builds");
let loaded = load_from_strs(&[
(
Path::new("/main.toml"),
"[daemon]\nuser = \"byssus\"\n",
true,
),
(Path::new("/conf.d/a.toml"), GROUP, false),
(Path::new("/conf.d/b.toml"), &frag_group, false),
])
.unwrap();
assert_eq!(loaded.config.groups.len(), 2);
assert_eq!(loaded.config.files.len(), 3);
let err = load_from_strs(&[
(Path::new("/conf.d/a.toml"), GROUP, false),
(Path::new("/conf.d/b.toml"), GROUP, false),
])
.unwrap_err();
assert!(messages(&err)[0].contains("already defined in /conf.d/a.toml"));
assert_error_contains(
load_from_strs(&[(Path::new("/conf.d/a.toml"), "[daemon]\n", false)]),
"only allowed in the main configuration file",
);
}
#[test]
fn shipped_examples_are_valid() {
let loaded = load_from_strs(&[
(
Path::new("examples/byssus.toml"),
include_str!("../examples/byssus.toml"),
true,
),
(
Path::new("examples/conf.d/research.toml"),
include_str!("../examples/conf.d/research.toml"),
false,
),
(
Path::new("examples/conf.d/projects.toml"),
include_str!("../examples/conf.d/projects.toml"),
false,
),
])
.unwrap();
assert!(loaded.warnings.is_empty());
assert_eq!(loaded.config.daemon.user.as_deref(), Some("byssus"));
assert!(
loaded
.config
.groups
.contains_key(&Name::new("research").unwrap())
);
assert_eq!(
loaded.config.group_sets[&Name::new("projects").unwrap()].depth,
2
);
}
#[test]
fn invalid_toml_reports_file() {
let err = load_from_strs(&[(Path::new("/conf.d/x.toml"), "[groups", false)]).unwrap_err();
assert!(messages(&err)[0].starts_with("/conf.d/x.toml: invalid TOML"));
}
struct Fixture {
dir: tempfile::TempDir,
}
impl Fixture {
fn new() -> Self {
let dir = tempfile::tempdir().unwrap();
fs::set_permissions(dir.path(), fs::Permissions::from_mode(0o755)).unwrap();
for sub in ["etc", "etc/conf.d", "projects", "view", "members", "state"] {
let p = dir.path().join(sub);
fs::create_dir(&p).unwrap();
fs::set_permissions(&p, fs::Permissions::from_mode(0o755)).unwrap();
}
Self { dir }
}
fn path(&self, rel: &str) -> PathBuf {
self.dir.path().join(rel)
}
fn group(&self, name: &str) -> String {
format!(
"[groups.{name}]\nsource_root = \"{}\"\nsource = \"{{name}}\"\ntarget_root = \"{}\"\ntarget = \"{{name}}\"\nmembership = \"{}\"\n",
self.path("projects").display(),
self.path("view").display(),
self.path("members").display()
)
}
fn write(&self, rel: &str, content: &str, mode: u32) {
let p = self.path(rel);
fs::write(&p, content).unwrap();
fs::set_permissions(&p, fs::Permissions::from_mode(mode)).unwrap();
}
fn options(&self) -> LoadOptions {
LoadOptions {
main_file: self.path("etc/byssus.toml"),
main_file_required: false,
config_dir: self.path("etc/conf.d"),
config_dir_required: false,
ownership: OwnershipPolicy::Enforce,
trusted_uid: rustix::process::getuid().as_raw(),
check_paths: true,
fragment_changes: FragmentChanges::default(),
}
}
fn state_dir_config(&self) -> String {
format!(
"[daemon]\nstate_dir = \"{}\"\n",
self.path("state").display()
)
}
}
#[test]
fn loads_main_and_sorted_fragments() {
let fx = Fixture::new();
fx.write("etc/byssus.toml", &fx.state_dir_config(), 0o644);
fx.write("etc/conf.d/20-b.toml", &fx.group("b"), 0o644);
fx.write("etc/conf.d/10-a.toml", &fx.group("a"), 0o644);
fx.write("etc/conf.d/.hidden.toml", "garbage", 0o644);
fx.write("etc/conf.d/notes.txt", "garbage", 0o644);
let loaded = load(&fx.options()).unwrap();
assert!(loaded.warnings.is_empty(), "{:#?}", loaded.warnings);
let files: Vec<_> = loaded
.config
.files
.iter()
.map(|p| p.file_name().unwrap().to_str().unwrap().to_owned())
.collect();
assert_eq!(files, ["byssus.toml", "10-a.toml", "20-b.toml"]);
assert_eq!(loaded.config.groups.len(), 2);
}
#[test]
fn missing_files() {
let fx = Fixture::new();
let loaded = load(&LoadOptions {
check_paths: false,
..fx.options()
})
.unwrap();
assert!(
loaded.warnings[0]
.message
.contains("no configuration files found")
);
let err = load(&LoadOptions {
main_file_required: true,
..fx.options()
})
.unwrap_err();
assert!(messages(&err)[0].contains("file does not exist"));
let err = load(&LoadOptions {
config_dir: fx.path("etc/missing.d"),
config_dir_required: true,
..fx.options()
})
.unwrap_err();
assert!(messages(&err)[0].contains("directory does not exist"));
}
#[test]
fn ownership_and_mode_enforced() {
let fx = Fixture::new();
fx.write("etc/byssus.toml", &fx.state_dir_config(), 0o664);
let err = load(&fx.options()).unwrap_err();
assert!(messages(&err)[0].contains("group- or world-writable (mode 0664)"));
let other_uid = fx.options().trusted_uid.wrapping_add(1);
let err = load(&LoadOptions {
trusted_uid: other_uid,
..fx.options()
})
.unwrap_err();
assert!(messages(&err).iter().any(|m| m.contains("expected uid")));
let loaded = load(&LoadOptions {
ownership: OwnershipPolicy::Warn,
..fx.options()
})
.unwrap();
assert!(loaded.warnings[0].message.contains("world-writable"));
}
#[test]
fn writable_containing_directory_rejected() {
let fx = Fixture::new();
fx.write("etc/conf.d/a.toml", &fx.group("a"), 0o644);
fs::set_permissions(fx.path("etc/conf.d"), fs::Permissions::from_mode(0o777)).unwrap();
let err = load(&LoadOptions {
check_paths: false,
..fx.options()
})
.unwrap_err();
assert!(
messages(&err)
.iter()
.any(|m| m.contains("conf.d is group- or world-writable"))
);
}
#[test]
fn fifo_fragment_rejected_without_blocking() {
let fx = Fixture::new();
rustix::fs::mknodat(
rustix::fs::CWD,
fx.path("etc/conf.d/a.toml"),
rustix::fs::FileType::Fifo,
Mode::from_raw_mode(0o644),
0,
)
.unwrap();
let err = load(&LoadOptions {
check_paths: false,
..fx.options()
})
.unwrap_err();
assert!(
messages(&err)
.iter()
.any(|m| m.contains("not a regular file"))
);
}
#[test]
fn symlinked_file_checked_where_it_resolves() {
let fx = Fixture::new();
fx.write("projects/real.toml", &fx.state_dir_config(), 0o644);
std::os::unix::fs::symlink(fx.path("projects/real.toml"), fx.path("etc/byssus.toml"))
.unwrap();
load(&fx.options()).unwrap();
fs::set_permissions(fx.path("projects"), fs::Permissions::from_mode(0o777)).unwrap();
let err = load(&fx.options()).unwrap_err();
assert!(
messages(&err)
.iter()
.any(|m| m.contains("projects is group- or world-writable"))
);
}
#[test]
fn candidate_fragments_add_replace_and_remove() {
let fx = Fixture::new();
fx.write("etc/byssus.toml", &fx.state_dir_config(), 0o644);
fx.write("etc/conf.d/acme.toml", &fx.group("acme"), 0o644);
fx.write("etc/conf.d/beta.toml", &fx.group("beta"), 0o644);
let staging = fx.dir.path().join("staging");
fs::create_dir(&staging).unwrap();
fs::set_permissions(&staging, fs::Permissions::from_mode(0o777)).unwrap();
let write_candidate = |name: &str, content: &str| {
let p = staging.join(name);
fs::write(&p, content).unwrap();
fs::set_permissions(&p, fs::Permissions::from_mode(0o644)).unwrap();
p
};
let with = |add: Vec<PathBuf>, remove: Vec<&str>| LoadOptions {
fragment_changes: FragmentChanges {
add,
remove: remove.into_iter().map(str::to_owned).collect(),
},
..fx.options()
};
let group_names = |loaded: &Loaded| {
loaded
.config
.groups
.keys()
.map(ToString::to_string)
.collect::<Vec<_>>()
};
let gamma = write_candidate("gamma.toml", &fx.group("gamma"));
let loaded = load(&with(vec![gamma], vec![])).unwrap();
assert_eq!(group_names(&loaded), ["acme", "beta", "gamma"]);
let acme2 = write_candidate("acme.toml", &fx.group("acme-new"));
let loaded = load(&with(vec![acme2], vec![])).unwrap();
assert_eq!(group_names(&loaded), ["acme-new", "beta"]);
let loaded = load(&with(vec![], vec!["beta.toml"])).unwrap();
assert_eq!(group_names(&loaded), ["acme"]);
let dup = write_candidate("dup.toml", &fx.group("acme"));
let err = load(&with(vec![dup], vec![])).unwrap_err();
assert!(
messages(&err)[0].contains("already defined"),
"{:#?}",
messages(&err)
);
let hidden = write_candidate(".hidden.toml", &fx.group("h"));
let err = load(&with(vec![hidden], vec![])).unwrap_err();
assert!(
messages(&err)
.iter()
.any(|m| m.contains("must be named <name>.toml"))
);
let err = load(&with(vec![staging.join("absent.toml")], vec![])).unwrap_err();
assert!(
messages(&err)
.iter()
.any(|m| m.contains("file does not exist"))
);
let err = load(&with(vec![], vec!["nope.toml"])).unwrap_err();
assert!(
messages(&err)
.iter()
.any(|m| m.contains("no such installed fragment"))
);
let broken = write_candidate("broken.toml", "[groups.x\n");
let err = load(&with(vec![broken], vec![])).unwrap_err();
assert!(messages(&err).iter().any(|m| m.contains("invalid TOML")));
let loose = write_candidate("loose.toml", &fx.group("loose"));
fs::set_permissions(&loose, fs::Permissions::from_mode(0o666)).unwrap();
let err = load(&with(vec![loose], vec![])).unwrap_err();
assert!(
messages(&err)
.iter()
.any(|m| m.contains("file is group- or world-writable"))
);
}
#[test]
fn nonexistent_paths_rejected() {
let fx = Fixture::new();
fx.write("etc/byssus.toml", &fx.state_dir_config(), 0o644);
let broken = fx.group("a").replace("/members\"", "/absent\"");
fx.write("etc/conf.d/a.toml", &broken, 0o644);
let err = load(&fx.options()).unwrap_err();
let msgs = messages(&err);
assert!(
msgs[0].contains("membership:") && msgs[0].contains("does not exist"),
"{msgs:#?}"
);
fx.write("projects/file", "", 0o644);
let broken = fx.group("a").replace("/projects\"", "/projects/file\"");
fx.write("etc/conf.d/a.toml", &broken, 0o644);
let err = load(&fx.options()).unwrap_err();
let msgs = messages(&err);
assert!(
msgs[0].contains("source_root:") && msgs[0].contains("is not a directory"),
"{msgs:#?}"
);
}
}