use std::collections::HashMap;
use std::path::Path;
use ostrya_core::{KeyFile, RepoMode};
use crate::error::{Error, Result};
use crate::pattern::ReceiveSelector;
use crate::remotes_dir;
use crate::repo::{Repo, check_config_size};
use crate::summary::{remove_root_file_blocking, write_root_file_blocking};
const CORE: &str = "core";
const ARCHIVE: &str = "archive";
const EX_INTEGRITY: &str = "ex-integrity";
pub(crate) const EX_OSTRYA: &str = "ex-ostrya";
pub(crate) const REMOTES_CONFIG_DIR: &str = "remotes-config-dir";
const CONFIG_FILE: &str = "config";
#[derive(Debug, Clone)]
pub struct RepoConfig {
keyfile: KeyFile,
mode: RepoMode,
repo_version: i64,
collection_id: Option<String>,
remotes: Vec<String>,
remote_files: Vec<RemoteFile>,
}
#[derive(Debug, Clone)]
pub(crate) struct RemoteFile {
pub(crate) name: String,
pub(crate) keyfile: KeyFile,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum RemoteSource<'a> {
Config,
File(&'a str),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MinFreeSpace {
Percent(u32),
Size(SizeSpec),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SizeSpec {
pub value: u64,
pub unit: SizeUnit,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SizeUnit {
Mega,
Giga,
Tera,
}
impl SizeUnit {
pub fn multiplier(self) -> u64 {
match self {
SizeUnit::Mega => 1 << 20,
SizeUnit::Giga => 1 << 30,
SizeUnit::Tera => 1 << 40,
}
}
}
impl SizeSpec {
pub fn bytes(self) -> u64 {
self.value.saturating_mul(self.unit.multiplier())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SignVerify {
Off,
All,
Engines(Vec<String>),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Tristate {
No,
Maybe,
Yes,
}
impl Tristate {
fn parse(raw: &str) -> Option<Tristate> {
match raw {
"no" => Some(Tristate::No),
"maybe" => Some(Tristate::Maybe),
"yes" => Some(Tristate::Yes),
_ => None,
}
}
}
impl RepoConfig {
pub fn from_keyfile(keyfile: KeyFile) -> Result<RepoConfig> {
if !keyfile.has_group(CORE) {
return Err(Error::InvalidFormat("config has no [core] group".into()));
}
let repo_version = keyfile
.get_integer(CORE, "repo_version")?
.ok_or_else(|| Error::InvalidFormat("config [core] has no repo_version".into()))?;
if repo_version != 1 {
return Err(Error::InvalidFormat(format!(
"unsupported repository version {repo_version}"
)));
}
let mode_str = keyfile
.get_string(CORE, "mode")?
.ok_or_else(|| Error::InvalidFormat("config [core] has no mode".into()))?;
let mode = RepoMode::from_mode_str(&mode_str)
.ok_or_else(|| Error::InvalidFormat(format!("unknown repository mode '{mode_str}'")))?;
let collection_id = keyfile.get_string(CORE, "collection-id")?;
let remotes: Vec<String> = keyfile
.groups()
.filter_map(remote_group_name)
.map(str::to_owned)
.collect();
Ok(RepoConfig {
keyfile,
mode,
repo_version,
collection_id,
remotes,
remote_files: Vec::new(),
})
}
pub(crate) fn with_remote_files(
mut self,
base: &Path,
files: Vec<RemoteFile>,
) -> Result<RepoConfig> {
let mut seen: HashMap<String, Option<usize>> = self
.remotes
.iter()
.map(|name| (name.clone(), None))
.collect();
for (index, file) in files.iter().enumerate() {
for name in file.keyfile.groups().filter_map(remote_group_name) {
if let Some(other) = seen.insert(name.to_owned(), Some(index)) {
let other = match other {
None => CONFIG_FILE.to_owned(),
Some(other) => base.join(&files[other].name).display().to_string(),
};
return Err(Error::InvalidFormat(format!(
"remote \"{name}\" is defined in {other} and in {}",
base.join(&file.name).display()
)));
}
self.remotes.push(name.to_owned());
}
}
self.remote_files = files;
Ok(self)
}
pub fn parse(text: &str) -> Result<RepoConfig> {
RepoConfig::from_keyfile(KeyFile::parse(text)?)
}
pub fn mode(&self) -> RepoMode {
self.mode
}
pub fn repo_version(&self) -> i64 {
self.repo_version
}
pub fn collection_id(&self) -> Option<&str> {
self.collection_id.as_deref()
}
pub fn remotes(&self) -> impl Iterator<Item = &str> {
self.remotes.iter().map(String::as_str)
}
pub fn remote(&self, name: &str) -> Option<Remote<'_>> {
let group = remote_group(name);
let (keyfile, source) = if self.keyfile.has_group(&group) {
(&self.keyfile, RemoteSource::Config)
} else {
let file = self
.remote_files
.iter()
.find(|file| file.keyfile.has_group(&group))?;
(&file.keyfile, RemoteSource::File(&file.name))
};
Some(Remote {
keyfile,
group,
source,
})
}
pub(crate) fn into_remote_file(self, file: &str) -> Option<KeyFile> {
self.remote_files
.into_iter()
.find(|held| held.name == file)
.map(|held| held.keyfile)
}
pub(crate) fn add_remotes_config_dir(&self) -> Result<bool> {
Ok(self
.keyfile
.get_bool(CORE, "add-remotes-config-dir")?
.unwrap_or(true))
}
pub fn fsync(&self) -> Result<bool> {
Ok(self.keyfile.get_bool(CORE, "fsync")?.unwrap_or(true))
}
pub fn per_object_fsync(&self) -> Result<bool> {
Ok(self
.keyfile
.get_bool(CORE, "per-object-fsync")?
.unwrap_or(false))
}
pub fn locking(&self) -> Result<bool> {
Ok(self.keyfile.get_bool(CORE, "locking")?.unwrap_or(true))
}
pub fn lock_timeout_secs(&self) -> Result<i64> {
let secs = self
.keyfile
.get_integer(CORE, "lock-timeout-secs")?
.unwrap_or(300);
if secs < -1 {
return Err(Error::InvalidFormat(format!(
"lock-timeout-secs {secs} is below -1"
)));
}
Ok(secs)
}
pub fn tmp_expiry_secs(&self) -> Result<i64> {
Ok(self
.keyfile
.get_integer(CORE, "tmp-expiry-secs")?
.unwrap_or(86400))
}
pub fn tombstone_commits(&self) -> Result<bool> {
Ok(self
.keyfile
.get_bool(CORE, "tombstone-commits")?
.unwrap_or(false))
}
pub fn indexed_deltas(&self) -> Result<bool> {
Ok(self
.keyfile
.get_bool(CORE, "indexed-deltas")?
.unwrap_or(true))
}
pub fn disable_xattrs(&self) -> Result<bool> {
Ok(self
.keyfile
.get_bool(CORE, "disable-xattrs")?
.unwrap_or(false))
}
pub fn parent(&self) -> Result<Option<String>> {
self.keyfile.get_string(CORE, "parent").map_err(Error::from)
}
pub fn default_repo_finders(&self) -> Result<Vec<String>> {
Ok(self
.keyfile
.get_string_list(CORE, "default-repo-finders")?
.unwrap_or_else(|| vec!["config".to_owned(), "mount".to_owned()]))
}
pub fn min_free_space(&self) -> Result<MinFreeSpace> {
if let Some(raw) = self.keyfile.get_value(CORE, "min-free-space-size") {
let spec = parse_size(raw).ok_or_else(|| {
Error::InvalidFormat(format!("malformed min-free-space-size '{raw}'"))
})?;
return Ok(MinFreeSpace::Size(spec));
}
let percent = self
.keyfile
.get_integer(CORE, "min-free-space-percent")?
.unwrap_or(3);
if !(0..=100).contains(&percent) {
return Err(Error::InvalidFormat(format!(
"min-free-space-percent {percent} is out of the range 0-100"
)));
}
Ok(MinFreeSpace::Percent(percent as u32))
}
pub fn zlib_level(&self) -> Result<i64> {
Ok(self
.keyfile
.get_integer(ARCHIVE, "zlib-level")?
.unwrap_or(6))
}
pub fn keep_detached_related(&self) -> Result<bool> {
Ok(self
.keyfile
.get_bool(EX_OSTRYA, "keep-detached-related")?
.unwrap_or(true))
}
pub fn generate_composefs(&self) -> Result<bool> {
let on = self
.keyfile
.get_bool(EX_OSTRYA, "generate-composefs")?
.unwrap_or(false);
if on && self.mode.is_archive() {
return Err(Error::Unsupported(
"[ex-ostrya] generate-composefs=true in an archive repository".into(),
));
}
Ok(on)
}
pub fn gc_weak_references(&self) -> Result<Option<ReceiveSelector>> {
let selector = read_selector(&self.keyfile, EX_OSTRYA, "gc-weak-references")?;
if selector.as_ref().is_some_and(|s| !s.has_positive()) {
return Err(Error::InvalidFormat(format!(
"[{EX_OSTRYA}] gc-weak-references: the list holds no pattern without '!'"
)));
}
Ok(selector)
}
pub fn auto_update_summary(&self) -> Result<bool> {
let canonical = self.keyfile.get_bool(CORE, "auto-update-summary")?;
let alias = self.keyfile.get_bool(CORE, "commit-update-summary")?;
Ok(canonical.unwrap_or(false) || alias.unwrap_or(false))
}
pub fn composefs(&self) -> Result<Tristate> {
Ok(self
.tristate(EX_INTEGRITY, "composefs")?
.unwrap_or(Tristate::No))
}
pub fn fsverity(&self) -> Result<Tristate> {
if let Some(explicit) = self.tristate(EX_INTEGRITY, "fsverity")? {
return Ok(explicit);
}
Ok(match self.composefs()? {
Tristate::No => Tristate::No,
Tristate::Maybe | Tristate::Yes => Tristate::Maybe,
})
}
fn tristate(&self, group: &str, key: &str) -> Result<Option<Tristate>> {
match self.keyfile.get_string(group, key)? {
None => Ok(None),
Some(raw) => Tristate::parse(&raw).map(Some).ok_or_else(|| {
Error::InvalidFormat(format!("malformed [{group}] {key} value '{raw}'"))
}),
}
}
pub fn keyfile(&self) -> &KeyFile {
&self.keyfile
}
pub(crate) fn into_keyfile(self) -> KeyFile {
self.keyfile
}
}
impl Repo {
pub async fn write_config(&self, keyfile: &KeyFile) -> Result<()> {
let fsync = self.config().fsync()?;
let bytes = keyfile.to_string().into_bytes();
check_config_size(&bytes)?;
let names = remotes_dir::config_remote_names(keyfile);
self.write_locked(move |repo| {
remotes_dir::check_config_remotes(repo.repo_fd(), repo.remotes_dir(), &names)?;
write_root_file_blocking(repo.repo_fd(), CONFIG_FILE, &bytes, fsync)
})
.await
}
pub async fn remove_remote_keyring(&self, remote: &str) -> Result<()> {
if !valid_remote_name(remote) {
return Err(Error::InvalidInput(format!(
"invalid remote name: {remote}"
)));
}
let name = remote_keyring_name(remote);
self.write_locked(move |repo| remove_root_file_blocking(repo.repo_fd(), &name).map(drop))
.await
}
}
pub(crate) fn remote_keyring_name(remote: &str) -> String {
format!("{remote}.trustedkeys.gpg")
}
#[derive(Debug, Clone)]
pub struct Remote<'a> {
keyfile: &'a KeyFile,
group: String,
source: RemoteSource<'a>,
}
impl<'a> Remote<'a> {
pub(crate) fn view(keyfile: &'a KeyFile, group: String) -> Remote<'a> {
Remote {
keyfile,
group,
source: RemoteSource::Config,
}
}
pub fn source(&self) -> RemoteSource<'a> {
self.source
}
}
impl Remote<'_> {
pub fn url(&self) -> Result<Option<String>> {
self.string("url")
}
pub fn contenturl(&self) -> Result<Option<String>> {
self.string("contenturl")
}
pub fn metalink(&self) -> Result<Option<String>> {
self.string("metalink")
}
pub fn gpg_verify(&self) -> Result<bool> {
Ok(self.gpg_verify_key()?.unwrap_or(true))
}
pub(crate) fn gpg_verify_key(&self) -> Result<Option<bool>> {
Ok(self.keyfile.get_bool(&self.group, "gpg-verify")?)
}
pub fn gpg_verify_summary(&self) -> Result<bool> {
Ok(self
.keyfile
.get_bool(&self.group, "gpg-verify-summary")?
.unwrap_or(false))
}
pub fn gpgkeypath(&self) -> Result<Vec<String>> {
let Some(raw) = self.get("gpgkeypath") else {
return Ok(Vec::new());
};
let mut entries: Vec<String> = raw.split(';').map(str::to_owned).collect();
if entries.len() > 1 && entries.last().is_some_and(String::is_empty) {
entries.pop();
}
Ok(entries)
}
pub fn sign_verify(&self) -> Result<SignVerify> {
Ok(parse_sign_verify(self.string("sign-verify")?.as_deref()))
}
pub fn sign_verify_summary(&self) -> Result<SignVerify> {
Ok(parse_sign_verify(
self.string("sign-verify-summary")?.as_deref(),
))
}
pub fn verification_key(&self, engine: &str) -> Result<Option<String>> {
self.string(&format!("verification-{engine}-key"))
}
pub fn verification_file(&self, engine: &str) -> Result<Option<String>> {
self.string(&format!("verification-{engine}-file"))
}
pub fn trust(&self) -> Result<Option<String>> {
self.string("trust")
}
pub fn collection_id(&self) -> Result<Option<String>> {
self.string("collection-id")
}
pub fn mirrored_collection_ids(&self) -> Result<Vec<String>> {
let Some(ids) = self
.keyfile
.get_string_list(&self.group, MIRRORED_COLLECTION_IDS)?
else {
return Ok(Vec::new());
};
check_mirrored_collection_ids(self.collection_id()?.as_deref(), ids)
}
pub fn branches(&self) -> Result<Option<Vec<String>>> {
self.keyfile
.get_string_list(&self.group, "branches")
.map_err(Error::from)
}
pub fn pull_branches(&self) -> Result<Option<ReceiveSelector>> {
read_selector(self.keyfile, &self.group, "pull-branches")
}
pub fn tls_ca_path(&self) -> Result<Option<String>> {
self.string("tls-ca-path")
}
pub fn tls_client_cert_path(&self) -> Result<Option<String>> {
self.string("tls-client-cert-path")
}
pub fn tls_client_key_path(&self) -> Result<Option<String>> {
self.string("tls-client-key-path")
}
pub fn tls_permissive(&self) -> Result<bool> {
Ok(self
.keyfile
.get_bool(&self.group, "tls-permissive")?
.unwrap_or(false))
}
pub fn push_url(&self) -> Result<Option<String>> {
self.string("push-url")
}
pub fn push_branches(&self) -> Result<Option<ReceiveSelector>> {
read_selector(self.keyfile, &self.group, "push-branches")
}
pub fn ssh_command(&self) -> Result<Option<String>> {
self.string("ssh-command")
}
pub fn receive_command(&self) -> Result<Option<String>> {
self.string("receive-command")
}
pub fn push_token_file(&self) -> Result<Option<String>> {
self.string("push-token-file")
}
pub fn push_user(&self) -> Result<Option<String>> {
self.string("push-user")
}
pub fn pull_url(&self) -> Result<Option<String>> {
self.string("pull-url")
}
pub fn s3_region(&self) -> Result<Option<String>> {
self.string("s3-region")
}
pub fn s3_endpoint(&self) -> Result<Option<String>> {
self.string("s3-endpoint")
}
pub fn s3_addressing(&self) -> Result<Option<String>> {
self.string("s3-addressing")
}
pub fn s3_profile(&self) -> Result<Option<String>> {
self.string("s3-profile")
}
pub fn send_command(&self) -> Result<Option<String>> {
self.string("send-command")
}
pub fn proxy(&self) -> Result<Option<String>> {
self.string("proxy")
}
pub fn get(&self, key: &str) -> Option<&str> {
self.keyfile.get_value(&self.group, key)
}
pub(crate) fn keys(&self) -> impl Iterator<Item = &str> {
self.keyfile.keys(&self.group)
}
fn string(&self, key: &str) -> Result<Option<String>> {
self.keyfile
.get_string(&self.group, key)
.map_err(Error::from)
}
}
fn parse_sign_verify(raw: Option<&str>) -> SignVerify {
let Some(raw) = raw else {
return SignVerify::Off;
};
match raw {
"true" | "1" => return SignVerify::All,
"false" | "0" => return SignVerify::Off,
_ => {}
}
let engines: Vec<String> = raw
.split([',', ';'])
.filter(|name| !name.is_empty())
.map(str::to_owned)
.collect();
if engines.is_empty() {
return SignVerify::Off;
}
SignVerify::Engines(engines)
}
const MIRRORED_COLLECTION_IDS: &str = "mirrored-collection-ids";
pub fn check_mirrored_collection_ids(own: Option<&str>, ids: Vec<String>) -> Result<Vec<String>> {
if ids.is_empty() {
return Err(Error::InvalidFormat(format!(
"{MIRRORED_COLLECTION_IDS} holds no collection id"
)));
}
let mut out: Vec<String> = Vec::with_capacity(ids.len());
for id in ids {
if !ostrya_core::is_valid_collection_id(&id) {
return Err(Error::InvalidFormat(format!(
"{MIRRORED_COLLECTION_IDS}: invalid collection id: '{id}'"
)));
}
if Some(id.as_str()) == own {
return Err(Error::InvalidFormat(format!(
"{MIRRORED_COLLECTION_IDS}: {id} is the collection-id of the remote"
)));
}
if !out.contains(&id) {
out.push(id);
}
}
Ok(out)
}
fn read_selector(keyfile: &KeyFile, group: &str, key: &str) -> Result<Option<ReceiveSelector>> {
let Some(entries) = keyfile.get_string_list(group, key)? else {
return Ok(None);
};
ReceiveSelector::parse(entries.iter().map(String::as_str))
.map(Some)
.map_err(|err| match err {
Error::InvalidFormat(m) => Error::InvalidFormat(format!("[{group}] {key}: {m}")),
other => other,
})
}
#[doc(hidden)]
pub fn remote_group(name: &str) -> String {
format!("remote \"{name}\"")
}
pub fn valid_remote_name(name: &str) -> bool {
let mut chars = name.chars();
let Some(first) = chars.next() else {
return false;
};
if !(first.is_alphanumeric() || first == '_') {
return false;
}
name.chars()
.all(|c| c.is_alphanumeric() || matches!(c, '-' | '_' | '.'))
}
#[doc(hidden)]
pub fn remote_group_name(group: &str) -> Option<&str> {
group
.strip_prefix("remote \"")
.and_then(|rest| rest.strip_suffix('"'))
}
fn parse_size(raw: &str) -> Option<SizeSpec> {
let digits = raw
.strip_suffix("MB")
.map(|d| (d, SizeUnit::Mega))
.or_else(|| {
raw.strip_suffix("GB")
.map(|d| (d, SizeUnit::Giga))
.or_else(|| raw.strip_suffix("TB").map(|d| (d, SizeUnit::Tera)))
});
let (digits, unit) = digits?;
if digits.is_empty() || !digits.bytes().all(|b| b.is_ascii_digit()) {
return None;
}
let value = digits.parse::<u64>().ok()?;
Some(SizeSpec { value, unit })
}
#[cfg(test)]
mod tests {
use super::*;
use ostrya_core::Ref;
const ARCHIVE_CONFIG: &str = "[core]\nrepo_version=1\nmode=archive-z2\n";
#[test]
fn valid_remote_name_takes_the_names_the_tool_takes() {
for name in ["_", "1o", "a..b", "\u{e9}", "origin"] {
assert!(valid_remote_name(name), "{name:?}");
}
for name in ["", "-", ".", "..", "a b", "a/b", "a+b"] {
assert!(!valid_remote_name(name), "{name:?}");
}
}
#[test]
fn parses_core_mode_and_version() {
let cfg = RepoConfig::parse(ARCHIVE_CONFIG).unwrap();
assert_eq!(cfg.mode(), RepoMode::Archive);
assert_eq!(cfg.repo_version(), 1);
assert_eq!(cfg.collection_id(), None);
assert_eq!(cfg.remotes().count(), 0);
}
#[test]
fn rejects_unsupported_repo_version() {
let err = RepoConfig::parse("[core]\nrepo_version=2\nmode=bare\n").unwrap_err();
assert!(matches!(err, Error::InvalidFormat(_)));
assert!(err.to_string().contains("version 2"));
}
#[test]
fn rejects_missing_core_group_and_keys() {
assert!(RepoConfig::parse("[other]\nx=1\n").is_err());
assert!(RepoConfig::parse("[core]\nmode=bare\n").is_err());
assert!(RepoConfig::parse("[core]\nrepo_version=1\n").is_err());
}
#[test]
fn rejects_unknown_mode() {
let err = RepoConfig::parse("[core]\nrepo_version=1\nmode=bogus\n").unwrap_err();
assert!(err.to_string().contains("unknown repository mode 'bogus'"));
}
#[test]
fn reads_collection_id() {
let cfg = RepoConfig::parse("[core]\nrepo_version=1\nmode=bare\ncollection-id=org.ex.C\n")
.unwrap();
assert_eq!(cfg.collection_id(), Some("org.ex.C"));
}
#[test]
fn tunables_default_when_absent() {
let cfg = RepoConfig::parse(ARCHIVE_CONFIG).unwrap();
assert!(cfg.fsync().unwrap());
assert!(!cfg.per_object_fsync().unwrap());
assert!(cfg.locking().unwrap());
assert_eq!(cfg.lock_timeout_secs().unwrap(), 300);
assert_eq!(cfg.tmp_expiry_secs().unwrap(), 86400);
assert!(!cfg.disable_xattrs().unwrap());
assert_eq!(cfg.parent().unwrap(), None);
assert_eq!(
cfg.default_repo_finders().unwrap(),
vec!["config".to_owned(), "mount".to_owned()]
);
assert_eq!(cfg.zlib_level().unwrap(), 6);
assert_eq!(cfg.min_free_space().unwrap(), MinFreeSpace::Percent(3));
}
#[test]
fn tunables_read_configured_values() {
let text = "[core]\nrepo_version=1\nmode=bare\nfsync=false\n\
per-object-fsync=1\nlock-timeout-secs=30\nmin-free-space-percent=5\n\
[archive]\nzlib-level=9\n";
let cfg = RepoConfig::parse(text).unwrap();
assert!(!cfg.fsync().unwrap());
assert!(cfg.per_object_fsync().unwrap());
assert_eq!(cfg.lock_timeout_secs().unwrap(), 30);
assert_eq!(cfg.min_free_space().unwrap(), MinFreeSpace::Percent(5));
assert_eq!(cfg.zlib_level().unwrap(), 9);
}
#[test]
fn lock_timeout_secs_takes_minus_one_and_refuses_below() {
let with = |v: &str| {
RepoConfig::parse(&format!(
"[core]\nrepo_version=1\nmode=bare\nlock-timeout-secs={v}\n"
))
.unwrap()
};
assert_eq!(with("-1").lock_timeout_secs().unwrap(), -1);
assert_eq!(with("0").lock_timeout_secs().unwrap(), 0);
let err = with("-2").lock_timeout_secs().unwrap_err();
assert!(err.to_string().contains("lock-timeout-secs -2 is below -1"));
}
#[test]
fn bad_boolean_value_is_an_error() {
let cfg = RepoConfig::parse("[core]\nrepo_version=1\nmode=bare\nfsync=yes\n").unwrap();
assert!(cfg.fsync().is_err());
}
#[test]
fn min_free_space_size_wins_over_percent() {
let text = "[core]\nrepo_version=1\nmode=bare\n\
min-free-space-percent=5\nmin-free-space-size=2GB\n";
let cfg = RepoConfig::parse(text).unwrap();
assert_eq!(
cfg.min_free_space().unwrap(),
MinFreeSpace::Size(SizeSpec {
value: 2,
unit: SizeUnit::Giga
})
);
}
#[test]
fn rejects_out_of_range_min_free_space_percent() {
for bad in ["-1", "101"] {
let text = format!("[core]\nrepo_version=1\nmode=bare\nmin-free-space-percent={bad}\n");
let cfg = RepoConfig::parse(&text).unwrap();
assert!(cfg.min_free_space().is_err(), "should reject {bad}");
}
}
#[test]
fn min_free_space_size_units_and_rejection() {
for (raw, unit) in [
("500MB", SizeUnit::Mega),
("1GB", SizeUnit::Giga),
("3TB", SizeUnit::Tera),
] {
assert_eq!(parse_size(raw).unwrap().unit, unit);
}
for bad in ["1G", "GB", "1KB", "1gb", "1GB ", "", "1.5GB"] {
assert!(parse_size(bad).is_none(), "should reject {bad:?}");
}
}
#[test]
fn ex_integrity_defaults_off() {
let cfg = RepoConfig::parse(ARCHIVE_CONFIG).unwrap();
assert_eq!(cfg.composefs().unwrap(), Tristate::No);
assert_eq!(cfg.fsverity().unwrap(), Tristate::No);
}
#[test]
fn composefs_raises_fsverity_default_to_maybe() {
for composefs in ["yes", "maybe"] {
let text = format!(
"[core]\nrepo_version=1\nmode=bare\n[ex-integrity]\ncomposefs={composefs}\n"
);
let cfg = RepoConfig::parse(&text).unwrap();
assert_eq!(
cfg.fsverity().unwrap(),
Tristate::Maybe,
"composefs={composefs}"
);
}
let text = "[core]\nrepo_version=1\nmode=bare\n[ex-integrity]\ncomposefs=no\n";
let cfg = RepoConfig::parse(text).unwrap();
assert_eq!(cfg.fsverity().unwrap(), Tristate::No);
}
#[test]
fn explicit_fsverity_overrides_the_composefs_default() {
let text = "[core]\nrepo_version=1\nmode=bare\n\
[ex-integrity]\ncomposefs=yes\nfsverity=no\n";
let cfg = RepoConfig::parse(text).unwrap();
assert_eq!(cfg.fsverity().unwrap(), Tristate::No);
let text = "[core]\nrepo_version=1\nmode=bare\n[ex-integrity]\nfsverity=yes\n";
let cfg = RepoConfig::parse(text).unwrap();
assert_eq!(cfg.fsverity().unwrap(), Tristate::Yes);
}
#[test]
fn malformed_tristate_is_an_error() {
let text = "[core]\nrepo_version=1\nmode=bare\n[ex-integrity]\nfsverity=true\n";
let cfg = RepoConfig::parse(text).unwrap();
assert!(cfg.fsverity().is_err());
}
#[test]
fn explicit_fsverity_ignores_a_malformed_composefs() {
let text = "[core]\nrepo_version=1\nmode=bare\n\
[ex-integrity]\ncomposefs=perhaps\nfsverity=no\n";
let cfg = RepoConfig::parse(text).unwrap();
assert_eq!(cfg.fsverity().unwrap(), Tristate::No);
}
#[test]
fn keep_detached_related_is_true_when_absent() {
let cfg = RepoConfig::parse(ARCHIVE_CONFIG).unwrap();
assert!(cfg.keep_detached_related().unwrap());
}
#[test]
fn keep_detached_related_reads_a_boolean() {
let read = |value: &str| {
RepoConfig::parse(&format!(
"[core]\nrepo_version=1\nmode=bare\n[ex-ostrya]\n\
keep-detached-related={value}\n"
))
.unwrap()
.keep_detached_related()
};
assert!(!read("false").unwrap());
assert!(!read("0").unwrap());
assert!(read("true").unwrap());
assert!(read("1").unwrap());
assert!(read("maybe").is_err());
assert!(read("yes").is_err());
}
#[test]
fn generate_composefs_is_false_when_absent() {
let cfg = RepoConfig::parse("[core]\nrepo_version=1\nmode=bare\n").unwrap();
assert!(!cfg.generate_composefs().unwrap());
}
#[test]
fn generate_composefs_reads_a_boolean() {
let read = |mode: &str, value: &str| {
RepoConfig::parse(&format!(
"[core]\nrepo_version=1\nmode={mode}\n[ex-ostrya]\n\
generate-composefs={value}\n"
))
.unwrap()
.generate_composefs()
};
assert!(!read("bare", "false").unwrap());
assert!(read("bare", "true").unwrap());
assert!(read("bare-user", "1").unwrap());
assert!(matches!(read("bare", "maybe"), Err(Error::Core(_))));
assert!(!read("archive", "false").unwrap());
assert!(matches!(
read("archive", "true"),
Err(Error::Unsupported(_))
));
}
#[test]
fn gc_weak_references_is_none_when_absent() {
let cfg = RepoConfig::parse("[core]\nrepo_version=1\nmode=bare\n").unwrap();
assert!(cfg.gc_weak_references().unwrap().is_none());
}
#[test]
fn gc_weak_references_reads_a_pattern_list() {
let read = |value: &str| {
RepoConfig::parse(&format!(
"[core]\nrepo_version=1\nmode=bare\n[ex-ostrya]\n\
gc-weak-references={value}\n"
))
.unwrap()
.gc_weak_references()
};
let sel = read("tmp/**;!tmp/keep;*:**;@org.example.X:**")
.unwrap()
.unwrap();
let own = Some("org.example.Own");
assert!(sel.matches(&Ref::local("tmp/a"), own));
assert!(sel.matches(&Ref::local("tmp/a/b"), own));
assert!(!sel.matches(&Ref::local("tmp/keep"), own));
assert!(!sel.matches(&Ref::local("main"), own));
assert!(sel.matches(&Ref::remote("origin", "main"), own));
assert!(sel.matches(&Ref::collection("org.example.X", "main"), own));
assert!(!sel.matches(&Ref::collection("org.example.Y", "main"), own));
for value in ["", " ", ";", "!tmp/**", "!tmp/a;!tmp/b"] {
let err = read(value).unwrap_err();
assert!(
matches!(&err, Error::InvalidFormat(m)
if m.contains("[ex-ostrya] gc-weak-references")),
"{value:?}: {err}"
);
}
let err = read("tmp/**;r*:x").unwrap_err();
assert!(
matches!(&err, Error::InvalidFormat(m)
if m.contains("[ex-ostrya] gc-weak-references")
&& m.contains("malformed receive pattern")),
"{err}"
);
}
#[test]
fn push_branches_is_none_when_absent() {
let cfg = RepoConfig::parse(
"[core]\nrepo_version=1\nmode=bare\n[remote \"origin\"]\nurl=http://a/\n",
)
.unwrap();
let origin = cfg.remote("origin").unwrap();
assert!(origin.push_branches().unwrap().is_none());
}
#[test]
fn push_branches_reads_a_pattern_list() {
let read = |value: &str| {
RepoConfig::parse(&format!(
"[core]\nrepo_version=1\nmode=bare\n[remote \"origin\"]\n\
url=http://a/\npush-branches={value}\n"
))
.unwrap()
.remote("origin")
.unwrap()
.push_branches()
};
let sel = read("apps/**;!apps/b;@org.example.X:**;@org.example.Own:**")
.unwrap()
.unwrap();
let own = Some("org.example.Own");
assert!(sel.matches(&Ref::local("apps/a"), own));
assert!(!sel.matches(&Ref::local("apps/b"), own));
assert!(sel.matches(&Ref::local("main"), own));
assert!(sel.matches(&Ref::collection("org.example.X", "main"), own));
assert!(!sel.matches(&Ref::collection("org.example.Y", "main"), own));
let empty = read("").unwrap().unwrap();
assert!(empty.matches(&Ref::local("main"), None));
let err = read("apps/**;r*:x").unwrap_err();
assert!(
matches!(&err, Error::InvalidFormat(m)
if m.contains("[remote \"origin\"] push-branches")
&& m.contains("malformed receive pattern")),
"{err}"
);
}
#[test]
fn pull_branches_is_none_when_absent() {
let cfg = RepoConfig::parse(
"[core]\nrepo_version=1\nmode=bare\n[remote \"origin\"]\nurl=http://a/\n\
branches=main;\n",
)
.unwrap();
let origin = cfg.remote("origin").unwrap();
assert!(origin.pull_branches().unwrap().is_none());
}
#[test]
fn pull_branches_reads_a_pattern_list() {
let read = |value: &str| {
RepoConfig::parse(&format!(
"[core]\nrepo_version=1\nmode=bare\n[remote \"origin\"]\n\
url=http://a/\npull-branches={value}\n"
))
.unwrap()
.remote("origin")
.unwrap()
.pull_branches()
};
let sel = read("apps/**;!apps/b;@org.example.X:**").unwrap().unwrap();
let own = Some("org.example.Own");
assert!(sel.matches(&Ref::local("apps/a"), own));
assert!(!sel.matches(&Ref::local("apps/b"), own));
assert!(sel.matches(&Ref::collection("org.example.X", "main"), own));
assert!(!sel.matches(&Ref::collection("org.example.Y", "main"), own));
let err = read("apps/**;r*:x").unwrap_err();
assert!(
matches!(&err, Error::InvalidFormat(m)
if m.contains("[remote \"origin\"] pull-branches")
&& m.contains("malformed receive pattern")),
"{err}"
);
}
#[test]
fn auto_update_summary_reads_both_keys() {
let read = |extra: &str| {
RepoConfig::parse(&format!("[core]\nrepo_version=1\nmode=archive\n{extra}"))
.unwrap()
.auto_update_summary()
};
assert!(!read("").unwrap());
assert!(read("auto-update-summary=true\n").unwrap());
assert!(read("commit-update-summary=1\n").unwrap());
assert!(!read("auto-update-summary=false\ncommit-update-summary=0\n").unwrap());
assert!(read("auto-update-summary=true\ncommit-update-summary=false\n").unwrap());
assert!(read("auto-update-summary=false\ncommit-update-summary=true\n").unwrap());
}
#[test]
fn a_malformed_auto_update_summary_is_an_error() {
for extra in [
"auto-update-summary=yes\n",
"commit-update-summary=yes\n",
"auto-update-summary=true\ncommit-update-summary=yes\n",
"auto-update-summary=yes\ncommit-update-summary=true\n",
] {
let cfg = RepoConfig::parse(&format!("[core]\nrepo_version=1\nmode=archive\n{extra}"))
.unwrap();
assert!(
matches!(
cfg.auto_update_summary(),
Err(Error::Core(ostrya_core::Error::KeyFile(_)))
),
"{extra:?}"
);
}
}
#[test]
fn parses_remote_sections() {
let text = "[core]\nrepo_version=1\nmode=archive-z2\n\n\
[remote \"origin\"]\nurl=https://example.com/repo\nbranches=main;\n\
gpg-verify=false\n\n\
[remote \"withkey\"]\nurl=https://ex2.com/r\ncollection-id=org.ex.C\n";
let cfg = RepoConfig::parse(text).unwrap();
assert_eq!(cfg.remotes().collect::<Vec<_>>(), ["origin", "withkey"]);
let origin = cfg.remote("origin").unwrap();
assert_eq!(
origin.url().unwrap().as_deref(),
Some("https://example.com/repo")
);
assert!(!origin.gpg_verify().unwrap());
assert!(!origin.gpg_verify_summary().unwrap());
assert_eq!(origin.get("branches"), Some("main;"));
assert_eq!(origin.branches().unwrap(), Some(vec!["main".to_owned()]));
assert!(!origin.tls_permissive().unwrap());
assert_eq!(origin.tls_ca_path().unwrap(), None);
let withkey = cfg.remote("withkey").unwrap();
assert!(withkey.gpg_verify().unwrap()); assert_eq!(
withkey.collection_id().unwrap().as_deref(),
Some("org.ex.C")
);
assert!(cfg.remote("absent").is_none());
}
fn remote_file(name: &str, text: &str) -> RemoteFile {
RemoteFile {
name: name.to_owned(),
keyfile: KeyFile::parse(text).unwrap(),
}
}
fn config_with_files() -> RepoConfig {
let text = format!("{ARCHIVE_CONFIG}\n[remote \"origin\"]\nurl=https://o\n");
RepoConfig::parse(&text)
.unwrap()
.with_remote_files(
Path::new("/etc/r.d"),
vec![
remote_file(
"a.conf",
"[remote \"z\"]\nurl=https://z\n\n[remote \"y\"]\nurl=https://y\n",
),
remote_file("b.conf", "[remote \"x\"]\nurl=https://x\n"),
],
)
.unwrap()
}
#[test]
fn remotes_list_config_first_then_each_file_in_group_order() {
let cfg = config_with_files();
assert_eq!(cfg.remotes().collect::<Vec<_>>(), ["origin", "z", "y", "x"]);
assert_eq!(
cfg.remote("y").unwrap().url().unwrap().as_deref(),
Some("https://y")
);
}
#[test]
fn remote_source_is_config_or_the_file_name() {
let cfg = config_with_files();
assert_eq!(cfg.remote("origin").unwrap().source(), RemoteSource::Config);
assert_eq!(
cfg.remote("z").unwrap().source(),
RemoteSource::File("a.conf")
);
assert_eq!(
cfg.remote("x").unwrap().source(),
RemoteSource::File("b.conf")
);
assert!(cfg.remote("absent").is_none());
}
#[test]
fn a_name_in_two_sources_is_refused() {
let text = format!("{ARCHIVE_CONFIG}\n[remote \"origin\"]\nurl=https://o\n");
let base = Path::new("/etc/r.d");
let err = RepoConfig::parse(&text)
.unwrap()
.with_remote_files(
base,
vec![remote_file(
"o.conf",
"[remote \"origin\"]\nurl=https://f\n",
)],
)
.unwrap_err();
assert!(
matches!(&err, Error::InvalidFormat(m)
if m == "remote \"origin\" is defined in config and in /etc/r.d/o.conf"),
"{err}"
);
let err = RepoConfig::parse(ARCHIVE_CONFIG)
.unwrap()
.with_remote_files(
base,
vec![
remote_file("a.conf", "[remote \"x\"]\nurl=https://a\n"),
remote_file("b.conf", "[remote \"x\"]\nurl=https://b\n"),
],
)
.unwrap_err();
assert!(
matches!(&err, Error::InvalidFormat(m)
if m == "remote \"x\" is defined in /etc/r.d/a.conf and in /etc/r.d/b.conf"),
"{err}"
);
}
#[test]
fn two_groups_of_one_name_in_one_file_give_one_remote() {
let cfg = RepoConfig::parse(ARCHIVE_CONFIG)
.unwrap()
.with_remote_files(
Path::new("r.d"),
vec![remote_file(
"a.conf",
"[remote \"x\"]\nurl=https://1\nbranches=main;\n\n\
[remote \"x\"]\nurl=https://2\n",
)],
)
.unwrap();
assert_eq!(cfg.remotes().collect::<Vec<_>>(), ["x"]);
let remote = cfg.remote("x").unwrap();
assert_eq!(remote.url().unwrap().as_deref(), Some("https://2"));
assert_eq!(remote.keys().collect::<Vec<_>>(), ["url", "branches"]);
}
#[test]
fn a_file_skips_groups_that_are_not_remotes() {
let cfg = RepoConfig::parse(ARCHIVE_CONFIG)
.unwrap()
.with_remote_files(
Path::new("r.d"),
vec![remote_file(
"a.conf",
"[core]\nfsync=false\n\n[ex-ostrya]\nremotes-config-dir=x\n\n\
[remote \"x\"]\nurl=https://x\n",
)],
)
.unwrap();
assert_eq!(cfg.remotes().collect::<Vec<_>>(), ["x"]);
assert!(cfg.fsync().unwrap());
assert!(!cfg.keyfile().has_group("ex-ostrya"));
}
#[test]
fn from_keyfile_and_parse_have_no_remote_files() {
let cfg = RepoConfig::parse(ARCHIVE_CONFIG).unwrap();
assert!(cfg.remote_files.is_empty());
let cfg = RepoConfig::from_keyfile(KeyFile::parse(ARCHIVE_CONFIG).unwrap()).unwrap();
assert!(cfg.remote_files.is_empty());
}
#[test]
fn reads_remote_verification_keys() {
let text = "[core]\nrepo_version=1\nmode=archive-z2\n\n\
[remote \"signed\"]\nurl=https://ex.com/r\nsign-verify=ed25519\n\
sign-verify-summary=true\nverification-ed25519-key=AAAA\n\
verification-ed25519-file=/etc/keys.ed25519\n\
gpgkeypath=/etc/one.gpg;/etc/keys.d\n";
let cfg = RepoConfig::parse(text).unwrap();
let remote = cfg.remote("signed").unwrap();
assert_eq!(
remote.sign_verify().unwrap(),
SignVerify::Engines(vec!["ed25519".to_owned()])
);
assert_eq!(remote.sign_verify_summary().unwrap(), SignVerify::All);
assert_eq!(
remote.verification_key("ed25519").unwrap().as_deref(),
Some("AAAA")
);
assert_eq!(
remote.verification_file("ed25519").unwrap().as_deref(),
Some("/etc/keys.ed25519")
);
assert_eq!(remote.verification_key("spki").unwrap(), None);
assert_eq!(
remote.gpgkeypath().unwrap(),
vec!["/etc/one.gpg".to_owned(), "/etc/keys.d".to_owned()]
);
let plain = cfg.remote("signed").unwrap();
assert!(plain.gpg_verify().unwrap());
let bare = RepoConfig::parse(
"[core]\nrepo_version=1\nmode=bare\n\n[remote \"plain\"]\nurl=http://ex/r\n",
)
.unwrap();
let bare = bare.remote("plain").unwrap();
assert_eq!(bare.sign_verify().unwrap(), SignVerify::Off);
assert_eq!(bare.sign_verify_summary().unwrap(), SignVerify::Off);
assert!(bare.gpgkeypath().unwrap().is_empty());
}
#[test]
fn gpgkeypath_splits_the_raw_value() {
let cases: &[(&str, &[&str])] = &[
(r"k\sspace.gpg", &[r"k\sspace.gpg"]),
(r"\q", &[r"\q"]),
("", &[""]),
(";", &[""]),
(";a", &["", "a"]),
("a;;b", &["a", "", "b"]),
("a;", &["a"]),
("a;;", &["a", ""]),
("a;b", &["a", "b"]),
];
for (value, want) in cases {
let text = format!(
"[core]\nrepo_version=1\nmode=bare\n\n\
[remote \"r\"]\nurl=http://ex/r\ngpgkeypath={value}\n"
);
let cfg = RepoConfig::parse(&text).unwrap();
assert_eq!(
cfg.remote("r").unwrap().gpgkeypath().unwrap(),
*want,
"gpgkeypath={value}"
);
}
}
#[test]
fn parses_the_sign_verify_spellings() {
assert_eq!(parse_sign_verify(None), SignVerify::Off);
assert_eq!(parse_sign_verify(Some("true")), SignVerify::All);
assert_eq!(parse_sign_verify(Some("1")), SignVerify::All);
assert_eq!(parse_sign_verify(Some("false")), SignVerify::Off);
assert_eq!(parse_sign_verify(Some("0")), SignVerify::Off);
assert_eq!(parse_sign_verify(Some("")), SignVerify::Off);
assert_eq!(
parse_sign_verify(Some("ed25519")),
SignVerify::Engines(vec!["ed25519".to_owned()])
);
assert_eq!(
parse_sign_verify(Some("ed25519;spki,")),
SignVerify::Engines(vec!["ed25519".to_owned(), "spki".to_owned()])
);
assert_eq!(
parse_sign_verify(Some("ed25519, ed25519")),
SignVerify::Engines(vec!["ed25519".to_owned(), " ed25519".to_owned()])
);
}
#[test]
fn reads_remote_tls_keys() {
let text = "[core]\nrepo_version=1\nmode=archive-z2\n\n\
[remote \"secure\"]\nurl=https://ex.com/r\ntls-ca-path=/etc/ca.pem\n\
tls-client-cert-path=/etc/client.pem\ntls-client-key-path=/etc/client.key\n\
tls-permissive=true\n";
let cfg = RepoConfig::parse(text).unwrap();
let remote = cfg.remote("secure").unwrap();
assert_eq!(
remote.tls_ca_path().unwrap().as_deref(),
Some("/etc/ca.pem")
);
assert_eq!(
remote.tls_client_cert_path().unwrap().as_deref(),
Some("/etc/client.pem")
);
assert_eq!(
remote.tls_client_key_path().unwrap().as_deref(),
Some("/etc/client.key")
);
assert!(remote.tls_permissive().unwrap());
}
#[test]
fn reads_remote_proxy_key() {
let text = "[core]\nrepo_version=1\nmode=archive-z2\n\n\
[remote \"set\"]\nurl=http://ex.com/r\n\
proxy=http://user:pw@proxy.ex.com:3128\n\n\
[remote \"empty\"]\nurl=http://ex.com/r\nproxy=\n\n\
[remote \"blank\"]\nurl=http://ex.com/r\nproxy= \n\n\
[remote \"trail\"]\nurl=http://ex.com/r\nproxy=http://p:1 \n\n\
[remote \"escape\"]\nurl=http://ex.com/r\nproxy=\\s\n\n\
[remote \"plain\"]\nurl=http://ex.com/r\n";
let cfg = RepoConfig::parse(text).unwrap();
assert_eq!(
cfg.remote("set").unwrap().proxy().unwrap().as_deref(),
Some("http://user:pw@proxy.ex.com:3128")
);
assert_eq!(
cfg.remote("empty").unwrap().proxy().unwrap().as_deref(),
Some("")
);
assert_eq!(
cfg.remote("blank").unwrap().proxy().unwrap().as_deref(),
Some("")
);
assert_eq!(
cfg.remote("trail").unwrap().proxy().unwrap().as_deref(),
Some("http://p:1 ")
);
assert_eq!(
cfg.remote("escape").unwrap().proxy().unwrap().as_deref(),
Some(" ")
);
assert_eq!(cfg.remote("plain").unwrap().proxy().unwrap(), None);
}
#[test]
fn reads_remote_push_keys() {
let text = "[core]\nrepo_version=1\nmode=archive-z2\n\n\
[remote \"central\"]\nurl=https://ex.com/r\n\
push-url=ssh://pusher@ex.com/srv/repo\n\
ssh-command=ssh -o BatchMode=yes\n\
receive-command=/opt/bin/ostrya receive\n\
push-token-file=/etc/push token\n\
push-user=alice\n\
pull-url=puller@ex.com:srv/repo\n\
send-command=/opt/bin/ostrya send -v\n\n\
[remote \"plain\"]\nurl=https://ex.com/r\n";
let cfg = RepoConfig::parse(text).unwrap();
let remote = cfg.remote("central").unwrap();
assert_eq!(
remote.push_url().unwrap().as_deref(),
Some("ssh://pusher@ex.com/srv/repo")
);
assert_eq!(
remote.ssh_command().unwrap().as_deref(),
Some("ssh -o BatchMode=yes")
);
assert_eq!(
remote.receive_command().unwrap().as_deref(),
Some("/opt/bin/ostrya receive")
);
assert_eq!(
remote.push_token_file().unwrap().as_deref(),
Some("/etc/push token")
);
assert_eq!(remote.push_user().unwrap().as_deref(), Some("alice"));
assert_eq!(
remote.pull_url().unwrap().as_deref(),
Some("puller@ex.com:srv/repo")
);
assert_eq!(
remote.send_command().unwrap().as_deref(),
Some("/opt/bin/ostrya send -v")
);
let plain = cfg.remote("plain").unwrap();
assert_eq!(plain.push_url().unwrap(), None);
assert_eq!(plain.ssh_command().unwrap(), None);
assert_eq!(plain.receive_command().unwrap(), None);
assert_eq!(plain.push_token_file().unwrap(), None);
assert_eq!(plain.push_user().unwrap(), None);
assert_eq!(plain.pull_url().unwrap(), None);
assert_eq!(plain.send_command().unwrap(), None);
}
#[test]
fn mirrored_collection_ids_reads_the_checked_ids() {
let ids = |keys: &str| {
let text = format!("[core]\nrepo_version=1\nmode=archive-z2\n\n[remote \"r\"]\n{keys}");
RepoConfig::parse(&text)
.unwrap()
.remote("r")
.unwrap()
.mirrored_collection_ids()
};
assert_eq!(ids("url=https://ex.com/r\n").unwrap(), Vec::<String>::new());
assert_eq!(
ids("mirrored-collection-ids=org.ex.B;org.ex.A;org.ex.B;\n").unwrap(),
["org.ex.B", "org.ex.A"]
);
assert_eq!(
ids("collection-id=org.ex.C\nmirrored-collection-ids=org.ex.A\n").unwrap(),
["org.ex.A"]
);
for keys in [
"mirrored-collection-ids=\n",
"mirrored-collection-ids=;\n",
"mirrored-collection-ids=org.ex.A;;org.ex.B\n",
"mirrored-collection-ids=org/ex\n",
"mirrored-collection-ids=1org.ex\n",
"collection-id=org.ex.C\nmirrored-collection-ids=org.ex.A;org.ex.C\n",
] {
assert!(
matches!(ids(keys), Err(Error::InvalidFormat(_))),
"{keys:?}"
);
}
}
}