use std::collections::HashMap;
use std::os::fd::{AsFd, BorrowedFd};
use std::path::{Component, Path, PathBuf};
use std::sync::Arc;
use ostrya_core::{KeyFile, RepoMode};
use rustix::io::Errno;
use crate::error::{Error, Result};
use crate::pattern::ReceiveSelector;
use crate::remotes_dir;
use crate::repo::{Repo, check_config_size};
use crate::repo_fs::{FsError, Publish, Reason, RootFile};
mod edit;
mod group_macro;
mod overrides;
mod section;
mod typed;
mod value;
#[doc(no_inline)]
pub use crate::config_group;
pub use edit::{ConfigEdit, SectionMut};
pub(crate) use overrides::{Entry, Overrides, find as find_entry, put as put_entry, put_settable};
pub use section::{GroupRef, Lookup, Section};
pub(crate) use section::{
TRUST_ENGINES, lookup_text, read_file, refuse_unknown_keys, section_name, verification_engine,
};
pub(crate) use typed::ValueOf;
pub(crate) use typed::sealed;
pub use typed::{Group, Key, Overridable, Settable, SingleKey, UserGroup};
pub use value::{
AllowItems, AuthItems, CollectionIdList, CollectionIdValue, ConfigPath, DenyItems,
FreeSpacePercent, HeaderName, KeyGroupNames, KeyringPaths, ListenAddrs, LockTimeout, PemPath,
PositiveInt, RemotesConfigPath, SigningKeyType, TrustGroupName, TrustRef, TrustedNets,
UploadStreams, Value, ValueError, decode_bool, decode_integer, decode_string,
decode_string_list, encode_bool, encode_integer, encode_string, encode_string_list,
};
const CORE: &str = "core";
pub(crate) const EX_OSTRYA: &str = "ex-ostrya";
pub(crate) const REMOTES_CONFIG_DIR: &str = "remotes-config-dir";
const CONFIG_FILE: &str = "config";
crate::__config_group! {
@builtin
pub group repo = "core" {
RepoVersion: i64 = "repo_version", required, fixed;
Mode: RepoMode = "mode", required, fixed;
CollectionId: Option<CollectionIdValue> = "collection-id";
Fsync: bool = "fsync", default true, overridable;
PerObjectFsync: bool = "per-object-fsync", default false, overridable;
Locking: bool = "locking", default true;
LockTimeoutSecs: LockTimeout = "lock-timeout-secs",
default LockTimeout::new_const(300), overridable;
TmpExpirySecs: i64 = "tmp-expiry-secs", default 86400, overridable;
TombstoneCommits: bool = "tombstone-commits", default false, overridable;
IndexedDeltas: bool = "indexed-deltas", default true, overridable;
DisableXattrs: bool = "disable-xattrs", default false;
DefaultRepoFinders: Vec<String> = "default-repo-finders",
default vec!["config".to_owned(), "mount".to_owned()], overridable;
MinFreeSpaceSize: Option<SizeSpec> = "min-free-space-size", overridable;
MinFreeSpacePercent: FreeSpacePercent = "min-free-space-percent",
default FreeSpacePercent::new_const(3), overridable;
AutoUpdateSummary: bool = "auto-update-summary", default false, overridable;
AddRemotesConfigDir: bool = "add-remotes-config-dir", default false, overridable;
}
}
crate::__config_group! {
@builtin
pub group archive = "archive" {
ZlibLevel: i64 = "zlib-level", default 6, overridable;
}
}
crate::__config_group! {
@builtin
pub group ex_integrity = "ex-integrity" {
Composefs: Tristate = "composefs", default Tristate::No, overridable;
Fsverity: Option<Tristate> = "fsverity", overridable;
}
}
crate::__config_group! {
@builtin
pub group ex_ostrya = "ex-ostrya" {
KeepDetachedRelated: bool = "keep-detached-related", default true, overridable;
GcWeakReferences: Option<ReceiveSelector> = "gc-weak-references", overridable;
RemotesConfigDir: Option<RemotesConfigPath> = "remotes-config-dir";
}
}
crate::__config_group! {
@builtin
pub group server = "ex-ostrya server", closed {
Listen: Option<ListenAddrs> = "listen";
TlsCert: Option<PemPath> = "tls-cert";
TlsKey: Option<PemPath> = "tls-key";
TlsClientCa: Option<PemPath> = "tls-client-ca";
TrustedProxy: Option<TrustedNets> = "trusted-proxy";
TrustedProxyHeader: Option<crate::access::ForwardedHeader> = "trusted-proxy-header";
TrustedProxyClientCert: Option<HeaderName> = "trusted-proxy-client-cert";
ProxyProtocol: Option<bool> = "proxy-protocol";
AllowCleartextCredentials: Option<bool> = "allow-cleartext-credentials";
SessionTimeout: Option<PositiveInt> = "session-timeout";
MaxSessions: Option<PositiveInt> = "max-sessions";
ParallelUploads: Option<UploadStreams> = "parallel-uploads";
BodyTimeout: Option<PositiveInt> = "body-timeout";
SignSummary: Option<KeyGroupNames> = "sign-summary";
}
}
crate::__config_group! {
@builtin
pub group client = named "ex-ostrya client", closed {
Auth: AuthItems = "auth", required;
Allow: AllowItems = "allow", default AllowItems::default();
Deny: DenyItems = "deny", default DenyItems::default();
TlsAcceptClaim: bool = "tls-accept-claim", default false;
Verify: Option<TrustRef> = "verify";
AllowUnsigned: Option<bool> = "allow-unsigned";
Sign: Option<KeyGroupNames> = "sign";
AllowPrivileged: bool = "allow-privileged", default false;
DisableVerifyBindings: bool = "disable-verify-bindings", default false;
Summary: bool = "summary", default false;
}
}
crate::__config_group! {
@builtin
pub group trust = named "ex-ostrya trust", closed {
use remote::GpgVerify: bool = "gpg-verify", default false;
use remote::GpgKeyPath: KeyringPaths = "gpgkeypath", default KeyringPaths::default();
use remote::SignVerify: super::SignVerify = "sign-verify", default super::SignVerify::Off;
use remote::VerificationEd25519Key: Option<String> = "verification-ed25519-key";
use remote::VerificationEd25519File: Option<ConfigPath> = "verification-ed25519-file";
use remote::VerificationSpkiKey: Option<String> = "verification-spki-key";
use remote::VerificationSpkiFile: Option<ConfigPath> = "verification-spki-file";
}
}
crate::__config_group! {
@builtin
pub group key = named "ex-ostrya key", closed {
Type: SigningKeyType = "type", required;
SecretKeyFile: Option<ConfigPath> = "secret-key-file";
GpgKey: Option<String> = "gpg-key";
GpgHomedir: Option<String> = "gpg-homedir";
}
}
crate::__config_group! {
@builtin
pub group remote = named "remote" {
Url: Option<String> = "url";
ContentUrl: Option<String> = "contenturl";
Metalink: Option<String> = "metalink";
Branches: Option<Vec<String>> = "branches";
CollectionId: Option<String> = "collection-id";
MirroredCollectionIds: Option<CollectionIdList> = "mirrored-collection-ids";
GpgVerify: bool = "gpg-verify", default true;
GpgVerifySummary: bool = "gpg-verify-summary", default false;
GpgKeyPath: KeyringPaths = "gpgkeypath", default KeyringPaths::default();
SignVerify: super::SignVerify = "sign-verify", default super::SignVerify::Off;
SignVerifySummary: super::SignVerify = "sign-verify-summary",
default super::SignVerify::Off;
VerificationEd25519Key: Option<String> = "verification-ed25519-key";
VerificationEd25519File: Option<ConfigPath> = "verification-ed25519-file";
VerificationSpkiKey: Option<String> = "verification-spki-key";
VerificationSpkiFile: Option<ConfigPath> = "verification-spki-file";
Trust: Option<TrustGroupName> = "trust";
TlsCaPath: Option<ConfigPath> = "tls-ca-path";
TlsClientCertPath: Option<ConfigPath> = "tls-client-cert-path";
TlsClientKeyPath: Option<ConfigPath> = "tls-client-key-path";
TlsPermissive: bool = "tls-permissive", default false;
Proxy: Option<String> = "proxy";
PushUrl: Option<String> = "push-url";
PullUrl: Option<String> = "pull-url";
PushBranches: Option<ReceiveSelector> = "push-branches";
PullBranches: Option<ReceiveSelector> = "pull-branches";
SshCommand: Option<String> = "ssh-command";
ReceiveCommand: Option<String> = "receive-command";
SendCommand: Option<String> = "send-command";
PushTokenFile: Option<ConfigPath> = "push-token-file";
PushUser: Option<String> = "push-user";
S3Region: Option<String> = "s3-region";
S3Endpoint: Option<String> = "s3-endpoint";
S3Addressing: Option<String> = "s3-addressing";
S3Profile: Option<String> = "s3-profile";
}
}
#[derive(Debug, Clone)]
pub struct RepoConfig {
keyfile: KeyFile,
mode: RepoMode,
repo_version: i64,
collection_id: Option<String>,
remote_files: Vec<RemoteFile>,
overrides: Arc<Overrides>,
}
#[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(crate) enum KeyOrigin {
Caller,
Config,
RemotesFile,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct KeyPath {
pub(crate) value: PathBuf,
pub(crate) origin: KeyOrigin,
}
impl KeyPath {
pub(crate) fn caller(value: impl Into<PathBuf>) -> KeyPath {
KeyPath {
value: value.into(),
origin: KeyOrigin::Caller,
}
}
pub(crate) fn locate<'a>(
&'a self,
repo: Option<&'a Repo>,
) -> (BorrowedFd<'a>, PathBuf, PathBuf) {
match (self.origin, repo) {
(KeyOrigin::Config, Some(repo)) => (
repo.root_dir().as_fd(),
self.value.clone(),
self.value.clone(),
),
(KeyOrigin::RemotesFile, Some(repo)) => match repo.remotes_dir() {
Some(dir) => remotes_dir::entry(repo.root_dir().as_fd(), dir, &self.value),
None => (rustix::fs::CWD, self.value.clone(), self.value.clone()),
},
_ => (rustix::fs::CWD, self.value.clone(), self.value.clone()),
}
}
}
pub(crate) fn io_of(err: FsError) -> std::io::Error {
match err {
FsError::Io(e) => e,
FsError::Absent { .. } => Errno::NOENT.into(),
FsError::Invalid {
reason: Reason::NotDirectory,
..
} => Errno::NOTDIR.into(),
other => std::io::Error::other(Error::from(other).to_string()),
}
}
pub(crate) fn relative_with_parent(path: &Path) -> bool {
path.is_relative() && path.components().any(|c| c == Component::ParentDir)
}
#[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 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")?;
Ok(RepoConfig {
keyfile,
mode,
repo_version,
collection_id,
remote_files: Vec::new(),
overrides: Arc::default(),
})
}
pub(crate) fn with_remote_files(
mut self,
base: &Path,
files: Vec<RemoteFile>,
) -> Result<RepoConfig> {
let mut seen: HashMap<&str, Option<usize>> = self
.keyfile
.groups()
.filter_map(remote_group_name)
.map(|name| (name, 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, 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.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(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 fn min_free_space(&self) -> Result<MinFreeSpace> {
if let Some(spec) = self.get::<repo::MinFreeSpaceSize>()? {
return Ok(MinFreeSpace::Size(spec));
}
Ok(MinFreeSpace::Percent(
self.get::<repo::MinFreeSpacePercent>()?.get(),
))
}
pub fn gc_weak_references(&self) -> Result<Option<ReceiveSelector>> {
refuse_no_positive(self.get::<ex_ostrya::GcWeakReferences>()?)
}
pub fn check(&self) -> Result<()> {
let keyfile = &self.keyfile;
repo::check_file(keyfile, <repo::Group as Group>::NAME)?;
archive::check_file(keyfile, <archive::Group as Group>::NAME)?;
ex_integrity::check_file(keyfile, <ex_integrity::Group as Group>::NAME)?;
ex_ostrya::check_file(keyfile, <ex_ostrya::Group as Group>::NAME)?;
refuse_no_positive(self.file_value::<ex_ostrya::GcWeakReferences>()?)?;
for section in self.sections::<remote::Group>() {
section.check()?;
}
server::check_file(keyfile, <server::Group as Group>::NAME)?;
for section in self.sections::<client::Group>() {
section.check()?;
}
for section in self.sections::<trust::Group>() {
section.check()?;
}
for section in self.sections::<key::Group>() {
section.check()?;
}
Ok(())
}
#[doc(hidden)]
pub fn text_in_effect(&self, group: &str, key: &str) -> Result<TextInEffect> {
if let Some(name) = remote_group_name(group) {
return match self.section::<remote::Group>(name) {
Some(section) => section.text_in_effect(key),
None => Ok(TextInEffect::NoGroup),
};
}
if is_header_of::<client::Group>(group) {
return match self.section_of_header::<client::Group>(group) {
Some(section) => section.text_in_effect(key),
None => Ok(TextInEffect::NoGroup),
};
}
if is_header_of::<trust::Group>(group) {
return match self.section_of_header::<trust::Group>(group) {
Some(section) => section.text_in_effect(key),
None => Ok(TextInEffect::NoGroup),
};
}
if is_header_of::<key::Group>(group) {
return match self.section_of_header::<key::Group>(group) {
Some(section) => section.text_in_effect(key),
None => Ok(TextInEffect::NoGroup),
};
}
let keyfile = &self.keyfile;
let overrides: Option<&Overrides> = Some(&self.overrides);
let typed = if group == <repo::Group as Group>::NAME {
repo::text_in_effect(keyfile, group, overrides, key)
} else if group == <archive::Group as Group>::NAME {
archive::text_in_effect(keyfile, group, overrides, key)
} else if group == <ex_integrity::Group as Group>::NAME {
if key == <ex_integrity::Fsverity as Key<ex_integrity::Group>>::NAME {
Some(self.fsverity().map(|value| Some(value.format())))
} else {
ex_integrity::text_in_effect(keyfile, group, overrides, key)
}
} else if group == <ex_ostrya::Group as Group>::NAME {
if key == <ex_ostrya::GcWeakReferences as Key<ex_ostrya::Group>>::NAME {
Some(
self.gc_weak_references()
.map(|value| value.map(|selector| selector.format())),
)
} else {
ex_ostrya::text_in_effect(keyfile, group, overrides, key)
}
} else if group == <server::Group as Group>::NAME {
server::text_in_effect(keyfile, group, overrides, key)
} else {
None
};
if let Some(text) = typed {
return Ok(text?.map_or(TextInEffect::NoKey, TextInEffect::Value));
}
if !keyfile.has_group(group) {
return Ok(TextInEffect::NoGroup);
}
Ok(keyfile
.get_value(group, key)
.map_or(TextInEffect::NoKey, |raw| {
TextInEffect::Value(raw.to_owned())
}))
}
fn section_of_header<G: Group>(&self, group: &str) -> Option<Section<'_, G>> {
section_name::<G>(group).and_then(|name| self.section::<G>(name))
}
pub fn fsverity(&self) -> Result<Tristate> {
if let Some(explicit) = self.get::<ex_integrity::Fsverity>()? {
return Ok(explicit);
}
Ok(match self.get::<ex_integrity::Composefs>()? {
Tristate::No => Tristate::No,
Tristate::Maybe | Tristate::Yes => Tristate::Maybe,
})
}
pub fn keyfile(&self) -> &KeyFile {
&self.keyfile
}
pub(crate) fn into_keyfile(self) -> KeyFile {
self.keyfile
}
pub(crate) fn with_overrides(mut self, overrides: Arc<Overrides>) -> RepoConfig {
self.overrides = overrides;
self
}
pub(crate) fn overrides(&self) -> &Arc<Overrides> {
&self.overrides
}
}
impl Repo {
pub async fn write_config(&self, keyfile: &KeyFile) -> Result<()> {
let fsync = self.config().get::<repo::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)?;
repo.root_dir()
.write_root_file(RootFile::Config, &bytes, Publish::Replace, fsync)?;
Ok(())
})
.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);
let fsync = self.config().get::<repo::Fsync>()?;
self.write_locked(move |repo| {
repo.root_dir().remove_file(&name, fsync)?;
Ok(())
})
.await
}
}
fn refuse_no_positive(selector: Option<ReceiveSelector>) -> Result<Option<ReceiveSelector>> {
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(crate) fn remote_keyring_name(remote: &str) -> String {
format!("{remote}.trustedkeys.gpg")
}
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)
}
#[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('"'))
}
#[doc(hidden)]
pub fn trust_group_name(group: &str) -> Option<&str> {
group
.strip_prefix(<trust::Group as Group>::NAME)
.and_then(|rest| rest.strip_prefix(" \""))
.and_then(|rest| rest.strip_suffix('"'))
}
fn is_header_of<G: Group>(group: &str) -> bool {
group
.strip_prefix(G::NAME)
.and_then(|rest| rest.strip_prefix(" \""))
.is_some_and(|rest| rest.ends_with('"'))
}
#[doc(hidden)]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TextInEffect {
Value(String),
NoKey,
NoGroup,
}
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)]
pub(crate) mod tests {
use super::*;
use ostrya_core::Ref;
const ARCHIVE_CONFIG: &str = "[core]\nrepo_version=1\nmode=archive-z2\n";
fn remote_names(cfg: &RepoConfig) -> Vec<&str> {
cfg.sections::<remote::Group>().map(|s| s.name()).collect()
}
#[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!(remote_names(&cfg).len(), 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.get::<repo::Fsync>().unwrap());
assert!(!cfg.get::<repo::PerObjectFsync>().unwrap());
assert!(cfg.get::<repo::Locking>().unwrap());
assert_eq!(cfg.get::<repo::LockTimeoutSecs>().unwrap().get(), 300);
assert_eq!(cfg.get::<repo::TmpExpirySecs>().unwrap(), 86400);
assert!(!cfg.get::<repo::DisableXattrs>().unwrap());
assert_eq!(
cfg.get::<repo::DefaultRepoFinders>().unwrap(),
vec!["config".to_owned(), "mount".to_owned()]
);
assert_eq!(cfg.get::<archive::ZlibLevel>().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.get::<repo::Fsync>().unwrap());
assert!(cfg.get::<repo::PerObjectFsync>().unwrap());
assert_eq!(cfg.get::<repo::LockTimeoutSecs>().unwrap().get(), 30);
assert_eq!(cfg.min_free_space().unwrap(), MinFreeSpace::Percent(5));
assert_eq!(cfg.get::<archive::ZlibLevel>().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()
};
let read = |v: &str| with(v).get::<repo::LockTimeoutSecs>();
assert_eq!(read("-1").unwrap().get(), -1);
assert_eq!(read("0").unwrap().get(), 0);
let err = read("-2").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.get::<repo::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.get::<ex_integrity::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.get::<ex_ostrya::KeepDetachedRelated>().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()
.get::<ex_ostrya::KeepDetachedRelated>()
};
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 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.section::<remote::Group>("origin").unwrap();
assert!(origin.get::<remote::PushBranches>().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()
.section::<remote::Group>("origin")
.unwrap()
.get::<remote::PushBranches>()
};
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.section::<remote::Group>("origin").unwrap();
assert!(origin.get::<remote::PullBranches>().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()
.section::<remote::Group>("origin")
.unwrap()
.get::<remote::PullBranches>()
};
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_its_key_alone() {
let read = |extra: &str| {
RepoConfig::parse(&format!("[core]\nrepo_version=1\nmode=archive\n{extra}"))
.unwrap()
.get::<repo::AutoUpdateSummary>()
};
assert!(!read("").unwrap());
assert!(read("auto-update-summary=true\n").unwrap());
assert!(!read("auto-update-summary=false\n").unwrap());
assert!(!read("commit-update-summary=true\n").unwrap());
assert!(!read("commit-update-summary=yes\n").unwrap());
assert!(read("auto-update-summary=true\ncommit-update-summary=yes\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",
"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.get::<repo::AutoUpdateSummary>(),
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!(remote_names(&cfg), ["origin", "withkey"]);
let origin = cfg.section::<remote::Group>("origin").unwrap();
assert_eq!(
origin.get::<remote::Url>().unwrap().as_deref(),
Some("https://example.com/repo")
);
assert!(!origin.get::<remote::GpgVerify>().unwrap());
assert!(!origin.get::<remote::GpgVerifySummary>().unwrap());
assert_eq!(origin.raw_value::<remote::Branches>(), Some("main;"));
assert_eq!(
origin.get::<remote::Branches>().unwrap(),
Some(vec!["main".to_owned()])
);
assert!(!origin.get::<remote::TlsPermissive>().unwrap());
assert_eq!(origin.get::<remote::TlsCaPath>().unwrap(), None);
let withkey = cfg.section::<remote::Group>("withkey").unwrap();
assert!(withkey.get::<remote::GpgVerify>().unwrap()); assert_eq!(
withkey.get::<remote::CollectionId>().unwrap().as_deref(),
Some("org.ex.C")
);
assert!(cfg.section::<remote::Group>("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!(remote_names(&cfg), ["origin", "z", "y", "x"]);
assert_eq!(
cfg.section::<remote::Group>("y")
.unwrap()
.get::<remote::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.section::<remote::Group>("origin").unwrap().source(),
RemoteSource::Config
);
assert_eq!(
cfg.section::<remote::Group>("z").unwrap().source(),
RemoteSource::File("a.conf")
);
assert_eq!(
cfg.section::<remote::Group>("x").unwrap().source(),
RemoteSource::File("b.conf")
);
assert!(cfg.section::<remote::Group>("absent").is_none());
}
#[test]
fn section_and_resolve_find_a_remote_of_a_conf_file() {
let cfg = config_with_files();
let y = cfg.section::<remote::Group>("y").unwrap();
assert_eq!(y.name(), "y");
assert_eq!(y.source(), RemoteSource::File("a.conf"));
assert_eq!(
y.get::<remote::Url>().unwrap().as_deref(),
Some("https://y")
);
let x = cfg
.resolve(&GroupRef::<remote::Group>::new("x").unwrap())
.unwrap();
assert_eq!(x.source(), RemoteSource::File("b.conf"));
assert_eq!(
x.get::<remote::Url>().unwrap().as_deref(),
Some("https://x")
);
let origin = cfg
.resolve(&GroupRef::<remote::Group>::new("origin").unwrap())
.unwrap();
assert_eq!(origin.source(), RemoteSource::Config);
let err = cfg
.resolve(&GroupRef::<remote::Group>::new("absent").unwrap())
.unwrap_err();
assert_eq!(
err.to_string(),
"invalid format: the config has no [remote \"absent\"] group"
);
let sources: Vec<_> = cfg
.sections::<remote::Group>()
.map(|s| (s.name(), s.source()))
.collect();
assert_eq!(
sources,
[
("origin", RemoteSource::Config),
("z", RemoteSource::File("a.conf")),
("y", RemoteSource::File("a.conf")),
("x", RemoteSource::File("b.conf")),
]
);
}
#[test]
fn a_conf_file_gives_no_section_of_another_group() {
crate::config_group! {
pub group image = named "ex-image" {
Arch: Option<String> = "arch";
}
}
let cfg = RepoConfig::parse(&format!("{ARCHIVE_CONFIG}[ex-image \"c\"]\narch=amd64\n"))
.unwrap()
.with_remote_files(
Path::new("r.d"),
vec![remote_file(
"a.conf",
"[ex-image \"f\"]\narch=arm64\n\n[remote \"x\"]\nurl=https://x\n",
)],
)
.unwrap();
let names: Vec<_> = cfg.sections::<image::Group>().map(|s| s.name()).collect();
assert_eq!(names, ["c"]);
assert_eq!(
cfg.section::<image::Group>("c")
.unwrap()
.get::<image::Arch>()
.unwrap()
.as_deref(),
Some("amd64")
);
assert!(cfg.section::<image::Group>("f").is_none());
assert!(
cfg.resolve(&GroupRef::<image::Group>::new("f").unwrap())
.is_err()
);
assert_eq!(remote_names(&cfg), ["x"]);
}
#[test]
fn a_remote_name_is_not_empty_and_holds_no_quote() {
let cfg = RepoConfig::parse(&format!(
"{ARCHIVE_CONFIG}[remote \"\"]\nurl=https://e\n\
[remote \"a\" \"b\"]\nurl=https://q\n[remote \"c\"]\nurl=https://c\n"
))
.unwrap()
.with_remote_files(
Path::new("r.d"),
vec![remote_file(
"a.conf",
"[remote \"x\" \"y\"]\nurl=https://f\n\n[remote \"d\"]\nurl=https://d\n",
)],
)
.unwrap();
assert_eq!(remote_names(&cfg), ["c", "d"]);
assert!(cfg.section::<remote::Group>("").is_none());
assert!(cfg.section::<remote::Group>("a\" \"b").is_none());
assert!(cfg.section::<remote::Group>("x\" \"y").is_none());
}
#[test]
fn a_trust_section_reads_the_shared_keys() {
let cfg = RepoConfig::parse(&format!(
"{ARCHIVE_CONFIG}[ex-ostrya trust \"t\"]\nsign-verify=ed25519\ngpgkeypath=/k.gpg\n\
verification-ed25519-key=AAAA\n\
[ex-ostrya trust \"g\"]\ngpg-verify=true\n"
))
.unwrap();
let t = cfg.section::<trust::Group>("t").unwrap();
assert_eq!(t.name(), "t");
assert_eq!(
t.get::<trust::SignVerify>().unwrap(),
SignVerify::Engines(vec!["ed25519".to_owned()])
);
assert_eq!(
t.verification_key("ed25519").unwrap().as_deref(),
Some("AAAA")
);
assert_eq!(t.verification_key("other").unwrap(), None);
assert_eq!(t.raw_value::<trust::GpgKeyPath>(), Some("/k.gpg"));
assert!(t.contains::<trust::GpgKeyPath>());
assert!(!t.contains::<trust::VerificationSpkiKey>());
assert_eq!(
t.key_names().collect::<Vec<_>>(),
["sign-verify", "gpgkeypath", "verification-ed25519-key"]
);
assert_eq!(t.file_value::<trust::GpgVerify>().unwrap(), None);
assert!(!t.get::<trust::GpgVerify>().unwrap());
let remote = RepoConfig::parse(&format!("{ARCHIVE_CONFIG}[remote \"o\"]\n")).unwrap();
assert!(
remote
.section::<remote::Group>("o")
.unwrap()
.get::<remote::GpgVerify>()
.unwrap()
);
let g = cfg.section::<trust::Group>("g").unwrap();
assert_eq!(g.name(), "g");
assert!(g.get::<trust::GpgVerify>().unwrap());
assert!(g.get::<trust::GpgKeyPath>().unwrap().entries().is_empty());
assert_eq!(g.get::<trust::SignVerify>().unwrap(), SignVerify::Off);
}
#[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!(remote_names(&cfg), ["x"]);
let remote = cfg.section::<remote::Group>("x").unwrap();
assert_eq!(
remote.get::<remote::Url>().unwrap().as_deref(),
Some("https://2")
);
assert_eq!(remote.key_names().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!(remote_names(&cfg), ["x"]);
assert!(cfg.get::<repo::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 from_keyfile_and_parse_have_no_override() {
let mut overrides = Overrides::default();
overrides.force::<repo::Fsync>(false);
overrides.fallback::<repo::TmpExpirySecs>(5);
let text = format!("{ARCHIVE_CONFIG}fsync=true\n");
let held = RepoConfig::parse(&text)
.unwrap()
.with_overrides(Arc::new(overrides));
assert_eq!(
held.lookup::<repo::Fsync>().unwrap(),
Some(Lookup::Forced(false))
);
assert_eq!(
held.lookup::<repo::TmpExpirySecs>().unwrap(),
Some(Lookup::Fallback(5))
);
for cfg in [
RepoConfig::parse(&text).unwrap(),
RepoConfig::from_keyfile(held.keyfile().clone()).unwrap(),
] {
assert_eq!(
cfg.lookup::<repo::Fsync>().unwrap(),
Some(Lookup::File(true))
);
assert_eq!(
cfg.lookup::<repo::TmpExpirySecs>().unwrap(),
Some(Lookup::Default(86400))
);
}
}
#[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.section::<remote::Group>("signed").unwrap();
assert_eq!(
remote.get::<remote::SignVerify>().unwrap(),
SignVerify::Engines(vec!["ed25519".to_owned()])
);
assert_eq!(
remote.get::<remote::SignVerifySummary>().unwrap(),
SignVerify::All
);
assert_eq!(
remote.verification_key("ed25519").unwrap().as_deref(),
Some("AAAA")
);
assert_eq!(
remote.verification_file("ed25519").unwrap(),
Some(KeyPath {
value: PathBuf::from("/etc/keys.ed25519"),
origin: KeyOrigin::Config,
})
);
assert_eq!(remote.verification_key("spki").unwrap(), None);
assert_eq!(
remote.get::<remote::GpgKeyPath>().unwrap().entries(),
["/etc/one.gpg", "/etc/keys.d"]
);
let plain = cfg.section::<remote::Group>("signed").unwrap();
assert!(plain.get::<remote::GpgVerify>().unwrap());
let bare = RepoConfig::parse(
"[core]\nrepo_version=1\nmode=bare\n\n[remote \"plain\"]\nurl=http://ex/r\n",
)
.unwrap();
let bare = bare.section::<remote::Group>("plain").unwrap();
assert_eq!(bare.get::<remote::SignVerify>().unwrap(), SignVerify::Off);
assert_eq!(
bare.get::<remote::SignVerifySummary>().unwrap(),
SignVerify::Off
);
assert!(
bare.get::<remote::GpgKeyPath>()
.unwrap()
.entries()
.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.section::<remote::Group>("r")
.unwrap()
.get::<remote::GpgKeyPath>()
.unwrap()
.entries(),
*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.section::<remote::Group>("secure").unwrap();
assert_eq!(
remote
.get::<remote::TlsCaPath>()
.unwrap()
.as_ref()
.map(ConfigPath::as_str),
Some("/etc/ca.pem")
);
assert_eq!(
remote
.get::<remote::TlsClientCertPath>()
.unwrap()
.as_ref()
.map(ConfigPath::as_str),
Some("/etc/client.pem")
);
assert_eq!(
remote
.get::<remote::TlsClientKeyPath>()
.unwrap()
.as_ref()
.map(ConfigPath::as_str),
Some("/etc/client.key")
);
assert!(remote.get::<remote::TlsPermissive>().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.section::<remote::Group>("set")
.unwrap()
.get::<remote::Proxy>()
.unwrap()
.as_deref(),
Some("http://user:pw@proxy.ex.com:3128")
);
assert_eq!(
cfg.section::<remote::Group>("empty")
.unwrap()
.get::<remote::Proxy>()
.unwrap()
.as_deref(),
Some("")
);
assert_eq!(
cfg.section::<remote::Group>("blank")
.unwrap()
.get::<remote::Proxy>()
.unwrap()
.as_deref(),
Some("")
);
assert_eq!(
cfg.section::<remote::Group>("trail")
.unwrap()
.get::<remote::Proxy>()
.unwrap()
.as_deref(),
Some("http://p:1 ")
);
assert_eq!(
cfg.section::<remote::Group>("escape")
.unwrap()
.get::<remote::Proxy>()
.unwrap()
.as_deref(),
Some(" ")
);
assert_eq!(
cfg.section::<remote::Group>("plain")
.unwrap()
.get::<remote::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.section::<remote::Group>("central").unwrap();
assert_eq!(
remote.get::<remote::PushUrl>().unwrap().as_deref(),
Some("ssh://pusher@ex.com/srv/repo")
);
assert_eq!(
remote.get::<remote::SshCommand>().unwrap().as_deref(),
Some("ssh -o BatchMode=yes")
);
assert_eq!(
remote.get::<remote::ReceiveCommand>().unwrap().as_deref(),
Some("/opt/bin/ostrya receive")
);
assert_eq!(
remote
.get::<remote::PushTokenFile>()
.unwrap()
.as_ref()
.map(ConfigPath::as_str),
Some("/etc/push token")
);
assert_eq!(
remote.get::<remote::PushUser>().unwrap().as_deref(),
Some("alice")
);
assert_eq!(
remote.get::<remote::PullUrl>().unwrap().as_deref(),
Some("puller@ex.com:srv/repo")
);
assert_eq!(
remote.get::<remote::SendCommand>().unwrap().as_deref(),
Some("/opt/bin/ostrya send -v")
);
let plain = cfg.section::<remote::Group>("plain").unwrap();
assert_eq!(plain.get::<remote::PushUrl>().unwrap(), None);
assert_eq!(plain.get::<remote::SshCommand>().unwrap(), None);
assert_eq!(plain.get::<remote::ReceiveCommand>().unwrap(), None);
assert_eq!(plain.get::<remote::PushTokenFile>().unwrap(), None);
assert_eq!(plain.get::<remote::PushUser>().unwrap(), None);
assert_eq!(plain.get::<remote::PullUrl>().unwrap(), None);
assert_eq!(plain.get::<remote::SendCommand>().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()
.section::<remote::Group>("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"]
);
let key = "[remote \"r\"] mirrored-collection-ids";
for (keys, reason) in [
("mirrored-collection-ids=\n", "holds no collection id"),
(
"mirrored-collection-ids=;\n",
"holds the invalid collection id ''",
),
(
"mirrored-collection-ids=org.ex.A;;org.ex.B\n",
"holds the invalid collection id ''",
),
(
"mirrored-collection-ids=org/ex\n",
"holds the invalid collection id 'org/ex'",
),
(
"mirrored-collection-ids=1org.ex\n",
"holds the invalid collection id '1org.ex'",
),
(
"collection-id=org.ex.C\nmirrored-collection-ids=org.ex.A;org.ex.C\n",
"holds 'org.ex.C', the collection-id of the remote",
),
(
"collection-id=\\q\nmirrored-collection-ids=org/ex\n",
"holds the invalid collection id 'org/ex'",
),
] {
assert!(
matches!(ids(keys), Err(Error::InvalidFormat(m)) if m == format!("{key} {reason}")),
"{keys:?}: {:?}",
ids(keys)
);
}
}
fn read_located(path: &KeyPath, repo: Option<&Repo>) -> (String, PathBuf) {
use std::io::Read as _;
let (base, at, shown) = path.locate(repo);
let fd = crate::repo_fs::open_named(base, &at, crate::repo_fs::Named::File).unwrap();
let mut text = String::new();
std::fs::File::from(fd).read_to_string(&mut text).unwrap();
(text, shown)
}
#[test]
fn a_relative_key_path_resolves_against_the_base_of_its_source() {
use std::sync::Arc;
use crate::repo::RemotesDir;
use crate::repo_fs::TestDir;
use crate::{CreateOptions, OpenOptions};
let dir = TestDir::new("key-path");
let root = dir.path().join("repo");
let remotes = dir.path().join("remotes.d");
let conf = "[remote \"o\"]\nurl=http://h/\ntls-ca-path=k.pem\n";
let repo = ostrya_rt::block_on(async {
Repo::create(&root, CreateOptions::new(RepoMode::Archive))
.await
.unwrap()
});
drop(repo);
let mut text = std::fs::read_to_string(root.join("config")).unwrap();
text.push_str(&format!(
"[remote \"c\"]\nurl=http://h/\ntls-ca-path=k.pem\n\
[remote \"a\"]\nurl=http://h/\ntls-ca-path={}\n\
[remote \"p\"]\nurl=http://h/\ntls-ca-path=../k.pem\n",
root.join("in.d/../k.pem").display()
));
std::fs::write(root.join("config"), text).unwrap();
std::fs::create_dir(root.join("in.d")).unwrap();
std::fs::create_dir(&remotes).unwrap();
std::fs::write(root.join("k.pem"), "root").unwrap();
std::fs::write(root.join("in.d/k.pem"), "in-repo").unwrap();
std::fs::write(root.join("in.d/o.conf"), conf).unwrap();
std::fs::write(remotes.join("k.pem"), "path").unwrap();
std::fs::write(remotes.join("o.conf"), conf).unwrap();
let open = |dir: RemotesDir| {
ostrya_rt::block_on(OpenOptions::new().remotes_dir(dir).open(&root)).unwrap()
};
let fd = rustix::fs::open(
&remotes,
rustix::fs::OFlags::RDONLY | rustix::fs::OFlags::DIRECTORY,
rustix::fs::Mode::empty(),
)
.unwrap();
let cases = [
(RemotesDir::path(&remotes), "path", remotes.join("k.pem")),
(
RemotesDir::InRepo("in.d".into()),
"in-repo",
PathBuf::from("in.d/k.pem"),
),
(RemotesDir::Fd(Arc::new(fd)), "path", PathBuf::from("k.pem")),
];
for (remotes_dir, text, shown) in cases {
let repo = open(remotes_dir);
let path = repo
.config()
.section::<remote::Group>("o")
.unwrap()
.key_path::<remote::TlsCaPath>()
.unwrap()
.unwrap();
assert_eq!(path.origin, KeyOrigin::RemotesFile);
assert_eq!(read_located(&path, Some(&repo)), (text.to_owned(), shown));
let path = repo
.config()
.section::<remote::Group>("c")
.unwrap()
.key_path::<remote::TlsCaPath>()
.unwrap()
.unwrap();
assert_eq!(path.origin, KeyOrigin::Config);
assert_eq!(
read_located(&path, Some(&repo)),
("root".to_owned(), PathBuf::from("k.pem"))
);
}
let repo = open(RemotesDir::path(&remotes));
let absolute = repo.config().section::<remote::Group>("a").unwrap();
let path = absolute.key_path::<remote::TlsCaPath>().unwrap().unwrap();
assert_eq!(read_located(&path, Some(&repo)).0, "root");
let caller = KeyPath::caller(root.join("in.d/k.pem"));
assert_eq!(read_located(&caller, Some(&repo)).0, "in-repo");
let parent = repo.config().section::<remote::Group>("p").unwrap();
for result in [
parent.get::<remote::TlsCaPath>(),
parent.key_path::<remote::TlsCaPath>().map(|_| None),
] {
assert!(
matches!(&result, Err(Error::InvalidFormat(m)) if m == "[remote \"p\"] tls-ca-path \
../k.pem has a `..` component, which a relative path in a config cannot have"),
"{result:?}"
);
}
}
pub(crate) fn repos_with_remotes_file(root: &Path, sections: &str, conf: &str) -> Vec<Repo> {
use crate::repo::RemotesDir;
use crate::{CreateOptions, OpenOptions};
ostrya_rt::block_on(async {
Repo::create(root, CreateOptions::new(RepoMode::Archive))
.await
.unwrap();
});
let mut text = std::fs::read_to_string(root.join("config")).unwrap();
text.push_str(sections);
std::fs::write(root.join("config"), text).unwrap();
let remotes = root.join("remotes.d");
std::fs::create_dir(&remotes).unwrap();
std::fs::write(remotes.join("o.conf"), conf).unwrap();
let fd = std::os::fd::OwnedFd::from(std::fs::File::open(&remotes).unwrap());
[
RemotesDir::path(&remotes),
RemotesDir::InRepo(PathBuf::from("remotes.d")),
RemotesDir::from(fd),
]
.into_iter()
.map(|dir| ostrya_rt::block_on(OpenOptions::new().remotes_dir(dir).open(root)).unwrap())
.collect()
}
}
#[cfg(test)]
mod typed_key_tests {
use std::fmt::Debug;
use super::*;
use crate::config::typed::{OutputOf, ValueOf};
const BASE: &str = "[core]\nrepo_version=1\nmode=bare\n";
fn config_with(group: &str, line: &str) -> RepoConfig {
let text = if line.is_empty() {
BASE.to_owned()
} else {
format!("{BASE}[{group}]\n{line}\n")
};
RepoConfig::parse(&text).unwrap()
}
fn check_key<K>(raw: &str, want: ValueOf<K>, default: Option<ValueOf<K>>)
where
K: SingleKey + Key<<K as SingleKey>::Group>,
ValueOf<K>: Value + PartialEq + Debug + Clone,
OutputOf<K>: PartialEq + Debug,
{
let group = <<K as SingleKey>::Group as Group>::NAME;
let name = <K as Key<<K as SingleKey>::Group>>::NAME;
let set = config_with(group, &format!("{name}={raw}"));
assert_eq!(set.file_value::<K>().unwrap(), Some(want.clone()), "{name}");
assert_eq!(
set.lookup::<K>().unwrap(),
Some(Lookup::File(want.clone())),
"{name}"
);
assert_eq!(
set.get::<K>().unwrap(),
K::output(Some(want.clone())).unwrap(),
"{name}"
);
assert_eq!(ValueOf::<K>::parse(&want.format()), Ok(want), "{name}");
let absent = config_with(group, "");
assert_eq!(absent.file_value::<K>().unwrap(), None, "{name}");
assert_eq!(K::default_value(), default, "{name}");
assert_eq!(
absent.lookup::<K>().unwrap(),
default.clone().map(Lookup::Default),
"{name}"
);
if let Some(default) = default {
assert_eq!(
absent.get::<K>().unwrap(),
K::output(Some(default.clone())).unwrap(),
"{name}"
);
assert_eq!(
ValueOf::<K>::parse(&default.format()),
Ok(default),
"{name}"
);
}
}
fn check_remote_key<K>(raw: &str, want: K::Value, default: Option<K::Value>)
where
K: Key<remote::Group>,
K::Value: Value + PartialEq + Debug + Clone,
K::Output: PartialEq + Debug,
{
let name = K::NAME;
let set = RepoConfig::parse(&format!("{BASE}[remote \"r\"]\n{name}={raw}\n")).unwrap();
let section = set.section::<remote::Group>("r").unwrap();
assert_eq!(
section.file_value::<K>().unwrap(),
Some(want.clone()),
"{name}"
);
assert_eq!(
section.lookup::<K>().unwrap(),
Some(Lookup::File(want.clone())),
"{name}"
);
assert_eq!(
section.get::<K>().unwrap(),
K::output(Some(want.clone())).unwrap(),
"{name}"
);
assert_eq!(K::Value::parse(&want.format()), Ok(want), "{name}");
let absent = RepoConfig::parse(&format!("{BASE}[remote \"r\"]\nother=1\n")).unwrap();
let section = absent.section::<remote::Group>("r").unwrap();
assert_eq!(section.file_value::<K>().unwrap(), None, "{name}");
assert_eq!(K::default_value(), default, "{name}");
assert_eq!(
section.lookup::<K>().unwrap(),
default.clone().map(Lookup::Default),
"{name}"
);
assert_eq!(
section.get::<K>().unwrap(),
K::output(default).unwrap(),
"{name}"
);
}
#[test]
fn the_groups_list_their_keys_in_order() {
assert_eq!(<repo::Group as Group>::NAME, "core");
assert_eq!(
<repo::Group as Group>::KEYS,
[
"repo_version",
"mode",
"collection-id",
"fsync",
"per-object-fsync",
"locking",
"lock-timeout-secs",
"tmp-expiry-secs",
"tombstone-commits",
"indexed-deltas",
"disable-xattrs",
"default-repo-finders",
"min-free-space-size",
"min-free-space-percent",
"auto-update-summary",
"add-remotes-config-dir",
]
);
assert_eq!(<archive::Group as Group>::NAME, "archive");
assert_eq!(<archive::Group as Group>::KEYS, ["zlib-level"]);
assert_eq!(<ex_integrity::Group as Group>::NAME, "ex-integrity");
assert_eq!(
<ex_integrity::Group as Group>::KEYS,
["composefs", "fsverity"]
);
assert_eq!(<ex_ostrya::Group as Group>::NAME, "ex-ostrya");
assert_eq!(
<ex_ostrya::Group as Group>::KEYS,
[
"keep-detached-related",
"gc-weak-references",
"remotes-config-dir"
]
);
assert_eq!(<server::Group as Group>::NAME, "ex-ostrya server");
assert_eq!(
<server::Group as Group>::KEYS,
[
"listen",
"tls-cert",
"tls-key",
"tls-client-ca",
"trusted-proxy",
"trusted-proxy-header",
"trusted-proxy-client-cert",
"proxy-protocol",
"allow-cleartext-credentials",
"session-timeout",
"max-sessions",
"parallel-uploads",
"body-timeout",
"sign-summary",
]
);
const { assert!(!<server::Group as Group>::NAMED) };
const { assert!(<server::Group as Group>::CLOSED) };
assert!(<server::Group as Group>::OVERRIDABLE.is_empty());
assert_eq!(
<server::Group as Group>::SETTABLE,
<server::Group as Group>::KEYS
);
assert_eq!(<remote::Group as Group>::NAME, "remote");
assert_eq!(
<remote::Group as Group>::KEYS,
[
"url",
"contenturl",
"metalink",
"branches",
"collection-id",
"mirrored-collection-ids",
"gpg-verify",
"gpg-verify-summary",
"gpgkeypath",
"sign-verify",
"sign-verify-summary",
"verification-ed25519-key",
"verification-ed25519-file",
"verification-spki-key",
"verification-spki-file",
"trust",
"tls-ca-path",
"tls-client-cert-path",
"tls-client-key-path",
"tls-permissive",
"proxy",
"push-url",
"pull-url",
"push-branches",
"pull-branches",
"ssh-command",
"receive-command",
"send-command",
"push-token-file",
"push-user",
"s3-region",
"s3-endpoint",
"s3-addressing",
"s3-profile",
]
);
const { assert!(<remote::Group as Group>::NAMED) };
const { assert!(!<remote::Group as Group>::CLOSED) };
assert!(<remote::Group as Group>::OVERRIDABLE.is_empty());
assert!(<remote::Group as Group>::SETTABLE.is_empty());
for (named, closed) in [
(
<repo::Group as Group>::NAMED,
<repo::Group as Group>::CLOSED,
),
(
<archive::Group as Group>::NAMED,
<archive::Group as Group>::CLOSED,
),
(
<ex_integrity::Group as Group>::NAMED,
<ex_integrity::Group as Group>::CLOSED,
),
(
<ex_ostrya::Group as Group>::NAMED,
<ex_ostrya::Group as Group>::CLOSED,
),
] {
assert!(!named);
assert!(!closed);
}
}
#[test]
fn each_key_parses_defaults_and_formats() {
let text = |items: &[&str]| items.iter().map(|s| (*s).to_owned()).collect::<Vec<_>>();
check_key::<repo::CollectionId>(
"org.ex.C",
CollectionIdValue::try_from("org.ex.C").unwrap(),
None,
);
check_key::<repo::Fsync>("false", false, Some(true));
check_key::<repo::PerObjectFsync>("1", true, Some(false));
check_key::<repo::Locking>("0", false, Some(true));
check_key::<repo::LockTimeoutSecs>(
"-1",
LockTimeout::try_from(-1).unwrap(),
Some(LockTimeout::try_from(300).unwrap()),
);
check_key::<repo::TmpExpirySecs>("60", 60, Some(86400));
check_key::<repo::TombstoneCommits>("true", true, Some(false));
check_key::<repo::IndexedDeltas>("false", false, Some(true));
check_key::<repo::DisableXattrs>("true", true, Some(false));
check_key::<repo::DefaultRepoFinders>(
"lan;config;",
text(&["lan", "config"]),
Some(text(&["config", "mount"])),
);
check_key::<repo::MinFreeSpaceSize>(
"2GB",
SizeSpec {
value: 2,
unit: SizeUnit::Giga,
},
None,
);
check_key::<repo::MinFreeSpacePercent>(
"100",
FreeSpacePercent::try_from(100).unwrap(),
Some(FreeSpacePercent::try_from(3).unwrap()),
);
check_key::<repo::AutoUpdateSummary>("true", true, Some(false));
check_key::<repo::AddRemotesConfigDir>("true", true, Some(false));
check_key::<archive::ZlibLevel>("9", 9, Some(6));
check_key::<ex_integrity::Composefs>("maybe", Tristate::Maybe, Some(Tristate::No));
check_key::<ex_integrity::Fsverity>("yes", Tristate::Yes, None);
check_key::<ex_ostrya::KeepDetachedRelated>("false", false, Some(true));
check_key::<ex_ostrya::GcWeakReferences>(
"tmp/**;!tmp/keep",
ReceiveSelector::parse(["tmp/**", "!tmp/keep"]).unwrap(),
None,
);
check_key::<ex_ostrya::RemotesConfigDir>(
"/etc/r.d",
RemotesConfigPath::try_from("/etc/r.d").unwrap(),
None,
);
check_key::<server::Listen>(
"127.0.0.1:80;[::1]:81",
ListenAddrs::try_from(vec![
"127.0.0.1:80".parse().unwrap(),
"[::1]:81".parse().unwrap(),
])
.unwrap(),
None,
);
let pem = |p: &str| PemPath::try_from(p).unwrap();
check_key::<server::TlsCert>(r"c\s.pem", pem("c .pem"), None);
check_key::<server::TlsKey>("/k.pem", pem("/k.pem"), None);
check_key::<server::TlsClientCa>("ca.pem", pem("ca.pem"), None);
check_key::<server::TrustedProxy>(
"10.0.0.0/8",
TrustedNets::try_from(vec![crate::access::IpNet::parse("10.0.0.0/8").unwrap()])
.unwrap(),
None,
);
check_key::<server::TrustedProxyHeader>(
"x-real-ip",
crate::access::ForwardedHeader::XRealIp,
None,
);
check_key::<server::TrustedProxyClientCert>(
"X-Cert",
HeaderName::try_from("X-Cert").unwrap(),
None,
);
check_key::<server::ProxyProtocol>("1", true, None);
check_key::<server::AllowCleartextCredentials>("false", false, None);
let positive = |n: i64| PositiveInt::try_from(n).unwrap();
check_key::<server::SessionTimeout>("600", positive(600), None);
check_key::<server::MaxSessions>("9223372036854775807", positive(i64::MAX), None);
check_key::<server::ParallelUploads>("31", UploadStreams::try_from(31).unwrap(), None);
check_key::<server::BodyTimeout>("1", positive(1), None);
check_key::<server::SignSummary>(
"b;a;b",
KeyGroupNames::try_from(text(&["b", "a"])).unwrap(),
None,
);
let path = |p: &str| ConfigPath::try_from(p).unwrap();
let text_of = |v: &str| v.to_owned();
check_remote_key::<remote::Url>("https://h/r", text_of("https://h/r"), None);
check_remote_key::<remote::ContentUrl>(r"https://h/\sc", text_of("https://h/ c"), None);
check_remote_key::<remote::Metalink>("https://h/m", text_of("https://h/m"), None);
check_remote_key::<remote::Branches>("a;b;", text(&["a", "b"]), None);
check_remote_key::<remote::CollectionId>("org.ex.C", text_of("org.ex.C"), None);
check_remote_key::<remote::MirroredCollectionIds>(
"org.ex.A;org.ex.B;org.ex.A",
CollectionIdList::try_from(text(&["org.ex.A", "org.ex.B"])).unwrap(),
None,
);
check_remote_key::<remote::GpgVerify>("false", false, Some(true));
check_remote_key::<remote::GpgVerifySummary>("1", true, Some(false));
check_remote_key::<remote::GpgKeyPath>(
r"/a.gpg;k\s.gpg;",
KeyringPaths::parse(r"/a.gpg;k\s.gpg").unwrap(),
Some(KeyringPaths::default()),
);
check_remote_key::<remote::SignVerify>(
"ed25519",
SignVerify::Engines(text(&["ed25519"])),
Some(SignVerify::Off),
);
check_remote_key::<remote::SignVerifySummary>(
"true",
SignVerify::All,
Some(SignVerify::Off),
);
check_remote_key::<remote::VerificationEd25519Key>("AAAA", text_of("AAAA"), None);
check_remote_key::<remote::VerificationEd25519File>("/k", path("/k"), None);
check_remote_key::<remote::VerificationSpkiKey>("BBBB", text_of("BBBB"), None);
check_remote_key::<remote::VerificationSpkiFile>("k.pem", path("k.pem"), None);
check_remote_key::<remote::Trust>("t", TrustGroupName::try_from("t").unwrap(), None);
check_remote_key::<remote::TlsCaPath>("/ca.pem", path("/ca.pem"), None);
check_remote_key::<remote::TlsClientCertPath>(r"c\s.pem", path("c .pem"), None);
check_remote_key::<remote::TlsClientKeyPath>("", path(""), None);
check_remote_key::<remote::TlsPermissive>("true", true, Some(false));
check_remote_key::<remote::Proxy>("http://p:1 ", text_of("http://p:1 "), None);
check_remote_key::<remote::PushUrl>("ssh://h/p", text_of("ssh://h/p"), None);
check_remote_key::<remote::PullUrl>("s3://b/p", text_of("s3://b/p"), None);
check_remote_key::<remote::PushBranches>(
"apps/**;!apps/b",
ReceiveSelector::parse(["apps/**", "!apps/b"]).unwrap(),
None,
);
check_remote_key::<remote::PullBranches>(
"",
ReceiveSelector::parse(std::iter::empty::<&str>()).unwrap(),
None,
);
check_remote_key::<remote::SshCommand>("ssh -v", text_of("ssh -v"), None);
check_remote_key::<remote::ReceiveCommand>("r", text_of("r"), None);
check_remote_key::<remote::SendCommand>("s", text_of("s"), None);
check_remote_key::<remote::PushTokenFile>("t.txt", path("t.txt"), None);
check_remote_key::<remote::PushUser>("alice", text_of("alice"), None);
check_remote_key::<remote::S3Region>("eu-1", text_of("eu-1"), None);
check_remote_key::<remote::S3Endpoint>("https://s3", text_of("https://s3"), None);
check_remote_key::<remote::S3Addressing>("path", text_of("path"), None);
check_remote_key::<remote::S3Profile>("p", text_of("p"), None);
let cfg = RepoConfig::parse(BASE).unwrap();
assert_eq!(cfg.get::<repo::RepoVersion>().unwrap(), 1);
assert_eq!(cfg.get::<repo::Mode>().unwrap(), RepoMode::Bare);
assert_eq!(
cfg.lookup::<repo::Mode>().unwrap(),
Some(Lookup::File(RepoMode::Bare))
);
assert_eq!(
<repo::RepoVersion as Key<repo::Group>>::default_value(),
None
);
assert_eq!(<repo::Mode as Key<repo::Group>>::default_value(), None);
}
#[test]
fn the_marker_traits_follow_the_key_table() {
fn ov<K: Overridable>() {}
fn st<K: Settable>() {}
ov::<repo::Fsync>();
ov::<repo::PerObjectFsync>();
ov::<repo::LockTimeoutSecs>();
ov::<repo::TmpExpirySecs>();
ov::<repo::TombstoneCommits>();
ov::<repo::IndexedDeltas>();
ov::<repo::DefaultRepoFinders>();
ov::<repo::MinFreeSpaceSize>();
ov::<repo::MinFreeSpacePercent>();
ov::<repo::AutoUpdateSummary>();
ov::<repo::AddRemotesConfigDir>();
ov::<archive::ZlibLevel>();
ov::<ex_integrity::Composefs>();
ov::<ex_integrity::Fsverity>();
ov::<ex_ostrya::KeepDetachedRelated>();
ov::<ex_ostrya::GcWeakReferences>();
st::<repo::CollectionId>();
st::<repo::Fsync>();
st::<repo::PerObjectFsync>();
st::<repo::Locking>();
st::<repo::LockTimeoutSecs>();
st::<repo::TmpExpirySecs>();
st::<repo::TombstoneCommits>();
st::<repo::IndexedDeltas>();
st::<repo::DisableXattrs>();
st::<repo::DefaultRepoFinders>();
st::<repo::MinFreeSpaceSize>();
st::<repo::MinFreeSpacePercent>();
st::<repo::AutoUpdateSummary>();
st::<repo::AddRemotesConfigDir>();
st::<archive::ZlibLevel>();
st::<ex_integrity::Composefs>();
st::<ex_integrity::Fsverity>();
st::<ex_ostrya::KeepDetachedRelated>();
st::<ex_ostrya::GcWeakReferences>();
st::<ex_ostrya::RemotesConfigDir>();
}
#[test]
fn the_marker_lists_follow_the_marker_traits() {
fn ov<K: Overridable + Key<<K as SingleKey>::Group>>() -> &'static str {
<K as Key<<K as SingleKey>::Group>>::NAME
}
fn st<K: Settable + Key<<K as SingleKey>::Group>>() -> &'static str {
<K as Key<<K as SingleKey>::Group>>::NAME
}
assert_eq!(
<repo::Group as Group>::OVERRIDABLE,
[
ov::<repo::Fsync>(),
ov::<repo::PerObjectFsync>(),
ov::<repo::LockTimeoutSecs>(),
ov::<repo::TmpExpirySecs>(),
ov::<repo::TombstoneCommits>(),
ov::<repo::IndexedDeltas>(),
ov::<repo::DefaultRepoFinders>(),
ov::<repo::MinFreeSpaceSize>(),
ov::<repo::MinFreeSpacePercent>(),
ov::<repo::AutoUpdateSummary>(),
ov::<repo::AddRemotesConfigDir>(),
]
);
assert_eq!(
<repo::Group as Group>::OVERRIDABLE,
[
"fsync",
"per-object-fsync",
"lock-timeout-secs",
"tmp-expiry-secs",
"tombstone-commits",
"indexed-deltas",
"default-repo-finders",
"min-free-space-size",
"min-free-space-percent",
"auto-update-summary",
"add-remotes-config-dir",
]
);
assert_eq!(
<archive::Group as Group>::OVERRIDABLE,
[ov::<archive::ZlibLevel>()]
);
assert_eq!(<archive::Group as Group>::OVERRIDABLE, ["zlib-level"]);
assert_eq!(
<ex_integrity::Group as Group>::OVERRIDABLE,
[
ov::<ex_integrity::Composefs>(),
ov::<ex_integrity::Fsverity>()
]
);
assert_eq!(
<ex_integrity::Group as Group>::OVERRIDABLE,
["composefs", "fsverity"]
);
assert_eq!(
<ex_ostrya::Group as Group>::OVERRIDABLE,
[
ov::<ex_ostrya::KeepDetachedRelated>(),
ov::<ex_ostrya::GcWeakReferences>()
]
);
assert_eq!(
<ex_ostrya::Group as Group>::OVERRIDABLE,
["keep-detached-related", "gc-weak-references"]
);
assert_eq!(
<repo::Group as Group>::SETTABLE,
[
st::<repo::CollectionId>(),
st::<repo::Fsync>(),
st::<repo::PerObjectFsync>(),
st::<repo::Locking>(),
st::<repo::LockTimeoutSecs>(),
st::<repo::TmpExpirySecs>(),
st::<repo::TombstoneCommits>(),
st::<repo::IndexedDeltas>(),
st::<repo::DisableXattrs>(),
st::<repo::DefaultRepoFinders>(),
st::<repo::MinFreeSpaceSize>(),
st::<repo::MinFreeSpacePercent>(),
st::<repo::AutoUpdateSummary>(),
st::<repo::AddRemotesConfigDir>(),
]
);
assert_eq!(
<repo::Group as Group>::SETTABLE,
&<repo::Group as Group>::KEYS[2..]
);
assert_eq!(
<archive::Group as Group>::SETTABLE,
[st::<archive::ZlibLevel>()]
);
assert_eq!(
<archive::Group as Group>::SETTABLE,
<archive::Group as Group>::KEYS
);
assert_eq!(
<ex_integrity::Group as Group>::SETTABLE,
[
st::<ex_integrity::Composefs>(),
st::<ex_integrity::Fsverity>()
]
);
assert_eq!(
<ex_integrity::Group as Group>::SETTABLE,
<ex_integrity::Group as Group>::KEYS
);
assert_eq!(
<ex_ostrya::Group as Group>::SETTABLE,
[
st::<ex_ostrya::KeepDetachedRelated>(),
st::<ex_ostrya::GcWeakReferences>(),
st::<ex_ostrya::RemotesConfigDir>()
]
);
assert_eq!(
<ex_ostrya::Group as Group>::SETTABLE,
<ex_ostrya::Group as Group>::KEYS
);
assert_eq!(<test_single::Group as Group>::OVERRIDABLE, ["jobs"]);
assert_eq!(<test_single::Group as Group>::SETTABLE, ["name", "jobs"]);
assert!(<test_named::Group as Group>::OVERRIDABLE.is_empty());
assert!(<test_named::Group as Group>::SETTABLE.is_empty());
}
fn expect<T: PartialEq + Debug>(
got: Result<T>,
want: std::result::Result<T, &str>,
case: &str,
) {
assert_eq!(
got.map_err(|err| err.to_string()),
want.map_err(str::to_owned),
"{case}"
);
}
#[test]
fn typed_reads_give_the_value_of_the_file_or_the_default() {
type Bool = fn(&RepoConfig) -> Result<bool>;
let bools: [(&str, &str, Bool, bool); 9] = [
("core", "fsync", |c| c.get::<repo::Fsync>(), true),
(
"core",
"per-object-fsync",
|c| c.get::<repo::PerObjectFsync>(),
false,
),
("core", "locking", |c| c.get::<repo::Locking>(), true),
(
"core",
"tombstone-commits",
|c| c.get::<repo::TombstoneCommits>(),
false,
),
(
"core",
"indexed-deltas",
|c| c.get::<repo::IndexedDeltas>(),
true,
),
(
"core",
"disable-xattrs",
|c| c.get::<repo::DisableXattrs>(),
false,
),
(
"core",
"auto-update-summary",
|c| c.get::<repo::AutoUpdateSummary>(),
false,
),
(
"core",
"add-remotes-config-dir",
|c| c.get::<repo::AddRemotesConfigDir>(),
false,
),
(
"ex-ostrya",
"keep-detached-related",
|c| c.get::<ex_ostrya::KeepDetachedRelated>(),
true,
),
];
for (group, key, read, default) in bools {
let not_bool =
|raw: &str| format!("keyfile: value '{raw}' for {group}.{key} is not a boolean");
let (yes, empty) = (not_bool("yes"), not_bool(""));
for (raw, want) in [
(None, Ok(default)),
(Some("true"), Ok(true)),
(Some("0"), Ok(false)),
(Some("yes"), Err(yes.as_str())),
(Some(""), Err(empty.as_str())),
] {
let line = raw.map(|r| format!("{key}={r}")).unwrap_or_default();
let cfg = config_with(group, &line);
expect(read(&cfg), want, &format!("{key}={raw:?}"));
}
}
type Int = fn(&RepoConfig) -> Result<i64>;
let ints: [(&str, &str, Int, i64, Option<&str>); 3] = [
(
"core",
"lock-timeout-secs",
|c| c.get::<repo::LockTimeoutSecs>().map(LockTimeout::get),
300,
Some("invalid format: [core] lock-timeout-secs -2 is below -1"),
),
(
"core",
"tmp-expiry-secs",
|c| c.get::<repo::TmpExpirySecs>(),
86400,
None,
),
(
"archive",
"zlib-level",
|c| c.get::<archive::ZlibLevel>(),
6,
None,
),
];
for (group, key, read, default, below) in ints {
let not_int =
|raw: &str| format!("keyfile: value '{raw}' for {group}.{key} is not an integer");
let (plus, x) = (not_int("+3"), not_int("x"));
for (raw, want) in [
(None, Ok(default)),
(Some("-1"), Ok(-1)),
(Some("30"), Ok(30)),
(Some("-2"), below.map_or(Ok(-2), Err)),
(Some("+3"), Err(plus.as_str())),
(Some("x"), Err(x.as_str())),
] {
let line = raw.map(|r| format!("{key}={r}")).unwrap_or_default();
let cfg = config_with(group, &line);
expect(read(&cfg), want, &format!("{key}={raw:?}"));
}
}
let finders = |v: &[&str]| v.iter().map(|s| (*s).to_owned()).collect::<Vec<_>>();
for (raw, want) in [
(None, Ok(finders(&["config", "mount"]))),
(Some("a;b;"), Ok(finders(&["a", "b"]))),
(Some(r"a\sb"), Ok(finders(&["a b"]))),
(Some(r"a\q"), Err(r"keyfile: invalid escape '\q'")),
] {
let line = raw
.map(|r| format!("default-repo-finders={r}"))
.unwrap_or_default();
let cfg = config_with("core", &line);
expect(
cfg.get::<repo::DefaultRepoFinders>(),
want,
&format!("default-repo-finders={raw:?}"),
);
}
for (raw, want) in [
(None, Ok(MinFreeSpace::Percent(3))),
(Some("0"), Ok(MinFreeSpace::Percent(0))),
(Some("100"), Ok(MinFreeSpace::Percent(100))),
(
Some("101"),
Err("invalid format: [core] min-free-space-percent 101 is out of the range 0-100"),
),
(
Some("-1"),
Err("invalid format: [core] min-free-space-percent -1 is out of the range 0-100"),
),
(
Some("x"),
Err("keyfile: value 'x' for core.min-free-space-percent is not an integer"),
),
] {
let line = raw
.map(|r| format!("min-free-space-percent={r}"))
.unwrap_or_default();
let cfg = config_with("core", &line);
expect(
cfg.min_free_space(),
want,
&format!("min-free-space-percent={raw:?}"),
);
}
let size = |value, unit| Ok(MinFreeSpace::Size(SizeSpec { value, unit }));
for (raw, want) in [
("min-free-space-size=2GB", size(2, SizeUnit::Giga)),
("min-free-space-size=1TB", size(1, SizeUnit::Tera)),
(
"min-free-space-size=5XB",
Err(
"invalid format: [core] min-free-space-size value '5XB' is not of the form \
123MB, 123GB, or 123TB",
),
),
(
"min-free-space-size=3MB\nmin-free-space-percent=x",
size(3, SizeUnit::Mega),
),
] {
expect(config_with("core", raw).min_free_space(), want, raw);
}
for (raw, want) in [
(None, Ok(Tristate::No)),
(Some("maybe"), Ok(Tristate::Maybe)),
(
Some("x"),
Err("invalid format: [ex-integrity] composefs value 'x' is not no, maybe, or yes"),
),
(Some(r"\q"), Err(r"keyfile: invalid escape '\q'")),
] {
let line = raw.map(|r| format!("composefs={r}")).unwrap_or_default();
let cfg = config_with("ex-integrity", &line);
expect(
cfg.get::<ex_integrity::Composefs>(),
want,
&format!("composefs={raw:?}"),
);
}
for (raw, want) in [
("yes", Ok(Tristate::Yes)),
(
"true",
Err(
"invalid format: [ex-integrity] fsverity value 'true' is not no, maybe, or yes",
),
),
(r"\q", Err(r"keyfile: invalid escape '\q'")),
] {
let cfg = config_with("ex-integrity", &format!("fsverity={raw}"));
expect(cfg.fsverity(), want, raw);
}
assert_eq!(
config_with("ex-integrity", "")
.get::<ex_integrity::Fsverity>()
.unwrap(),
None
);
for (raw, want) in [
(None, Ok(None)),
(
Some("tmp/**;!tmp/keep;"),
Ok(Some("tmp/**;!tmp/keep;".to_owned())),
),
(
Some("tmp/**;r*:x"),
Err(
"invalid format: [ex-ostrya] gc-weak-references holds a malformed entry: \
malformed receive pattern 'r*:x': a remote part is one remote or '*'",
),
),
(
Some("!tmp/**"),
Err(
"invalid format: [ex-ostrya] gc-weak-references: the list holds no pattern \
without '!'",
),
),
(Some(r"a\q"), Err(r"keyfile: invalid escape '\q'")),
] {
let line = raw
.map(|r| format!("gc-weak-references={r}"))
.unwrap_or_default();
let cfg = config_with("ex-ostrya", &line);
expect(
cfg.gc_weak_references()
.map(|s| s.as_ref().map(Value::format)),
want,
&format!("gc-weak-references={raw:?}"),
);
}
for raw in [None, Some("org.ex.C"), Some(r"org\q")] {
let line = raw
.map(|r| format!("collection-id={r}"))
.unwrap_or_default();
let text = format!("{BASE}{line}\n");
match RepoConfig::parse(&text) {
Ok(cfg) => assert_eq!(
cfg.get::<repo::CollectionId>()
.unwrap()
.as_ref()
.map(CollectionIdValue::as_str),
cfg.collection_id(),
"{raw:?}"
),
Err(err) => {
let mut kf = KeyFile::parse(BASE).unwrap();
kf.set_value(CORE, "collection-id", raw.unwrap()).unwrap();
let cfg_err = typed_read_of(kf);
assert_eq!(cfg_err, err.to_string(), "{raw:?}");
}
}
}
let cfg = RepoConfig::parse(BASE).unwrap();
assert_eq!(cfg.get::<repo::Mode>().unwrap(), cfg.mode());
assert_eq!(cfg.get::<repo::RepoVersion>().unwrap(), cfg.repo_version());
let dir = |kind: &'static str, path: &str| Ok(Some((kind, PathBuf::from(path))));
for (raw, want) in [
("/etc/r.d", dir("path", "/etc/r.d")),
("r.d", dir("in-repo", "r.d")),
("/etc/../r.d", dir("path", "/etc/../r.d")),
(
"",
Err("invalid format: [ex-ostrya] remotes-config-dir is empty"),
),
(
"a\0b",
Err("invalid format: [ex-ostrya] remotes-config-dir holds a NUL byte"),
),
(
"../r.d",
Err(
"invalid format: [ex-ostrya] remotes-config-dir ../r.d has a `..` \
component, which a relative path in a config cannot have",
),
),
(r"\q", Err(r"keyfile: invalid escape '\q'")),
] {
let cfg = config_with("ex-ostrya", &format!("remotes-config-dir={raw}"));
let read = crate::remotes_dir::from_key(&cfg).map(|dir| {
dir.map(|dir| match dir {
crate::repo::RemotesDir::Path(p) => ("path", p),
crate::repo::RemotesDir::InRepo(p) => ("in-repo", p),
crate::repo::RemotesDir::Fd(_) => unreachable!(),
})
});
expect(read, want, raw);
}
assert!(
crate::remotes_dir::from_key(&config_with("ex-ostrya", ""))
.unwrap()
.is_none()
);
}
#[test]
fn a_remote_key_refusal_names_the_section() {
let read =
|line: &str| RepoConfig::parse(&format!("{BASE}[remote \"o\"]\n{line}\n")).unwrap();
let cfg = read("pull-branches=apps/**;r*:x");
let section = cfg.section::<remote::Group>("o").unwrap();
assert_eq!(
section
.get::<remote::PullBranches>()
.unwrap_err()
.to_string(),
"invalid format: [remote \"o\"] pull-branches holds a malformed entry: malformed \
receive pattern 'r*:x': a remote part is one remote or '*'"
);
let cfg = read("gpgkeypath=/a;../b");
let section = cfg.section::<remote::Group>("o").unwrap();
assert_eq!(
section.get::<remote::GpgKeyPath>().unwrap_err().to_string(),
"invalid format: [remote \"o\"] gpgkeypath ../b has a `..` component, which a \
relative path in a config cannot have"
);
let cfg = read("gpg-verify=maybe");
let section = cfg.section::<remote::Group>("o").unwrap();
assert_eq!(
section.get::<remote::GpgVerify>().unwrap_err().to_string(),
"keyfile: value 'maybe' for remote \"o\".gpg-verify is not a boolean"
);
}
fn typed_read_of(kf: KeyFile) -> String {
let raw = kf.get_value(CORE, "collection-id").unwrap();
let err = <CollectionIdValue as Value>::parse(raw).unwrap_err();
value::value_error(CORE, "collection-id", raw, err).to_string()
}
#[test]
fn collection_id_refuses_an_id_that_fails_the_rule() {
let cfg = config_with("core", "collection-id=a b");
assert_eq!(cfg.collection_id(), Some("a b"));
assert_eq!(
cfg.get::<repo::CollectionId>().unwrap_err().to_string(),
"invalid format: [core] collection-id value 'a b' is not a valid collection id"
);
}
crate::config_group! {
pub group test_single = "ex-test" {
Name: Option<String> = "name";
Jobs: u32 = "jobs", default 4, overridable;
Strict: bool = "strict", default false, fixed;
}
}
crate::config_group! {
pub group test_named = named "ex-test n", closed {
Arch: String = "arch", required;
Tags: Vec<String> = "tags", default Vec::new();
Next: Option<GroupRef<test_named::Group>> = "next";
}
}
#[test]
fn a_user_group_reads_its_sections() {
let text = format!(
"{BASE}[ex-test]\njobs=8\n\
[ex-test n \"b\"]\narch=arm64\nnext=a\n\
[remote \"o\"]\nurl=http://o/\n\
[ex-test n \"a\"]\narch=amd64\ntags=x;y;\n\
[ex-test n \"c\"]\ntags=z\n\
[ex-test nx \"d\"]\narch=amd64\n"
);
let cfg = RepoConfig::parse(&text).unwrap();
assert_eq!(cfg.get::<test_single::Jobs>().unwrap(), 8);
assert_eq!(cfg.get::<test_single::Name>().unwrap(), None);
assert!(!cfg.get::<test_single::Strict>().unwrap());
let names: Vec<_> = cfg
.sections::<test_named::Group>()
.map(|s| s.name().to_owned())
.collect();
assert_eq!(names, ["b", "a", "c"]);
assert!(cfg.section::<test_named::Group>("absent").is_none());
let b = cfg.section::<test_named::Group>("b").unwrap();
assert_eq!(b.name(), "b");
assert_eq!(b.get::<test_named::Arch>().unwrap(), "arm64");
assert_eq!(b.get::<test_named::Tags>().unwrap(), Vec::<String>::new());
assert_eq!(
b.lookup::<test_named::Tags>().unwrap(),
Some(Lookup::Default(Vec::new()))
);
assert_eq!(b.file_value::<test_named::Tags>().unwrap(), None);
let next = b.get::<test_named::Next>().unwrap().unwrap();
assert_eq!(next, GroupRef::new("a").unwrap());
let a = cfg.resolve(&next).unwrap();
assert_eq!(a.get::<test_named::Tags>().unwrap(), ["x", "y"]);
assert_eq!(a.get::<test_named::Next>().unwrap(), None);
let err = cfg
.resolve(&GroupRef::<test_named::Group>::new("z").unwrap())
.unwrap_err();
assert_eq!(
err.to_string(),
"invalid format: the config has no [ex-test n \"z\"] group"
);
let c = cfg.section::<test_named::Group>("c").unwrap();
assert_eq!(
c.get::<test_named::Arch>().unwrap_err().to_string(),
"invalid format: [ex-test n \"c\"] has no arch"
);
assert_eq!(c.lookup::<test_named::Arch>().unwrap(), None);
const { assert!(<test_named::Group as Group>::CLOSED) };
const { assert!(<test_named::Group as Group>::NAMED) };
assert_eq!(<test_named::Group as Group>::KEYS, ["arch", "tags", "next"]);
}
#[test]
fn a_typed_read_names_the_group_header_in_an_error() {
let text = format!(
"{BASE}[ex-test]\njobs=-1\n[ex-test n \"a\"]\narch=amd64\nnext=\n\
[ex-test n \"b\"]\narch=\\q\n"
);
let cfg = RepoConfig::parse(&text).unwrap();
assert_eq!(
cfg.get::<test_single::Jobs>().unwrap_err().to_string(),
"invalid format: [ex-test] jobs -1 is out of the range 0-4294967295"
);
let a = cfg.section::<test_named::Group>("a").unwrap();
assert_eq!(
a.get::<test_named::Next>().unwrap_err().to_string(),
"invalid format: [ex-test n \"a\"] next is empty"
);
let b = cfg.section::<test_named::Group>("b").unwrap();
assert_eq!(
b.get::<test_named::Arch>().unwrap_err().to_string(),
r"keyfile: invalid escape '\q'"
);
crate::config_group! {
pub group flags = named "ex-flags" {
On: Option<bool> = "on";
}
}
let cfg = RepoConfig::parse(&format!("{BASE}[ex-flags \"s\"]\non=x\n")).unwrap();
assert_eq!(
cfg.section::<flags::Group>("s")
.unwrap()
.get::<flags::On>()
.unwrap_err()
.to_string(),
"keyfile: value 'x' for ex-flags \"s\".on is not a boolean"
);
}
#[test]
fn config_edit_sets_and_removes_keys() {
let mut kf = KeyFile::parse(&format!("{BASE}fsync=true\n")).unwrap();
let mut edit = ConfigEdit::new(&mut kf);
edit.set::<repo::Fsync>(false).unwrap();
edit.set::<repo::Locking>(false).unwrap();
edit.set::<archive::ZlibLevel>(9).unwrap();
edit.set::<ex_ostrya::RemotesConfigDir>(RemotesConfigPath::try_from(" r.d").unwrap())
.unwrap();
assert!(edit.remove::<repo::Locking>());
assert!(!edit.remove::<repo::Locking>());
edit.set::<test_single::Name>(" x".to_owned()).unwrap();
assert_eq!(
kf.to_string(),
"[core]\nrepo_version=1\nmode=bare\nfsync=false\n\n\
[archive]\nzlib-level=9\n\n\
[ex-ostrya]\nremotes-config-dir=\\sr.d\n\n\
[ex-test]\nname=\\s\\sx\n"
);
let cfg = RepoConfig::from_keyfile(kf.clone()).unwrap();
assert!(!cfg.get::<repo::Fsync>().unwrap());
assert_eq!(cfg.get::<archive::ZlibLevel>().unwrap(), 9);
assert_eq!(
cfg.get::<test_single::Name>().unwrap().as_deref(),
Some(" x")
);
assert_eq!(
cfg.get::<ex_ostrya::RemotesConfigDir>()
.unwrap()
.unwrap()
.as_str(),
" r.d"
);
let mut edit = ConfigEdit::new(&mut kf);
edit.keyfile_mut().set_value("core", "other", "1").unwrap();
assert_eq!(kf.get_value("core", "other"), Some("1"));
}
#[test]
fn config_edit_writes_sections() {
let mut kf = KeyFile::parse(BASE).unwrap();
let mut edit = ConfigEdit::new(&mut kf);
let mut section = edit.section_mut::<test_named::Group>("n").unwrap();
assert_eq!(section.name(), "n");
section.set::<test_named::Arch>("amd64".to_owned()).unwrap();
section
.set::<test_named::Next>(GroupRef::new("m").unwrap())
.unwrap();
assert!(section.remove::<test_named::Next>());
assert!(!section.remove::<test_named::Next>());
assert!(edit.section_mut::<test_named::Group>("unused").is_ok());
for bad in ["", "a]b", "a[b", "a\"b", "a\nb"] {
assert!(
matches!(
edit.section_mut::<test_named::Group>(bad),
Err(Error::InvalidInput(_))
),
"{bad:?}"
);
}
assert_eq!(
kf.to_string(),
"[core]\nrepo_version=1\nmode=bare\n\n[ex-test n \"n\"]\narch=amd64\n"
);
let mut edit = ConfigEdit::new(&mut kf);
assert!(edit.remove_section::<test_named::Group>("n"));
assert!(!edit.remove_section::<test_named::Group>("n"));
assert_eq!(kf.to_string(), BASE);
}
#[test]
fn config_edit_escapes_a_value_and_refuses_a_quote_in_a_section_name() {
let mut kf = KeyFile::parse(BASE).unwrap();
let before = kf.clone();
let mut edit = ConfigEdit::new(&mut kf);
let mut section = edit.section_mut::<test_named::Group>("n").unwrap();
section.set::<test_named::Arch>("a\nb".to_owned()).unwrap();
assert_eq!(kf.get_value("ex-test n \"n\"", "arch"), Some("a\\nb"));
let mut kf = before.clone();
let mut edit = ConfigEdit::new(&mut kf);
let err = edit.section_mut::<test_named::Group>("x\"y").err().unwrap();
assert_eq!(
err.to_string(),
"invalid input: the section name \"x\\\"y\" of a [ex-test n \"NAME\"] group holds \
'[', ']', '\"', or a line break"
);
assert_eq!(kf.to_string(), before.to_string());
}
#[test]
fn a_section_name_is_not_empty_and_holds_no_quote() {
crate::config_group! {
pub group h = named "ex-h" {
X: Option<String> = "x";
}
}
let cfg = RepoConfig::parse(&format!(
"{BASE}[ex-h \"\"]\nx=1\n[ex-h \"a\" \"b\"]\nx=2\n[ex-h \"c\"]\nx=3\n"
))
.unwrap();
assert!(cfg.keyfile().has_group("ex-h \"\""));
assert!(cfg.keyfile().has_group("ex-h \"a\" \"b\""));
let names: Vec<_> = cfg
.sections::<h::Group>()
.map(|s| s.name().to_owned())
.collect();
assert_eq!(names, ["c"]);
assert!(cfg.section::<h::Group>("").is_none());
assert!(cfg.section::<h::Group>("a\" \"b").is_none());
assert_eq!(
cfg.section::<h::Group>("c")
.unwrap()
.get::<h::X>()
.unwrap()
.as_deref(),
Some("3")
);
assert!(GroupRef::<h::Group>::new("").is_err());
let err = cfg
.resolve(&GroupRef::<h::Group>::new("a\" \"b").unwrap())
.unwrap_err();
assert_eq!(
err.to_string(),
"invalid format: the config has no [ex-h \"a\" \"b\"] group"
);
}
#[test]
fn group_ref_new_refuses_an_empty_name() {
assert_eq!(
GroupRef::<test_named::Group>::new("").unwrap_err(),
<GroupRef<test_named::Group> as Value>::parse("").unwrap_err()
);
assert_eq!(
GroupRef::<test_named::Group>::new("")
.unwrap_err()
.to_string(),
"is empty"
);
assert_eq!(GroupRef::<test_named::Group>::new("a").unwrap().name(), "a");
}
}
#[cfg(test)]
mod check_tests {
use super::*;
const BASE: &str = "[core]\nrepo_version=1\nmode=archive-z2\n";
fn config(text: &str) -> RepoConfig {
RepoConfig::parse(&format!("{BASE}{text}")).unwrap()
}
fn refusal(cfg: &RepoConfig) -> String {
cfg.check().unwrap_err().to_string()
}
#[test]
fn a_valid_config_passes() {
let cfg = config(
"fsync=false\nlock-timeout-secs=-1\nmin-free-space-size=5GB\n\
min-free-space-percent=10\ncollection-id=org.example.Repo\n\
[archive]\nzlib-level=99\n\
[ex-integrity]\ncomposefs=maybe\nfsverity=yes\n\
[ex-ostrya]\ngc-weak-references=tmp/**;!tmp/keep\n\
remotes-config-dir=remotes.d\n\
[remote \"o\"]\nurl=https://o\ngpg-verify=false\n\
collection-id=org.example.A\nmirrored-collection-ids=org.example.B\n",
);
cfg.check().unwrap();
RepoConfig::parse(BASE).unwrap().check().unwrap();
}
#[test]
fn a_bad_value_of_each_group_is_refused() {
let cfg = config("tombstone-commits=maybe\n");
assert_eq!(
refusal(&cfg),
cfg.file_value::<repo::TombstoneCommits>()
.unwrap_err()
.to_string()
);
assert_eq!(
refusal(&cfg),
"keyfile: value 'maybe' for core.tombstone-commits is not a boolean"
);
let cfg = config("[archive]\nzlib-level=abc\n");
assert_eq!(
refusal(&cfg),
cfg.file_value::<archive::ZlibLevel>()
.unwrap_err()
.to_string()
);
let cfg = config("[ex-integrity]\ncomposefs=sometimes\n");
assert_eq!(
refusal(&cfg),
cfg.file_value::<ex_integrity::Composefs>()
.unwrap_err()
.to_string()
);
let cfg = config("[ex-ostrya]\nkeep-detached-related=maybe\n");
assert_eq!(
refusal(&cfg),
cfg.file_value::<ex_ostrya::KeepDetachedRelated>()
.unwrap_err()
.to_string()
);
let cfg = config("[remote \"o\"]\nurl=https://o\ngpg-verify=maybe\n");
let remote = cfg.section::<remote::Group>("o").unwrap();
assert_eq!(
refusal(&cfg),
remote
.file_value::<remote::GpgVerify>()
.unwrap_err()
.to_string()
);
assert_eq!(
refusal(&cfg),
"keyfile: value 'maybe' for remote \"o\".gpg-verify is not a boolean"
);
}
#[test]
fn the_check_gives_the_first_error_in_group_and_key_order() {
let cfg = config(
"[remote \"o\"]\ngpg-verify=maybe\n\
[ex-ostrya]\nkeep-detached-related=maybe\n\
[core]\nindexed-deltas=maybe\nfsync=maybe\n",
);
assert_eq!(
refusal(&cfg),
"keyfile: value 'maybe' for core.fsync is not a boolean"
);
let cfg = config("[remote \"b\"]\ngpg-verify=maybe\n[remote \"a\"]\ngpg-verify=maybe\n");
assert_eq!(
refusal(&cfg),
"keyfile: value 'maybe' for remote \"b\".gpg-verify is not a boolean"
);
}
#[test]
fn each_key_of_a_pair_is_checked() {
let cfg = config("min-free-space-size=5GB\nmin-free-space-percent=200\n");
cfg.min_free_space().unwrap();
assert_eq!(
refusal(&cfg),
cfg.file_value::<repo::MinFreeSpacePercent>()
.unwrap_err()
.to_string()
);
let cfg = config("[ex-integrity]\ncomposefs=yes\nfsverity=sometimes\n");
assert_eq!(
refusal(&cfg),
cfg.file_value::<ex_integrity::Fsverity>()
.unwrap_err()
.to_string()
);
let cfg = config("[ex-integrity]\ncomposefs=sometimes\nfsverity=yes\n");
cfg.fsverity().unwrap();
assert_eq!(
refusal(&cfg),
cfg.file_value::<ex_integrity::Composefs>()
.unwrap_err()
.to_string()
);
}
#[test]
fn a_gc_weak_references_list_with_no_positive_entry_is_refused() {
for value in ["", "!tmp/**"] {
let cfg = config(&format!("[ex-ostrya]\ngc-weak-references={value}\n"));
assert_eq!(
refusal(&cfg),
cfg.gc_weak_references().unwrap_err().to_string()
);
assert_eq!(
refusal(&cfg),
"invalid format: [ex-ostrya] gc-weak-references: the list holds no pattern \
without '!'"
);
}
}
#[test]
fn a_mirrored_id_that_is_the_collection_id_of_the_remote_is_refused() {
let cfg = config(
"[remote \"o\"]\ncollection-id=org.a.B\nmirrored-collection-ids=org.a.C;org.a.B\n",
);
assert_eq!(
refusal(&cfg),
"invalid format: [remote \"o\"] mirrored-collection-ids holds 'org.a.B', the \
collection-id of the remote"
);
}
#[test]
fn a_collection_id_that_fails_the_rule_is_refused() {
let cfg = config("collection-id=a b\n");
assert_eq!(
refusal(&cfg),
"invalid format: [core] collection-id value 'a b' is not a valid collection id"
);
}
#[test]
fn keys_and_groups_that_the_port_does_not_define_pass() {
let cfg = config(
"parent=/nonexistent\ncommit-update-summary=maybe\nzzz=maybe\n\
[archive]\nzzz=x\n\
[ex-ostrya]\ngenerate-composefs=maybe\n\
[ex-debles]\ntarget=anything\nparallel=many\n\
[ex-ostrya trust \"\"]\nzzz=1\n\
[ex-ostrya key \"a\"b\"]\nzzz=1\n\
[remote \"o\"]\nzzz=maybe\n\
[remote \"\"]\ngpg-verify=maybe\n",
);
cfg.check().unwrap();
}
#[test]
fn an_unknown_key_of_the_server_group_is_refused() {
let cfg = config("[ex-ostrya server]\nlisten=bad\nzzz=1\nyyy=2\n");
assert_eq!(
refusal(&cfg),
"invalid format: [ex-ostrya server] holds the unknown key 'zzz'"
);
config("[ex-ostrya server]\n").check().unwrap();
config("[ex-debles]\nzzz=1\n").check().unwrap();
}
#[test]
fn a_bad_server_value_is_refused_with_the_text_of_the_reader() {
for keys in [
"listen=\n",
"listen=localhost:8080\n",
"listen=a\\\n",
"tls-cert=\n",
"tls-key=../k.pem\n",
"tls-client-ca=a\\q\n",
"trusted-proxy=\n",
"trusted-proxy=10.0.0.1/24\n",
"trusted-proxy-header=X-Real-IP\n",
"trusted-proxy-client-cert=X Client\n",
"proxy-protocol=yes\n",
"allow-cleartext-credentials=2\n",
"session-timeout=0\n",
"max-sessions=9223372036854775808\n",
"parallel-uploads=32\n",
"body-timeout=+1\n",
"sign-summary=\n",
] {
let cfg = config(&format!("[ex-ostrya server]\n{keys}"));
let read = crate::access::ClientAccess::from_config(&cfg)
.unwrap_err()
.to_string();
assert_eq!(refusal(&cfg), read, "{keys:?}");
}
}
#[test]
fn the_server_group_is_checked_after_the_remotes_in_key_order() {
let cfg = config("[ex-ostrya server]\ntrusted-proxy=\ntls-cert=\n");
assert_eq!(
refusal(&cfg),
"invalid format: [ex-ostrya server] tls-cert is empty; remove the key or name a file"
);
let cfg = config("[ex-ostrya server]\nzzz=1\n[remote \"o\"]\ngpg-verify=maybe\n");
assert_eq!(
refusal(&cfg),
"keyfile: value 'maybe' for remote \"o\".gpg-verify is not a boolean"
);
config(
"[ex-ostrya server]\nlisten=127.0.0.1:80;[::1]:81\ntls-cert=c.pem\n\
tls-key=/k.pem\ntls-client-ca=ca.pem\ntrusted-proxy=10.0.0.0/8\n\
trusted-proxy-header=forwarded\ntrusted-proxy-client-cert=X-Cert\n\
proxy-protocol=1\nallow-cleartext-credentials=false\nsession-timeout=5\n\
max-sessions=9223372036854775807\nparallel-uploads=31\nbody-timeout=1\n\
sign-summary=nokey;nokey\n",
)
.check()
.unwrap();
}
#[test]
fn an_unknown_key_of_a_client_group_is_refused() {
let cfg = config("[ex-ostrya client \"c\"]\nauth=bogus\nzzz=1\nyyy=2\n");
assert_eq!(
refusal(&cfg),
"invalid format: [ex-ostrya client \"c\"] holds the unknown key 'zzz'"
);
let cfg = config("[ex-ostrya client \"c\"]\nzzz=1\ncollection=x\n");
assert_eq!(
refusal(&cfg),
"invalid format: [ex-ostrya client \"c\"] holds the removed key 'collection'; an \
allow item or a deny item names the refs of a collection as @ID:PATTERN"
);
config("[ex-ostrya client \"c\"]\n").check().unwrap();
}
#[test]
fn a_bad_client_value_is_refused_with_the_text_of_the_reader() {
for keys in [
"auth=bogus\n",
"auth=;\n",
"auth=a\\q\n",
"auth=anonymous\nallow=R:a\n",
"auth=anonymous\nallow=a\\\n",
"auth=anonymous\ndeny=@a.b\n",
"auth=tls:*\ntls-accept-claim=yes\n",
"auth=anonymous\nverify=off\n",
"auth=anonymous\nverify=remote:origin\n",
"auth=anonymous\nverify=trust:\n",
"auth=anonymous\nallow-unsigned=maybe\n",
"auth=anonymous\nsign=\n",
"auth=anonymous\nallow-privileged=2\n",
"auth=anonymous\ndisable-verify-bindings=on\n",
"auth=anonymous\nsummary=yes\n",
"auth=anonymous\nzzz=1\n",
"auth=anonymous\ncollection=x\n",
] {
let cfg = config(&format!("[ex-ostrya client \"c\"]\n{keys}"));
let read = crate::access::ClientAccess::from_config(&cfg)
.unwrap_err()
.to_string();
assert_eq!(refusal(&cfg), read, "{keys:?}");
}
}
#[test]
fn the_client_groups_are_checked_after_the_server_in_file_order() {
let cfg = config(
"[ex-ostrya client \"b\"]\nsummary=yes\n[ex-ostrya server]\nzzz=1\n\
[ex-ostrya client \"a\"]\nzzz=1\n",
);
assert_eq!(
refusal(&cfg),
"invalid format: [ex-ostrya server] holds the unknown key 'zzz'"
);
let cfg =
config("[ex-ostrya client \"b\"]\nsummary=yes\n[ex-ostrya client \"a\"]\nzzz=1\n");
assert_eq!(
refusal(&cfg),
"keyfile: value 'yes' for ex-ostrya client \"b\".summary is not a boolean"
);
let cfg = config("[ex-ostrya client \"c\"]\nsummary=yes\ntls-accept-claim=maybe\n");
assert_eq!(
refusal(&cfg),
"keyfile: value 'maybe' for ex-ostrya client \"c\".tls-accept-claim is not a \
boolean"
);
}
#[test]
fn the_check_does_not_apply_the_rules_of_the_client_reader() {
for text in [
"[ex-ostrya client \"c\"]\n",
"[ex-ostrya client \"c\"]\nauth=\n",
"[ex-ostrya client \"c\"]\nauth=anonymous\ntls-accept-claim=true\n",
"[ex-ostrya client \"c\"]\nauth=tls:*\ntls-accept-claim=true\nsummary=true\n",
"[ex-ostrya client \"c\"]\nauth=anonymous\nverify=trust:nosuch\n",
"[ex-ostrya client \"c\"]\nauth=anonymous\nsign=nosuch\n",
"[ex-ostrya client \"c\"]\nauth=anonymous\nallow-unsigned=false\n",
"[ex-ostrya client \"a\"]\nauth=anonymous\n[ex-ostrya client \"b\"]\nauth=anonymous\n",
"[ex-ostrya client \"a\tb\"]\nauth=anonymous\n",
] {
let cfg = config(text);
cfg.check().unwrap();
crate::access::ClientAccess::from_config(&cfg).unwrap_err();
}
}
const TRUST_T: &str = "ex-ostrya trust \"t\"";
fn trust_reader_refusal(cfg: &RepoConfig) -> String {
let section = cfg.section::<trust::Group>("t").unwrap();
crate::verify::trust::check_trust(§ion)
.unwrap_err()
.to_string()
}
fn key_reader_refusal(cfg: &RepoConfig) -> String {
let section = cfg.section::<key::Group>("k").unwrap();
match crate::sign::key_group::parse_key(§ion) {
Ok(_) => panic!("the key group is accepted"),
Err(err) => err.to_string(),
}
}
#[test]
fn an_unknown_key_of_a_trust_group_is_refused_with_the_text_of_the_reader() {
let base = "sign-verify=ed25519\nverification-ed25519-key=AAAA\n";
for (keys, text) in [
(
"zzz=1\n",
"invalid format: [ex-ostrya trust \"t\"] holds the unknown key 'zzz'",
),
(
"gpg-verify-summary=true\n",
"invalid format: [ex-ostrya trust \"t\"] holds 'gpg-verify-summary', and a \
trust group sets a commit policy alone",
),
(
"sign-verify-summary=maybe\\q\n",
"invalid format: [ex-ostrya trust \"t\"] holds 'sign-verify-summary', and a \
trust group sets a commit policy alone",
),
(
"verification-foo-key=AAAA\n",
"invalid format: [ex-ostrya trust \"t\"] holds 'verification-foo-key', and \
'foo' is not ed25519 or spki",
),
(
"verification-dummy-file=../k\n",
"invalid format: [ex-ostrya trust \"t\"] holds 'verification-dummy-file', and \
'dummy' is not ed25519 or spki",
),
(
"zzz=1\ngpg-verify-summary=true\n",
"invalid format: [ex-ostrya trust \"t\"] holds the unknown key 'zzz'",
),
(
"gpg-verify-summary=true\nzzz=1\n",
"invalid format: [ex-ostrya trust \"t\"] holds 'gpg-verify-summary', and a \
trust group sets a commit policy alone",
),
(
"gpg-verify=maybe\nzzz=1\n",
"invalid format: [ex-ostrya trust \"t\"] holds the unknown key 'zzz'",
),
] {
let cfg = config(&format!("[{TRUST_T}]\n{base}{keys}"));
assert_eq!(refusal(&cfg), text, "{keys:?}");
assert_eq!(trust_reader_refusal(&cfg), text, "{keys:?}");
}
config(&format!("[{TRUST_T}]\n")).check().unwrap();
}
#[test]
fn a_bad_trust_value_is_refused() {
for (keys, text) in [
(
"gpg-verify=maybe\n",
"keyfile: value 'maybe' for ex-ostrya trust \"t\".gpg-verify is not a boolean",
),
(
"gpgkeypath=/a.gpg;../k.gpg\n",
"invalid format: [ex-ostrya trust \"t\"] gpgkeypath ../k.gpg has a `..` \
component, which a relative path in a config cannot have",
),
("sign-verify=a\\q\n", "keyfile: invalid escape '\\q'"),
(
"verification-ed25519-key=\\q\n",
"keyfile: invalid escape '\\q'",
),
(
"verification-ed25519-file=../k\n",
"invalid format: [ex-ostrya trust \"t\"] verification-ed25519-file ../k has a \
`..` component, which a relative path in a config cannot have",
),
(
"verification-spki-key=\\q\n",
"keyfile: invalid escape '\\q'",
),
(
"verification-spki-file=k/../../k\n",
"invalid format: [ex-ostrya trust \"t\"] verification-spki-file k/../../k has \
a `..` component, which a relative path in a config cannot have",
),
(
"sign-verify=a\\q\ngpg-verify=2\n",
"keyfile: value '2' for ex-ostrya trust \"t\".gpg-verify is not a boolean",
),
] {
let cfg = config(&format!("[{TRUST_T}]\n{keys}"));
assert_eq!(refusal(&cfg), text, "{keys:?}");
}
}
#[test]
fn a_key_group_is_checked() {
for (keys, text, reader) in [
(
"type=rsa\nzzz=1\n",
"invalid format: [ex-ostrya key \"k\"] holds the unknown key 'zzz'",
true,
),
(
"type=rsa\n",
"invalid format: malformed [ex-ostrya key \"k\"] type value 'rsa': the type is \
ed25519, spki, or gpg",
true,
),
(
"type=dummy\n",
"invalid format: malformed [ex-ostrya key \"k\"] type value 'dummy': the dummy \
engine is not a signing key, its signature is its key",
true,
),
("type=ed\\q\n", "keyfile: invalid escape '\\q'", true),
(
"type=ed25519\nsecret-key-file=../s\n",
"invalid format: [ex-ostrya key \"k\"] secret-key-file ../s has a `..` \
component, which a relative path in a config cannot have",
true,
),
(
"secret-key-file=\\q\n",
"keyfile: invalid escape '\\q'",
false,
),
("gpg-key=\\q\n", "keyfile: invalid escape '\\q'", false),
("gpg-homedir=\\q\n", "keyfile: invalid escape '\\q'", false),
(
"gpg-homedir=\\q\ntype=rsa\n",
"invalid format: malformed [ex-ostrya key \"k\"] type value 'rsa': the type is \
ed25519, spki, or gpg",
false,
),
] {
let cfg = config(&format!("[ex-ostrya key \"k\"]\n{keys}"));
assert_eq!(refusal(&cfg), text, "{keys:?}");
if reader {
assert_eq!(key_reader_refusal(&cfg), text, "{keys:?}");
}
}
}
#[test]
fn the_trust_and_key_groups_are_checked_after_the_clients_in_file_order() {
let key_b = "[ex-ostrya key \"b\"]\nzzz=1\n";
let trust_b = "[ex-ostrya trust \"b\"]\nzzz=1\n";
let client_b = "[ex-ostrya client \"b\"]\nzzz=1\n";
let key_a = "[ex-ostrya key \"a\"]\nzzz=1\n";
let trust_a = "[ex-ostrya trust \"a\"]\nzzz=1\n";
for (groups, header) in [
(
[key_b, trust_b, client_b, key_a, trust_a].concat(),
"ex-ostrya client \"b\"",
),
(
[key_b, trust_b, key_a, trust_a].concat(),
"ex-ostrya trust \"b\"",
),
([key_b, key_a, trust_a].concat(), "ex-ostrya trust \"a\""),
([key_b, key_a].concat(), "ex-ostrya key \"b\""),
] {
assert_eq!(
refusal(&config(&groups)),
format!("invalid format: [{header}] holds the unknown key 'zzz'"),
"{groups:?}"
);
}
}
#[test]
fn the_check_does_not_apply_the_rules_of_the_trust_and_key_readers() {
for keys in [
"",
"gpg-verify=false\nsign-verify=false\n",
"sign-verify=dummy\n",
"sign-verify=ed25519;foo\nverification-ed25519-key=AAAA\n",
"gpgkeypath=/k.gpg\nsign-verify=ed25519\nverification-ed25519-key=AAAA\n",
"gpg-verify=true\n",
"gpg-verify=true\ngpgkeypath=;;/k.gpg\n",
"sign-verify=ed25519\nverification-spki-key=AAAA\n",
] {
let cfg = config(&format!("[{TRUST_T}]\n{keys}"));
cfg.check().unwrap();
trust_reader_refusal(&cfg);
}
for keys in [
"",
"secret-key-file=/s\n",
"type=ed25519\n",
"type=ed25519\nsecret-key-file=\n",
"type=gpg\ngpg-key=\n",
"type=ed25519\nsecret-key-file=/s\ngpg-key=A\n",
"type=gpg\ngpg-key=A\nsecret-key-file=/s\n",
] {
let cfg = config(&format!("[ex-ostrya key \"k\"]\n{keys}"));
cfg.check().unwrap();
key_reader_refusal(&cfg);
}
config("[ex-ostrya trust \"a\tb\"]\nsign-verify=ed25519\n[ex-ostrya key \"a\tb\"]\n")
.check()
.unwrap();
}
#[test]
fn the_closed_check_refuses_an_unknown_key() {
let cfg = config(
"zzz=1\n[ex-ostrya client \"a\"]\nauth=x\n[ex-ostrya client \"b\"]\nzzz=1\n\
[ex-ostrya server]\nyyy=1\n",
);
cfg.refuse_unknown_keys::<repo::Group>().unwrap();
cfg.refuse_unknown_keys::<remote::Group>().unwrap();
assert_eq!(
cfg.refuse_unknown_keys::<client::Group>()
.unwrap_err()
.to_string(),
"invalid format: [ex-ostrya client \"b\"] holds the unknown key 'zzz'"
);
assert_eq!(
cfg.refuse_unknown_keys::<server::Group>()
.unwrap_err()
.to_string(),
"invalid format: [ex-ostrya server] holds the unknown key 'yyy'"
);
let a = cfg.section::<client::Group>("a").unwrap();
a.refuse_unknown_keys().unwrap();
let b = cfg.section::<client::Group>("b").unwrap();
assert_eq!(
b.refuse_unknown_keys().unwrap_err().to_string(),
"invalid format: [ex-ostrya client \"b\"] holds the unknown key 'zzz'"
);
config("").refuse_unknown_keys::<server::Group>().unwrap();
}
#[test]
fn an_override_does_not_hide_a_bad_value_of_the_file() {
let mut overrides = Overrides::default();
overrides.force::<repo::Fsync>(false);
let cfg = config("fsync=maybe\n").with_overrides(Arc::new(overrides));
assert!(!cfg.get::<repo::Fsync>().unwrap());
assert_eq!(
refusal(&cfg),
"keyfile: value 'maybe' for core.fsync is not a boolean"
);
}
#[test]
fn a_bad_value_of_a_remote_of_a_conf_file_is_refused() {
let cfg = config("[remote \"o\"]\nurl=https://o\n")
.with_remote_files(
Path::new("/etc/r.d"),
vec![RemoteFile {
name: "a.conf".to_owned(),
keyfile: KeyFile::parse("[remote \"a\"]\ntls-permissive=maybe\n").unwrap(),
}],
)
.unwrap();
assert_eq!(
refusal(&cfg),
"keyfile: value 'maybe' for remote \"a\".tls-permissive is not a boolean"
);
}
}
#[cfg(test)]
mod text_in_effect_tests {
use super::*;
const BASE: &str = "[core]\nrepo_version=1\nmode=archive-z2\n";
fn config(text: &str) -> RepoConfig {
RepoConfig::parse(&format!("{BASE}{text}")).unwrap()
}
fn value(text: &str) -> TextInEffect {
TextInEffect::Value(text.to_owned())
}
#[test]
fn each_key_of_each_builtin_group_dispatches() {
let keyfile = KeyFile::parse(BASE).unwrap();
type Dispatch =
fn(&KeyFile, &str, Option<&Overrides>, &str) -> Option<Result<Option<String>>>;
let groups: [(&[&str], &str, Dispatch); 7] = [
(<repo::Group as Group>::KEYS, "core", repo::text_in_effect),
(
<archive::Group as Group>::KEYS,
"archive",
archive::text_in_effect,
),
(
<ex_integrity::Group as Group>::KEYS,
"ex-integrity",
ex_integrity::text_in_effect,
),
(
<ex_ostrya::Group as Group>::KEYS,
"ex-ostrya",
ex_ostrya::text_in_effect,
),
(
<remote::Group as Group>::KEYS,
"remote \"o\"",
remote::text_in_effect,
),
(
<server::Group as Group>::KEYS,
"ex-ostrya server",
server::text_in_effect,
),
(
<client::Group as Group>::KEYS,
"ex-ostrya client \"c\"",
client::text_in_effect,
),
];
for (keys, header, dispatch) in groups {
for key in keys {
assert!(
dispatch(&keyfile, header, None, key).is_some(),
"[{header}] {key}"
);
}
assert!(
dispatch(&keyfile, header, None, "zzz").is_none(),
"{header}"
);
}
}
#[test]
fn text_in_effect_applies_the_forced_and_the_fallback_values() {
let mut overrides = Overrides::default();
overrides.force::<repo::Fsync>(false);
overrides.fallback::<repo::TmpExpirySecs>(5);
overrides.fallback::<archive::ZlibLevel>(9);
let cfg = config("fsync=true\n").with_overrides(Arc::new(overrides));
assert_eq!(cfg.text_in_effect("core", "fsync").unwrap(), value("false"));
assert_eq!(
cfg.text_in_effect("core", "tmp-expiry-secs").unwrap(),
value("5")
);
assert_eq!(
cfg.text_in_effect("archive", "zlib-level").unwrap(),
value("9")
);
let cfg = config("fsync=true\ntmp-expiry-secs=7\n");
assert_eq!(cfg.text_in_effect("core", "fsync").unwrap(), value("true"));
assert_eq!(
cfg.text_in_effect("core", "tmp-expiry-secs").unwrap(),
value("7")
);
}
#[test]
fn text_in_effect_reads_a_remote_of_a_conf_file() {
let cfg = config("[remote \"o\"]\nurl=https://o\n")
.with_remote_files(
Path::new("/etc/r.d"),
vec![RemoteFile {
name: "a.conf".to_owned(),
keyfile: KeyFile::parse("[remote \"a\"]\nurl=https://a\nzzz=1\n").unwrap(),
}],
)
.unwrap();
assert_eq!(
cfg.text_in_effect("remote \"a\"", "url").unwrap(),
value("https://a")
);
assert_eq!(
cfg.text_in_effect("remote \"a\"", "zzz").unwrap(),
value("1")
);
assert_eq!(
cfg.text_in_effect("remote \"a\"", "gpg-verify").unwrap(),
value("true")
);
assert_eq!(
cfg.text_in_effect("remote \"a\"", "nope").unwrap(),
TextInEffect::NoKey
);
assert_eq!(
cfg.text_in_effect("remote \"b\"", "url").unwrap(),
TextInEffect::NoGroup
);
assert_eq!(
cfg.text_in_effect("remote \"o\"", "url").unwrap(),
value("https://o")
);
}
#[test]
fn text_in_effect_gives_the_raw_file_text_of_an_unknown_key() {
let cfg = config(
"zzz=a\\sb\ncommit-update-summary=maybe\n[ex-debles]\nparallel=many\n\
[remote \"\"]\nurl=https://e\n",
);
assert_eq!(cfg.text_in_effect("core", "zzz").unwrap(), value("a\\sb"));
assert_eq!(
cfg.text_in_effect("core", "commit-update-summary").unwrap(),
value("maybe")
);
assert_eq!(
cfg.text_in_effect("ex-debles", "parallel").unwrap(),
value("many")
);
assert_eq!(
cfg.text_in_effect("core", "nope").unwrap(),
TextInEffect::NoKey
);
assert_eq!(
cfg.text_in_effect("nope", "x").unwrap(),
TextInEffect::NoGroup
);
assert_eq!(
cfg.text_in_effect("remote \"\"", "url").unwrap(),
TextInEffect::NoGroup
);
assert_eq!(
cfg.text_in_effect("archive", "zlib-level").unwrap(),
value("6")
);
assert_eq!(
cfg.text_in_effect("ex-ostrya", "gc-weak-references")
.unwrap(),
TextInEffect::NoKey
);
assert_eq!(
cfg.text_in_effect("archive", "nope").unwrap(),
TextInEffect::NoGroup
);
}
#[test]
fn text_in_effect_reads_the_server_keys() {
let cfg = config(
"[ex-ostrya server]\nlisten=127.0.0.1:80\nproxy-protocol=1\n\
parallel-uploads=04\nsign-summary=b;a;b\nzzz=a\\sb\n",
);
let server = "ex-ostrya server";
assert_eq!(
cfg.text_in_effect(server, "listen").unwrap(),
value("127.0.0.1:80;")
);
assert_eq!(
cfg.text_in_effect(server, "proxy-protocol").unwrap(),
value("true")
);
assert_eq!(
cfg.text_in_effect(server, "parallel-uploads").unwrap(),
value("4")
);
assert_eq!(
cfg.text_in_effect(server, "sign-summary").unwrap(),
value("b;a;")
);
assert_eq!(
cfg.text_in_effect(server, "max-sessions").unwrap(),
TextInEffect::NoKey
);
assert_eq!(cfg.text_in_effect(server, "zzz").unwrap(), value("a\\sb"));
assert_eq!(
cfg.text_in_effect(server, "nope").unwrap(),
TextInEffect::NoKey
);
let cfg = config("[ex-ostrya server]\nmax-sessions=0\n");
assert_eq!(
cfg.text_in_effect(server, "max-sessions")
.unwrap_err()
.to_string(),
"invalid format: [ex-ostrya server] max-sessions is 0; the value is a positive \
integer"
);
let cfg = config("");
assert_eq!(
cfg.text_in_effect(server, "listen").unwrap(),
TextInEffect::NoKey
);
assert_eq!(
cfg.text_in_effect(server, "zzz").unwrap(),
TextInEffect::NoGroup
);
}
#[test]
fn text_in_effect_reads_the_client_keys() {
let cfg = config(
"[ex-ostrya client \"c\"]\nauth=ssh:a;anonymous;ssh:a\nallow=r:@a.b:x;wr:y\n\
deny=@a.b:z\nsummary=1\nsign=b;a;b\nverify=trust:t\nzzz=a\\sb\n\
[ex-ostrya client \"d\"]\nauth=anonymous\nallow-unsigned=true\nverify=trust:t\n",
);
let c = "ex-ostrya client \"c\"";
let d = "ex-ostrya client \"d\"";
for (group, key, want) in [
(c, "auth", value("ssh:a;anonymous;")),
(c, "allow", value("r:@a.b:x;rw:y;")),
(c, "deny", value("@a.b:z;")),
(c, "summary", value("true")),
(c, "sign", value("b;a;")),
(c, "verify", value("trust:t")),
(c, "allow-unsigned", value("false")),
(c, "tls-accept-claim", value("false")),
(c, "allow-privileged", value("false")),
(c, "disable-verify-bindings", value("false")),
(c, "zzz", value("a\\sb")),
(c, "nope", TextInEffect::NoKey),
(d, "allow-unsigned", value("true")),
(d, "allow", value("")),
(d, "deny", value("")),
(d, "sign", TextInEffect::NoKey),
("ex-ostrya client \"e\"", "auth", TextInEffect::NoGroup),
(
"ex-ostrya client \"anonymous\"",
"auth",
TextInEffect::NoGroup,
),
] {
assert_eq!(
cfg.text_in_effect(group, key).unwrap(),
want,
"[{group}] {key}"
);
}
let cfg = config("[ex-ostrya client \"c\"]\nallow=x\n");
let c = "ex-ostrya client \"c\"";
assert_eq!(cfg.text_in_effect(c, "auth").unwrap(), TextInEffect::NoKey);
assert_eq!(
cfg.text_in_effect(c, "verify").unwrap(),
TextInEffect::NoKey
);
assert_eq!(
cfg.text_in_effect(c, "allow-unsigned").unwrap(),
value("true")
);
let cfg = config("[ex-ostrya client \"c\"]\nverify=off\n");
assert_eq!(
cfg.text_in_effect(c, "allow-unsigned")
.unwrap_err()
.to_string(),
"invalid format: malformed [ex-ostrya client \"c\"] verify value 'off': the value \
is trust:NAME; leave out the key for no verification"
);
}
#[test]
fn text_in_effect_reads_the_trust_and_key_keys() {
let cfg = config(
"[ex-ostrya trust \"t\"]\ngpg-verify=1\ngpgkeypath=k\\s.gpg;\n\
sign-verify=ed25519,spki\nverification-spki-file=k\\s.pem\nzzz=a\\sb\n\
[ex-ostrya trust \"u\"]\n\
[ex-ostrya key \"k\"]\ntype=gpg\ngpg-key=A\\sB\nzzz=1\n\
[ex-ostrya key \"l\"]\n",
);
let t = "ex-ostrya trust \"t\"";
let u = "ex-ostrya trust \"u\"";
let k = "ex-ostrya key \"k\"";
let l = "ex-ostrya key \"l\"";
for (group, key, want) in [
(t, "gpg-verify", value("true")),
(t, "gpgkeypath", value("k\\s.gpg")),
(t, "sign-verify", value("ed25519;spki;")),
(t, "verification-spki-file", value("k .pem")),
(t, "verification-ed25519-key", TextInEffect::NoKey),
(t, "zzz", value("a\\sb")),
(t, "nope", TextInEffect::NoKey),
(u, "gpg-verify", value("false")),
(u, "sign-verify", value("false")),
(u, "gpgkeypath", value("")),
(u, "verification-ed25519-key", TextInEffect::NoKey),
(u, "verification-ed25519-file", TextInEffect::NoKey),
(u, "verification-spki-key", TextInEffect::NoKey),
(u, "verification-spki-file", TextInEffect::NoKey),
(k, "type", value("gpg")),
(k, "gpg-key", value("A B")),
(k, "zzz", value("1")),
(k, "secret-key-file", TextInEffect::NoKey),
(l, "type", TextInEffect::NoKey),
(l, "secret-key-file", TextInEffect::NoKey),
(l, "gpg-key", TextInEffect::NoKey),
(l, "gpg-homedir", TextInEffect::NoKey),
("ex-ostrya trust \"v\"", "gpg-verify", TextInEffect::NoGroup),
("ex-ostrya key \"m\"", "type", TextInEffect::NoGroup),
] {
assert_eq!(
cfg.text_in_effect(group, key).unwrap(),
want,
"[{group}] {key}"
);
}
let cfg =
config("[ex-ostrya trust \"t\"]\ngpg-verify=maybe\n[ex-ostrya key \"k\"]\ntype=rsa\n");
assert_eq!(
cfg.text_in_effect(t, "gpg-verify").unwrap_err().to_string(),
"keyfile: value 'maybe' for ex-ostrya trust \"t\".gpg-verify is not a boolean"
);
assert_eq!(
cfg.text_in_effect(k, "type").unwrap_err().to_string(),
"invalid format: malformed [ex-ostrya key \"k\"] type value 'rsa': the type is \
ed25519, spki, or gpg"
);
}
#[test]
fn text_in_effect_gives_no_group_for_a_trust_or_key_name_that_is_not_a_section_name() {
let cfg = config(
"[ex-ostrya trust \"\"]\ngpg-verify=true\nzzz=1\n\
[ex-ostrya trust \"a\"b\"]\ngpg-verify=true\nzzz=1\n\
[ex-ostrya key \"\"]\ntype=gpg\nzzz=1\n\
[ex-ostrya key \"a\"b\"]\ntype=gpg\nzzz=1\n",
);
for (group, keys) in [
("ex-ostrya trust \"\"", ["gpg-verify", "sign-verify", "zzz"]),
(
"ex-ostrya trust \"a\"b\"",
["gpg-verify", "gpgkeypath", "zzz"],
),
("ex-ostrya key \"\"", ["type", "gpg-key", "zzz"]),
("ex-ostrya key \"a\"b\"", ["type", "gpg-homedir", "zzz"]),
] {
for key in keys {
assert_eq!(
cfg.text_in_effect(group, key).unwrap(),
TextInEffect::NoGroup,
"[{group}] {key}"
);
}
}
}
#[test]
fn text_in_effect_gives_no_group_for_a_client_name_that_is_not_a_section_name() {
let cfg = config(
"[ex-ostrya client \"\"]\nallow=x\nzzz=1\n\
[ex-ostrya client \"a\"b\"]\nallow=x\nzzz=1\n",
);
for group in ["ex-ostrya client \"\"", "ex-ostrya client \"a\"b\""] {
for key in ["allow", "allow-privileged", "zzz"] {
assert_eq!(
cfg.text_in_effect(group, key).unwrap(),
TextInEffect::NoGroup,
"[{group}] {key}"
);
}
}
}
#[test]
fn text_in_effect_reads_the_keys_of_the_methods() {
let cfg = config(
"[ex-integrity]\ncomposefs=yes\n[ex-ostrya]\ngc-weak-references=!a;b\n\
remotes-config-dir=r.d\n\
[remote \"o\"]\ncollection-id=org.a.B\nmirrored-collection-ids=org.a.C;org.a.C\n\
[remote \"p\"]\ncollection-id=org.a.B\nmirrored-collection-ids=org.a.B\n\
[remote \"q\"]\nurl=https://q\n",
);
assert_eq!(
cfg.text_in_effect("ex-integrity", "fsverity").unwrap(),
value("maybe")
);
assert_eq!(
cfg.text_in_effect("ex-ostrya", "gc-weak-references")
.unwrap(),
value("b;!a;")
);
assert_eq!(
cfg.text_in_effect("ex-ostrya", "remotes-config-dir")
.unwrap(),
value("r.d")
);
assert_eq!(
cfg.text_in_effect("remote \"o\"", "mirrored-collection-ids")
.unwrap(),
value("org.a.C;")
);
assert_eq!(
cfg.text_in_effect("remote \"p\"", "mirrored-collection-ids")
.unwrap_err()
.to_string(),
"invalid format: [remote \"p\"] mirrored-collection-ids holds 'org.a.B', \
the collection-id of the remote"
);
assert_eq!(
cfg.text_in_effect("remote \"q\"", "mirrored-collection-ids")
.unwrap(),
TextInEffect::NoKey
);
let cfg = config("[ex-ostrya]\ngc-weak-references=!a\n");
assert_eq!(
cfg.text_in_effect("ex-ostrya", "gc-weak-references")
.unwrap_err()
.to_string(),
"invalid format: [ex-ostrya] gc-weak-references: the list holds no pattern without '!'"
);
}
}