use std::collections::HashSet;
use std::net::SocketAddr;
use std::path::{Component, Path};
use ostrya_core::{KeyFile, RefPattern, RepoMode};
use super::{
GroupRef, SignVerify, SizeSpec, SizeUnit, Tristate, parse_sign_verify, parse_size, trust,
};
use crate::access::{
AllowItem, AuthItem, ForwardedHeader, IpNet, is_header_name, parse_allow_item, parse_deny_item,
parse_item, parse_net,
};
use crate::error::Error;
pub trait Value: Sized {
fn parse(raw: &str) -> Result<Self, ValueError>;
fn format(&self) -> String;
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ValueError {
kind: Kind,
}
#[derive(Debug, Clone, PartialEq, Eq)]
enum Kind {
NotBoolean,
NotInteger,
KeyFile(String),
Invalid(String),
Malformed {
part: &'static str,
text: String,
why: String,
},
}
impl ValueError {
pub fn new(reason: impl Into<String>) -> ValueError {
ValueError {
kind: Kind::Invalid(reason.into()),
}
}
pub fn malformed_item(text: impl Into<String>, why: impl Into<String>) -> ValueError {
ValueError {
kind: Kind::Malformed {
part: "item",
text: text.into(),
why: why.into(),
},
}
}
pub fn malformed_value(text: impl Into<String>, why: impl Into<String>) -> ValueError {
ValueError {
kind: Kind::Malformed {
part: "value",
text: text.into(),
why: why.into(),
},
}
}
}
impl std::fmt::Display for ValueError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
Kind::NotBoolean => f.write_str("is not a boolean"),
Kind::NotInteger => f.write_str("is not an integer"),
Kind::KeyFile(text) | Kind::Invalid(text) => f.write_str(text),
Kind::Malformed { part, text, why } => write!(f, "malformed {part} '{text}': {why}"),
}
}
}
impl std::error::Error for ValueError {}
pub(crate) fn value_error(group: &str, key: &str, raw: &str, err: ValueError) -> Error {
match err.kind {
Kind::NotBoolean => Error::Core(ostrya_core::Error::KeyFile(format!(
"value '{raw}' for {group}.{key} is not a boolean"
))),
Kind::NotInteger => Error::Core(ostrya_core::Error::KeyFile(format!(
"value '{raw}' for {group}.{key} is not an integer"
))),
Kind::KeyFile(text) => Error::Core(ostrya_core::Error::KeyFile(text)),
Kind::Invalid(reason) => Error::InvalidFormat(format!("[{group}] {key} {reason}")),
Kind::Malformed { part, text, why } => {
Error::InvalidFormat(format!("malformed [{group}] {key} {part} '{text}': {why}"))
}
}
}
fn keyfile_error(err: ostrya_core::Error) -> ValueError {
match err {
ostrya_core::Error::KeyFile(text) => ValueError {
kind: Kind::KeyFile(text),
},
other => ValueError {
kind: Kind::KeyFile(other.to_string()),
},
}
}
pub fn decode_string(raw: &str) -> Result<String, ValueError> {
KeyFile::decode_string(raw).map_err(keyfile_error)
}
pub fn encode_string(value: &str) -> String {
KeyFile::encode_string(value)
}
pub fn decode_bool(raw: &str) -> Result<bool, ValueError> {
KeyFile::decode_bool(raw).ok_or(ValueError {
kind: Kind::NotBoolean,
})
}
pub fn encode_bool(value: bool) -> String {
if value { "true" } else { "false" }.to_owned()
}
pub fn decode_integer(raw: &str) -> Result<i64, ValueError> {
KeyFile::decode_integer(raw).ok_or(ValueError {
kind: Kind::NotInteger,
})
}
pub fn encode_integer(value: i64) -> String {
value.to_string()
}
pub fn decode_string_list(raw: &str) -> Result<Vec<String>, ValueError> {
KeyFile::decode_string_list(raw).map_err(keyfile_error)
}
pub fn encode_string_list(items: &[impl AsRef<str>]) -> String {
KeyFile::encode_string_list(items)
}
impl Value for bool {
fn parse(raw: &str) -> Result<bool, ValueError> {
decode_bool(raw)
}
fn format(&self) -> String {
encode_bool(*self)
}
}
impl Value for i64 {
fn parse(raw: &str) -> Result<i64, ValueError> {
decode_integer(raw)
}
fn format(&self) -> String {
encode_integer(*self)
}
}
macro_rules! value_through_i64 {
($($int:ty),*) => {$(
impl Value for $int {
fn parse(raw: &str) -> Result<$int, ValueError> {
let n = decode_integer(raw)?;
<$int>::try_from(n).map_err(|_| {
ValueError::new(format!(
"{n} is out of the range {}-{}",
<$int>::MIN,
<$int>::MAX
))
})
}
fn format(&self) -> String {
self.to_string()
}
}
)*};
}
value_through_i64!(i8, i16, i32, u8, u16, u32);
impl Value for u64 {
fn parse(raw: &str) -> Result<u64, ValueError> {
let n = match decode_integer(raw) {
Ok(n) => n,
Err(err) if raw.starts_with('+') => return Err(err),
Err(err) => return raw.parse::<u64>().map_err(|_| err),
};
u64::try_from(n).map_err(|_| {
ValueError::new(format!("{n} is out of the range {}-{}", u64::MIN, u64::MAX))
})
}
fn format(&self) -> String {
self.to_string()
}
}
impl Value for String {
fn parse(raw: &str) -> Result<String, ValueError> {
decode_string(raw)
}
fn format(&self) -> String {
encode_string(self)
}
}
impl Value for Vec<String> {
fn parse(raw: &str) -> Result<Vec<String>, ValueError> {
decode_string_list(raw)
}
fn format(&self) -> String {
encode_string_list(self)
}
}
impl Value for Tristate {
fn parse(raw: &str) -> Result<Tristate, ValueError> {
let value = decode_string(raw)?;
match value.as_str() {
"no" => Ok(Tristate::No),
"maybe" => Ok(Tristate::Maybe),
"yes" => Ok(Tristate::Yes),
_ => Err(ValueError::new(format!(
"value '{value}' is not no, maybe, or yes"
))),
}
}
fn format(&self) -> String {
match self {
Tristate::No => "no",
Tristate::Maybe => "maybe",
Tristate::Yes => "yes",
}
.to_owned()
}
}
impl Value for SignVerify {
fn parse(raw: &str) -> Result<SignVerify, ValueError> {
Ok(parse_sign_verify(Some(&decode_string(raw)?)))
}
fn format(&self) -> String {
match self {
SignVerify::Off => encode_bool(false),
SignVerify::All => encode_bool(true),
SignVerify::Engines(names) => encode_string_list(names),
}
}
}
impl Value for SizeSpec {
fn parse(raw: &str) -> Result<SizeSpec, ValueError> {
parse_size(raw).ok_or_else(|| {
ValueError::new(format!(
"value '{raw}' is not of the form 123MB, 123GB, or 123TB"
))
})
}
fn format(&self) -> String {
let unit = match self.unit {
SizeUnit::Mega => "MB",
SizeUnit::Giga => "GB",
SizeUnit::Tera => "TB",
};
format!("{}{unit}", self.value)
}
}
impl Value for RepoMode {
fn parse(raw: &str) -> Result<RepoMode, ValueError> {
let value = decode_string(raw)?;
RepoMode::from_mode_str(&value)
.ok_or_else(|| ValueError::new(format!("'{value}' names no repository mode")))
}
fn format(&self) -> String {
self.as_mode_str().to_owned()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct LockTimeout {
secs: i64,
}
impl LockTimeout {
pub(crate) const fn new_const(secs: i64) -> LockTimeout {
assert!(secs >= -1);
LockTimeout { secs }
}
pub fn get(self) -> i64 {
self.secs
}
}
impl TryFrom<i64> for LockTimeout {
type Error = ValueError;
fn try_from(secs: i64) -> Result<LockTimeout, ValueError> {
if secs < -1 {
return Err(ValueError::new(format!("{secs} is below -1")));
}
Ok(LockTimeout { secs })
}
}
impl Value for LockTimeout {
fn parse(raw: &str) -> Result<LockTimeout, ValueError> {
LockTimeout::try_from(decode_integer(raw)?)
}
fn format(&self) -> String {
encode_integer(self.secs)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct FreeSpacePercent {
percent: u32,
}
impl FreeSpacePercent {
pub(crate) const fn new_const(percent: u32) -> FreeSpacePercent {
assert!(percent <= 100);
FreeSpacePercent { percent }
}
pub fn get(self) -> u32 {
self.percent
}
}
impl TryFrom<i64> for FreeSpacePercent {
type Error = ValueError;
fn try_from(percent: i64) -> Result<FreeSpacePercent, ValueError> {
match u32::try_from(percent) {
Ok(percent) if percent <= 100 => Ok(FreeSpacePercent { percent }),
_ => Err(ValueError::new(format!(
"{percent} is out of the range 0-100"
))),
}
}
}
impl Value for FreeSpacePercent {
fn parse(raw: &str) -> Result<FreeSpacePercent, ValueError> {
FreeSpacePercent::try_from(decode_integer(raw)?)
}
fn format(&self) -> String {
encode_integer(i64::from(self.percent))
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CollectionIdValue {
id: String,
}
impl CollectionIdValue {
pub fn as_str(&self) -> &str {
&self.id
}
pub fn into_string(self) -> String {
self.id
}
}
impl TryFrom<String> for CollectionIdValue {
type Error = ValueError;
fn try_from(id: String) -> Result<CollectionIdValue, ValueError> {
if !ostrya_core::is_valid_collection_id(&id) {
return Err(ValueError::new(format!(
"value '{id}' is not a valid collection id"
)));
}
Ok(CollectionIdValue { id })
}
}
impl TryFrom<&str> for CollectionIdValue {
type Error = ValueError;
fn try_from(id: &str) -> Result<CollectionIdValue, ValueError> {
CollectionIdValue::try_from(id.to_owned())
}
}
impl Value for CollectionIdValue {
fn parse(raw: &str) -> Result<CollectionIdValue, ValueError> {
CollectionIdValue::try_from(decode_string(raw)?)
}
fn format(&self) -> String {
encode_string(&self.id)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct RemotesConfigPath {
path: String,
}
impl RemotesConfigPath {
pub fn as_str(&self) -> &str {
&self.path
}
pub fn as_path(&self) -> &Path {
Path::new(&self.path)
}
}
impl TryFrom<String> for RemotesConfigPath {
type Error = ValueError;
fn try_from(path: String) -> Result<RemotesConfigPath, ValueError> {
if path.is_empty() {
return Err(ValueError::new("is empty"));
}
if path.contains('\0') {
return Err(ValueError::new("holds a NUL byte"));
}
let value = Path::new(&path);
if value.is_relative() && value.components().any(|c| c == Component::ParentDir) {
return Err(ValueError::new(format!(
"{path} has a `..` component, which a relative path in a config cannot have"
)));
}
Ok(RemotesConfigPath { path })
}
}
impl TryFrom<&str> for RemotesConfigPath {
type Error = ValueError;
fn try_from(path: &str) -> Result<RemotesConfigPath, ValueError> {
RemotesConfigPath::try_from(path.to_owned())
}
}
impl Value for RemotesConfigPath {
fn parse(raw: &str) -> Result<RemotesConfigPath, ValueError> {
RemotesConfigPath::try_from(decode_string(raw)?)
}
fn format(&self) -> String {
encode_string(&self.path)
}
}
fn check_config_path(path: &str) -> Result<(), ValueError> {
if super::relative_with_parent(Path::new(path)) {
return Err(ValueError::new(format!(
"{path} has a `..` component, which a relative path in a config cannot have"
)));
}
Ok(())
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ConfigPath {
path: String,
}
impl ConfigPath {
pub fn as_str(&self) -> &str {
&self.path
}
pub fn as_path(&self) -> &Path {
Path::new(&self.path)
}
pub fn into_string(self) -> String {
self.path
}
}
impl TryFrom<String> for ConfigPath {
type Error = ValueError;
fn try_from(path: String) -> Result<ConfigPath, ValueError> {
check_config_path(&path)?;
Ok(ConfigPath { path })
}
}
impl TryFrom<&str> for ConfigPath {
type Error = ValueError;
fn try_from(path: &str) -> Result<ConfigPath, ValueError> {
ConfigPath::try_from(path.to_owned())
}
}
impl Value for ConfigPath {
fn parse(raw: &str) -> Result<ConfigPath, ValueError> {
ConfigPath::try_from(decode_string(raw)?)
}
fn format(&self) -> String {
encode_string(&self.path)
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)]
pub struct KeyringPaths {
entries: Vec<String>,
}
impl KeyringPaths {
pub fn entries(&self) -> &[String] {
&self.entries
}
pub fn into_entries(self) -> Vec<String> {
self.entries
}
}
impl Value for KeyringPaths {
fn parse(raw: &str) -> Result<KeyringPaths, ValueError> {
let mut entries: Vec<String> = raw.split(';').map(str::to_owned).collect();
if entries.len() > 1 && entries.last().is_some_and(String::is_empty) {
entries.pop();
}
for entry in &entries {
check_config_path(entry)?;
}
Ok(KeyringPaths { entries })
}
fn format(&self) -> String {
let mut text = self.entries.join(";");
if self.entries.len() > 1 && self.entries.last().is_some_and(String::is_empty) {
text.push(';');
}
text
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CollectionIdList {
ids: Vec<String>,
}
impl CollectionIdList {
pub fn ids(&self) -> &[String] {
&self.ids
}
pub fn into_ids(self) -> Vec<String> {
self.ids
}
}
impl TryFrom<Vec<String>> for CollectionIdList {
type Error = ValueError;
fn try_from(ids: Vec<String>) -> Result<CollectionIdList, ValueError> {
if ids.is_empty() {
return Err(ValueError::new("holds no collection id"));
}
let mut seen = HashSet::with_capacity(ids.len());
let mut out: Vec<String> = Vec::with_capacity(ids.len());
for id in ids {
if !ostrya_core::is_valid_collection_id(&id) {
return Err(ValueError::new(format!(
"holds the invalid collection id '{id}'"
)));
}
if seen.insert(id.clone()) {
out.push(id);
}
}
Ok(CollectionIdList { ids: out })
}
}
impl Value for CollectionIdList {
fn parse(raw: &str) -> Result<CollectionIdList, ValueError> {
CollectionIdList::try_from(decode_string_list(raw)?)
}
fn format(&self) -> String {
encode_string_list(&self.ids)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ListenAddrs {
addrs: Vec<SocketAddr>,
}
impl ListenAddrs {
pub fn addrs(&self) -> &[SocketAddr] {
&self.addrs
}
pub fn into_addrs(self) -> Vec<SocketAddr> {
self.addrs
}
}
impl TryFrom<Vec<SocketAddr>> for ListenAddrs {
type Error = ValueError;
fn try_from(addrs: Vec<SocketAddr>) -> Result<ListenAddrs, ValueError> {
if addrs.is_empty() {
return Err(ValueError::new(
"is empty; remove the key for the default address",
));
}
if let Some(addr) = addrs
.iter()
.find(|addr| matches!(addr, SocketAddr::V6(v6) if v6.flowinfo() != 0))
{
return Err(ValueError::malformed_item(
addr.to_string(),
"the address has a flow label, which a config cannot hold",
));
}
Ok(ListenAddrs { addrs })
}
}
impl Value for ListenAddrs {
fn parse(raw: &str) -> Result<ListenAddrs, ValueError> {
let addrs = decode_string_list(raw)?
.iter()
.map(|text| {
text.parse::<SocketAddr>().map_err(|_| {
ValueError::malformed_item(
text.as_str(),
"the item is ADDR:PORT, an IP address and a port",
)
})
})
.collect::<Result<Vec<_>, _>>()?;
ListenAddrs::try_from(addrs)
}
fn format(&self) -> String {
let items: Vec<String> = self.addrs.iter().map(SocketAddr::to_string).collect();
encode_string_list(&items)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct TrustedNets {
nets: Vec<IpNet>,
}
impl TrustedNets {
pub fn nets(&self) -> &[IpNet] {
&self.nets
}
pub fn into_nets(self) -> Vec<IpNet> {
self.nets
}
}
impl TryFrom<Vec<IpNet>> for TrustedNets {
type Error = ValueError;
fn try_from(nets: Vec<IpNet>) -> Result<TrustedNets, ValueError> {
if nets.is_empty() {
return Err(ValueError::new(
"is empty; remove the key or name a network",
));
}
Ok(TrustedNets { nets })
}
}
impl Value for TrustedNets {
fn parse(raw: &str) -> Result<TrustedNets, ValueError> {
let nets = decode_string_list(raw)?
.iter()
.map(|text| {
parse_net(text).map_err(|why| ValueError::malformed_item(text.as_str(), why))
})
.collect::<Result<Vec<_>, _>>()?;
TrustedNets::try_from(nets)
}
fn format(&self) -> String {
let items: Vec<String> = self.nets.iter().map(IpNet::to_string).collect();
encode_string_list(&items)
}
}
impl Value for ForwardedHeader {
fn parse(raw: &str) -> Result<ForwardedHeader, ValueError> {
let text = decode_string(raw)?;
ForwardedHeader::parse(&text).map_err(|_| {
ValueError::malformed_value(
text,
"the value is forwarded, x-forwarded-for, or x-real-ip",
)
})
}
fn format(&self) -> String {
self.as_str().to_owned()
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct HeaderName {
name: String,
}
impl HeaderName {
pub fn as_str(&self) -> &str {
&self.name
}
pub fn into_string(self) -> String {
self.name
}
}
impl TryFrom<String> for HeaderName {
type Error = ValueError;
fn try_from(name: String) -> Result<HeaderName, ValueError> {
if !is_header_name(&name) {
return Err(ValueError::malformed_value(
name,
"the value is a header name, one or more letters, digits, and the \
characters !#$%&'*+-.^_`|~",
));
}
Ok(HeaderName { name })
}
}
impl TryFrom<&str> for HeaderName {
type Error = ValueError;
fn try_from(name: &str) -> Result<HeaderName, ValueError> {
HeaderName::try_from(name.to_owned())
}
}
impl Value for HeaderName {
fn parse(raw: &str) -> Result<HeaderName, ValueError> {
HeaderName::try_from(decode_string(raw)?)
}
fn format(&self) -> String {
encode_string(&self.name)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct PemPath {
path: String,
}
impl PemPath {
pub fn as_str(&self) -> &str {
&self.path
}
pub fn as_path(&self) -> &Path {
Path::new(&self.path)
}
pub fn into_string(self) -> String {
self.path
}
}
impl TryFrom<String> for PemPath {
type Error = ValueError;
fn try_from(path: String) -> Result<PemPath, ValueError> {
if path.is_empty() {
return Err(ValueError::new("is empty; remove the key or name a file"));
}
check_config_path(&path)?;
Ok(PemPath { path })
}
}
impl TryFrom<&str> for PemPath {
type Error = ValueError;
fn try_from(path: &str) -> Result<PemPath, ValueError> {
PemPath::try_from(path.to_owned())
}
}
impl Value for PemPath {
fn parse(raw: &str) -> Result<PemPath, ValueError> {
PemPath::try_from(decode_string(raw)?)
}
fn format(&self) -> String {
encode_string(&self.path)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct PositiveInt {
value: u64,
}
impl PositiveInt {
pub fn get(self) -> u64 {
self.value
}
}
impl TryFrom<i64> for PositiveInt {
type Error = ValueError;
fn try_from(value: i64) -> Result<PositiveInt, ValueError> {
match u64::try_from(value) {
Ok(n) if n >= 1 => Ok(PositiveInt { value: n }),
_ => Err(ValueError::new(format!(
"is {value}; the value is a positive integer"
))),
}
}
}
impl Value for PositiveInt {
fn parse(raw: &str) -> Result<PositiveInt, ValueError> {
PositiveInt::try_from(decode_integer(raw)?)
}
fn format(&self) -> String {
self.value.to_string()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct UploadStreams {
streams: u32,
}
impl UploadStreams {
pub fn get(self) -> u32 {
self.streams
}
}
impl TryFrom<i64> for UploadStreams {
type Error = ValueError;
fn try_from(streams: i64) -> Result<UploadStreams, ValueError> {
match u32::try_from(streams) {
Ok(n) if (1..=31).contains(&n) => Ok(UploadStreams { streams: n }),
_ => Err(ValueError::new(format!(
"is {streams}; the value is 1 to 31"
))),
}
}
}
impl Value for UploadStreams {
fn parse(raw: &str) -> Result<UploadStreams, ValueError> {
UploadStreams::try_from(decode_integer(raw)?)
}
fn format(&self) -> String {
self.streams.to_string()
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct KeyGroupNames {
names: Vec<String>,
}
impl KeyGroupNames {
pub fn names(&self) -> &[String] {
&self.names
}
pub fn into_names(self) -> Vec<String> {
self.names
}
}
impl TryFrom<Vec<String>> for KeyGroupNames {
type Error = ValueError;
fn try_from(names: Vec<String>) -> Result<KeyGroupNames, ValueError> {
if names.is_empty() {
return Err(ValueError::new(
"is empty; remove the key or name a key group",
));
}
let mut seen = HashSet::with_capacity(names.len());
let kept: Vec<String> = names
.into_iter()
.filter(|name| seen.insert(name.clone()))
.collect();
Ok(KeyGroupNames { names: kept })
}
}
impl Value for KeyGroupNames {
fn parse(raw: &str) -> Result<KeyGroupNames, ValueError> {
KeyGroupNames::try_from(decode_string_list(raw)?)
}
fn format(&self) -> String {
encode_string_list(&self.names)
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct AuthItems {
items: Vec<AuthItem>,
}
impl AuthItems {
pub fn items(&self) -> &[AuthItem] {
&self.items
}
pub fn into_items(self) -> Vec<AuthItem> {
self.items
}
}
impl Value for AuthItems {
fn parse(raw: &str) -> Result<AuthItems, ValueError> {
let entries = decode_string_list(raw)?;
let mut seen = HashSet::with_capacity(entries.len());
let mut items = Vec::with_capacity(entries.len());
for text in entries {
let item =
parse_item(&text).map_err(|why| ValueError::malformed_item(text.as_str(), why))?;
if seen.insert(item.clone()) {
items.push(item);
}
}
Ok(AuthItems { items })
}
fn format(&self) -> String {
let items: Vec<String> = self.items.iter().map(AuthItem::to_string).collect();
encode_string_list(&items)
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct AllowItems {
entries: Vec<(Option<String>, AllowItem)>,
}
impl AllowItems {
pub fn entries(&self) -> impl Iterator<Item = (Option<&str>, &AllowItem)> {
self.entries.iter().map(|(id, item)| (id.as_deref(), item))
}
pub fn into_entries(self) -> impl Iterator<Item = (Option<String>, AllowItem)> {
self.entries.into_iter()
}
}
impl Value for AllowItems {
fn parse(raw: &str) -> Result<AllowItems, ValueError> {
let entries = decode_string_list(raw)?
.iter()
.map(|text| {
parse_allow_item(text).map_err(|why| ValueError::malformed_item(text.as_str(), why))
})
.collect::<Result<Vec<_>, _>>()?;
Ok(AllowItems { entries })
}
fn format(&self) -> String {
let items: Vec<String> = self
.entries
.iter()
.map(|(id, item)| match id {
Some(id) => format!("{}:@{id}:{}", item.modes, item.pattern.as_str()),
None => item.to_string(),
})
.collect();
encode_string_list(&items)
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct DenyItems {
entries: Vec<(Option<String>, RefPattern)>,
}
impl DenyItems {
pub fn entries(&self) -> impl Iterator<Item = (Option<&str>, &RefPattern)> {
self.entries
.iter()
.map(|(id, pattern)| (id.as_deref(), pattern))
}
pub fn into_entries(self) -> impl Iterator<Item = (Option<String>, RefPattern)> {
self.entries.into_iter()
}
}
impl Value for DenyItems {
fn parse(raw: &str) -> Result<DenyItems, ValueError> {
let entries = decode_string_list(raw)?
.iter()
.map(|text| {
parse_deny_item(text).map_err(|why| ValueError::malformed_item(text.as_str(), why))
})
.collect::<Result<Vec<_>, _>>()?;
Ok(DenyItems { entries })
}
fn format(&self) -> String {
let items: Vec<String> = self
.entries
.iter()
.map(|(id, pattern)| match id {
Some(id) => format!("@{id}:{}", pattern.as_str()),
None => pattern.as_str().to_owned(),
})
.collect();
encode_string_list(&items)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct TrustRef {
group: GroupRef<trust::Group>,
}
impl TrustRef {
pub fn group(&self) -> &GroupRef<trust::Group> {
&self.group
}
pub fn into_group(self) -> GroupRef<trust::Group> {
self.group
}
}
impl From<GroupRef<trust::Group>> for TrustRef {
fn from(group: GroupRef<trust::Group>) -> TrustRef {
TrustRef { group }
}
}
impl Value for TrustRef {
fn parse(raw: &str) -> Result<TrustRef, ValueError> {
let text = decode_string(raw)?;
if let Some(name) = text.strip_prefix("trust:")
&& let Ok(group) = GroupRef::new(name)
{
return Ok(TrustRef { group });
}
let why = if text.starts_with("remote:") {
"the remote:NAME form is removed; name a trust group with trust:NAME"
} else {
"the value is trust:NAME; leave out the key for no verification"
};
Err(ValueError::malformed_value(text, why))
}
fn format(&self) -> String {
encode_string(&format!("trust:{}", self.group.name()))
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct TrustGroupName {
group: GroupRef<trust::Group>,
}
impl TrustGroupName {
pub fn group(&self) -> &GroupRef<trust::Group> {
&self.group
}
pub fn into_group(self) -> GroupRef<trust::Group> {
self.group
}
}
impl TryFrom<String> for TrustGroupName {
type Error = ValueError;
fn try_from(name: String) -> Result<TrustGroupName, ValueError> {
if name.is_empty() || name.chars().any(|c| c == '"' || c.is_control()) {
return Err(ValueError::malformed_value(
name,
"the value names a trust group, is not empty, and holds no '\"' and no \
control character",
));
}
Ok(TrustGroupName {
group: GroupRef::new(name)?,
})
}
}
impl TryFrom<&str> for TrustGroupName {
type Error = ValueError;
fn try_from(name: &str) -> Result<TrustGroupName, ValueError> {
TrustGroupName::try_from(name.to_owned())
}
}
impl Value for TrustGroupName {
fn parse(raw: &str) -> Result<TrustGroupName, ValueError> {
TrustGroupName::try_from(decode_string(raw)?)
}
fn format(&self) -> String {
encode_string(self.group.name())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum SigningKeyType {
Ed25519,
Spki,
Gpg,
}
impl SigningKeyType {
pub fn as_str(self) -> &'static str {
match self {
SigningKeyType::Ed25519 => "ed25519",
SigningKeyType::Spki => "spki",
SigningKeyType::Gpg => "gpg",
}
}
}
impl Value for SigningKeyType {
fn parse(raw: &str) -> Result<SigningKeyType, ValueError> {
let text = decode_string(raw)?;
match text.as_str() {
"ed25519" => Ok(SigningKeyType::Ed25519),
"spki" => Ok(SigningKeyType::Spki),
"gpg" => Ok(SigningKeyType::Gpg),
"dummy" => Err(ValueError::malformed_value(
text,
"the dummy engine is not a signing key, its signature is its key",
)),
_ => Err(ValueError::malformed_value(
text,
"the type is ed25519, spki, or gpg",
)),
}
}
fn format(&self) -> String {
self.as_str().to_owned()
}
}
#[cfg(test)]
mod tests {
use super::*;
fn round_trips<V: Value + PartialEq + std::fmt::Debug>(value: V) {
let text = value.format();
assert_eq!(V::parse(&text), Ok(value), "{text:?}");
}
#[test]
fn trust_group_name_values() {
let name = TrustGroupName::parse(r"a\sb").unwrap();
assert_eq!(name.group().name(), "a b");
round_trips(name);
round_trips(TrustGroupName::try_from("release").unwrap());
let why = "the value names a trust group, is not empty, and holds no '\"' and no \
control character";
for (raw, text) in [
("", ""),
("a\"b", "a\"b"),
(r"a\tb", "a\tb"),
(r"a\nb", "a\nb"),
] {
assert_eq!(
TrustGroupName::parse(raw).unwrap_err(),
ValueError::malformed_value(text, why),
"{raw:?}"
);
}
assert_eq!(
value_error(
"remote \"o\"",
"trust",
"",
TrustGroupName::parse("").unwrap_err()
)
.to_string(),
"invalid format: malformed [remote \"o\"] trust value '': the value names a trust \
group, is not empty, and holds no '\"' and no control character"
);
assert_eq!(
TrustGroupName::parse(r"\q").unwrap_err().to_string(),
r"invalid escape '\q'"
);
}
#[test]
fn signing_key_type_values() {
for (text, kind) in [
("ed25519", SigningKeyType::Ed25519),
("spki", SigningKeyType::Spki),
("gpg", SigningKeyType::Gpg),
] {
assert_eq!(SigningKeyType::parse(text), Ok(kind));
assert_eq!(kind.as_str(), text);
round_trips(kind);
}
assert_eq!(
SigningKeyType::parse("dummy").unwrap_err().to_string(),
"malformed value 'dummy': the dummy engine is not a signing key, its signature is \
its key"
);
for raw in ["", "rsa", "ED25519", " gpg", r"\sgpg"] {
let text = decode_string(raw).unwrap();
assert_eq!(
SigningKeyType::parse(raw).unwrap_err().to_string(),
format!("malformed value '{text}': the type is ed25519, spki, or gpg"),
"{raw:?}"
);
}
assert_eq!(
SigningKeyType::parse(r"ed\q").unwrap_err().to_string(),
r"invalid escape '\q'"
);
}
#[test]
fn helpers_decode_and_encode() {
assert_eq!(decode_string(r"a\sb\;c").unwrap(), "a b;c");
assert_eq!(
decode_string(r"\q").unwrap_err().to_string(),
r"invalid escape '\q'"
);
assert_eq!(encode_string(" a;b"), r"\s\sa;b");
assert_eq!(decode_bool("1"), Ok(true));
assert_eq!(decode_bool("0"), Ok(false));
assert_eq!(
decode_bool("yes").unwrap_err().to_string(),
"is not a boolean"
);
assert_eq!(encode_bool(true), "true");
assert_eq!(encode_bool(false), "false");
assert_eq!(decode_integer("-5"), Ok(-5));
assert_eq!(
decode_integer("+5").unwrap_err().to_string(),
"is not an integer"
);
assert_eq!(encode_integer(-5), "-5");
assert_eq!(
decode_string_list(r"a;b\;c;").unwrap(),
["a".to_owned(), "b;c".to_owned()]
);
assert_eq!(
decode_string_list("a\\").unwrap_err().to_string(),
"value ends with a lone backslash"
);
assert_eq!(encode_string_list(&["a", "b;c", " d"]), r"a;b\;c;\sd;");
}
#[test]
fn value_error_renders_with_the_group_and_the_key() {
let render = |err| value_error("core", "fsync", "x", err).to_string();
assert_eq!(
render(decode_bool("x").unwrap_err()),
"keyfile: value 'x' for core.fsync is not a boolean"
);
assert_eq!(
render(decode_integer("x").unwrap_err()),
"keyfile: value 'x' for core.fsync is not an integer"
);
assert_eq!(
render(decode_string(r"\q").unwrap_err()),
r"keyfile: invalid escape '\q'"
);
assert_eq!(
render(ValueError::new("is empty")),
"invalid format: [core] fsync is empty"
);
}
#[test]
fn bool_integer_and_text_values() {
assert_eq!(bool::parse("1"), Ok(true));
assert!(bool::parse("yes").is_err());
round_trips(true);
round_trips(false);
assert_eq!(i64::parse("-9223372036854775808"), Ok(i64::MIN));
round_trips(i64::MIN);
round_trips(i64::MAX);
assert_eq!(u8::parse("255"), Ok(255));
assert_eq!(
u8::parse("256").unwrap_err().to_string(),
"256 is out of the range 0-255"
);
assert_eq!(
i8::parse("-129").unwrap_err().to_string(),
"-129 is out of the range -128-127"
);
assert_eq!(
u32::parse("-1").unwrap_err().to_string(),
"-1 is out of the range 0-4294967295"
);
round_trips(7u16);
round_trips(-7i32);
assert_eq!(String::parse(r"\sa"), Ok(" a".to_owned()));
round_trips(" a\\b\nc;".to_owned());
round_trips(String::new());
assert_eq!(
Vec::<String>::parse("a;b;"),
Ok(vec!["a".to_owned(), "b".to_owned()])
);
round_trips(vec!["a;b".to_owned(), " c".to_owned(), String::new()]);
round_trips(Vec::<String>::new());
}
#[test]
fn u64_reads_its_full_range() {
let above = u64::try_from(i64::MAX).unwrap() + 1;
assert_eq!(u64::parse("9223372036854775808"), Ok(above));
assert_eq!(u64::parse("18446744073709551615"), Ok(u64::MAX));
for value in [0, u64::try_from(i64::MAX).unwrap(), above, u64::MAX] {
round_trips(value);
}
assert_eq!(
u64::parse("-1").unwrap_err().to_string(),
"-1 is out of the range 0-18446744073709551615"
);
for bad in [
"+1",
"+18446744073709551615",
"18446744073709551616",
"x",
"",
] {
assert_eq!(
u64::parse(bad).unwrap_err().to_string(),
"is not an integer",
"{bad:?}"
);
}
}
#[test]
fn tristate_values() {
assert_eq!(<Tristate as Value>::parse("yes"), Ok(Tristate::Yes));
assert_eq!(<Tristate as Value>::parse("maybe"), Ok(Tristate::Maybe));
assert_eq!(
<Tristate as Value>::parse("true").unwrap_err().to_string(),
"value 'true' is not no, maybe, or yes"
);
for value in [Tristate::No, Tristate::Maybe, Tristate::Yes] {
round_trips(value);
}
}
#[test]
fn sign_verify_values() {
assert_eq!(SignVerify::parse("1"), Ok(SignVerify::All));
assert_eq!(SignVerify::parse(""), Ok(SignVerify::Off));
assert_eq!(
SignVerify::parse(r"ed25519,\sspki"),
Ok(SignVerify::Engines(vec![
"ed25519".to_owned(),
" spki".to_owned()
]))
);
assert!(SignVerify::parse(r"\q").is_err());
round_trips(SignVerify::Off);
round_trips(SignVerify::All);
round_trips(SignVerify::Engines(vec![
" ed25519".to_owned(),
"spki".to_owned(),
]));
for names in [&["true"][..], &["0"], &["1"], &["false"], &["a", "b"]] {
round_trips(SignVerify::Engines(
names.iter().map(|name| (*name).to_owned()).collect(),
));
}
assert_eq!(
SignVerify::Engines(vec!["a".to_owned(), "b".to_owned()]).format(),
"a;b;"
);
assert_eq!(SignVerify::Engines(Vec::new()).format(), "");
assert_eq!(SignVerify::parse(""), Ok(SignVerify::Off));
}
#[test]
fn size_values_read_the_raw_text() {
assert_eq!(
SizeSpec::parse("2GB"),
Ok(SizeSpec {
value: 2,
unit: SizeUnit::Giga
})
);
assert_eq!(
SizeSpec::parse(r"\s1GB").unwrap_err().to_string(),
r"value '\s1GB' is not of the form 123MB, 123GB, or 123TB"
);
for unit in [SizeUnit::Mega, SizeUnit::Giga, SizeUnit::Tera] {
round_trips(SizeSpec { value: 500, unit });
}
}
#[test]
fn mode_values() {
assert_eq!(RepoMode::parse("archive"), Ok(RepoMode::Archive));
assert_eq!(RepoMode::Archive.format(), "archive-z2");
assert_eq!(
RepoMode::parse("bogus").unwrap_err().to_string(),
"'bogus' names no repository mode"
);
for mode in [
RepoMode::Bare,
RepoMode::BareUser,
RepoMode::BareUserOnly,
RepoMode::BareSplitXattrs,
RepoMode::Archive,
RepoMode::BareUserShared,
RepoMode::BareUserPrivate,
] {
round_trips(mode);
}
}
#[test]
fn newtypes_keep_their_bounds() {
assert_eq!(LockTimeout::parse("-1").map(LockTimeout::get), Ok(-1));
assert_eq!(
LockTimeout::parse("-2").unwrap_err().to_string(),
"-2 is below -1"
);
assert!(LockTimeout::parse("x").is_err());
round_trips(LockTimeout::new_const(300));
round_trips(LockTimeout::new_const(-1));
assert_eq!(
FreeSpacePercent::parse("0").map(FreeSpacePercent::get),
Ok(0)
);
assert_eq!(
FreeSpacePercent::parse("100").map(FreeSpacePercent::get),
Ok(100)
);
for bad in ["-1", "101", "4294967296"] {
assert_eq!(
FreeSpacePercent::parse(bad).unwrap_err().to_string(),
format!("{bad} is out of the range 0-100")
);
}
round_trips(FreeSpacePercent::new_const(3));
assert_eq!(
CollectionIdValue::parse("org.ex.C").map(CollectionIdValue::into_string),
Ok("org.ex.C".to_owned())
);
assert_eq!(
CollectionIdValue::parse("a b").unwrap_err().to_string(),
"value 'a b' is not a valid collection id"
);
round_trips(CollectionIdValue::try_from("org.ex.C").unwrap());
assert_eq!(
RemotesConfigPath::parse("").unwrap_err().to_string(),
"is empty"
);
assert_eq!(
RemotesConfigPath::try_from("a\0b").unwrap_err().to_string(),
"holds a NUL byte"
);
assert_eq!(
RemotesConfigPath::parse("../x").unwrap_err().to_string(),
"../x has a `..` component, which a relative path in a config cannot have"
);
let path = RemotesConfigPath::parse("/abs/../x").unwrap();
assert_eq!(path.as_path(), Path::new("/abs/../x"));
assert_eq!(RemotesConfigPath::parse(r"\sr.d").unwrap().as_str(), " r.d");
round_trips(path);
round_trips(RemotesConfigPath::try_from(" r.d").unwrap());
}
#[test]
fn config_paths_refuse_a_relative_parent() {
assert_eq!(
ConfigPath::parse("").map(ConfigPath::into_string),
Ok(String::new())
);
assert_eq!(ConfigPath::parse(r"a\sb").unwrap().as_str(), "a b");
assert_eq!(
ConfigPath::parse("../x").unwrap_err().to_string(),
"../x has a `..` component, which a relative path in a config cannot have"
);
assert!(ConfigPath::parse(r"\q").is_err());
let path = ConfigPath::parse("/abs/../x").unwrap();
assert_eq!(path.as_path(), Path::new("/abs/../x"));
round_trips(path);
round_trips(ConfigPath::try_from(" k.pem").unwrap());
round_trips(ConfigPath::try_from("").unwrap());
}
#[test]
fn keyring_paths_split_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 (raw, want) in cases {
let paths = KeyringPaths::parse(raw).unwrap();
assert_eq!(paths.entries(), *want, "{raw:?}");
round_trips(paths);
}
assert_eq!(
KeyringPaths::parse("/a;../k").unwrap_err().to_string(),
"../k has a `..` component, which a relative path in a config cannot have"
);
assert!(KeyringPaths::parse("/etc/../k").is_ok());
assert_eq!(KeyringPaths::default().format(), "");
assert_eq!(KeyringPaths::parse("a;;").unwrap().format(), "a;;");
}
#[test]
fn malformed_errors_render_with_the_group_and_the_key() {
let render = |err| value_error("ex-ostrya server", "listen", "x", err).to_string();
assert_eq!(
render(ValueError::malformed_item("x", "why")),
"invalid format: malformed [ex-ostrya server] listen item 'x': why"
);
assert_eq!(
render(ValueError::malformed_value("x", "why")),
"invalid format: malformed [ex-ostrya server] listen value 'x': why"
);
assert_eq!(
ValueError::malformed_item("x", "why").to_string(),
"malformed item 'x': why"
);
assert_eq!(
ValueError::malformed_value("x", "why").to_string(),
"malformed value 'x': why"
);
}
#[test]
fn listen_addresses_are_checked() {
let addrs = ListenAddrs::parse("127.0.0.1:80;[::1]:81;").unwrap();
assert_eq!(
addrs.addrs(),
[
"127.0.0.1:80".parse::<SocketAddr>().unwrap(),
"[::1]:81".parse().unwrap()
]
);
assert_eq!(addrs.format(), "127.0.0.1:80;[::1]:81;");
round_trips(addrs);
assert_eq!(
ListenAddrs::parse("").unwrap_err().to_string(),
"is empty; remove the key for the default address"
);
assert_eq!(
ListenAddrs::parse("localhost:80").unwrap_err(),
ValueError::malformed_item(
"localhost:80",
"the item is ADDR:PORT, an IP address and a port"
)
);
assert_eq!(
ListenAddrs::parse("a\\").unwrap_err().to_string(),
"value ends with a lone backslash"
);
assert_eq!(
ListenAddrs::try_from(Vec::new()).unwrap_err().to_string(),
"is empty; remove the key for the default address"
);
}
#[test]
fn listen_addresses_refuse_a_flow_label() {
let addr: SocketAddr =
std::net::SocketAddrV6::new(std::net::Ipv6Addr::LOCALHOST, 80, 5, 0).into();
let err = ListenAddrs::try_from(vec![addr]).unwrap_err();
assert_eq!(
err.to_string(),
"malformed item '[::1]:80': the address has a flow label, which a config \
cannot hold"
);
assert_eq!(
value_error("ex-ostrya server", "listen", "x", err).to_string(),
"invalid format: malformed [ex-ostrya server] listen item '[::1]:80': the \
address has a flow label, which a config cannot hold"
);
let parsed = ListenAddrs::parse("[::1]:80").unwrap();
assert!(matches!(parsed.addrs(), [SocketAddr::V6(v6)] if v6.flowinfo() == 0));
assert_eq!(parsed.format(), "[::1]:80;");
round_trips(parsed);
}
#[test]
fn trusted_networks_are_checked() {
let nets = TrustedNets::parse("10.0.0.0/8;2001:db8::1").unwrap();
assert_eq!(nets.format(), "10.0.0.0/8;2001:db8::1/128;");
assert_eq!(nets.nets().len(), 2);
round_trips(nets);
assert_eq!(
TrustedNets::parse("").unwrap_err().to_string(),
"is empty; remove the key or name a network"
);
assert_eq!(
TrustedNets::parse("10.0.0.1/24").unwrap_err(),
ValueError::malformed_item("10.0.0.1/24", "the address has host bits set")
);
assert_eq!(
TrustedNets::try_from(Vec::new()).unwrap_err().to_string(),
"is empty; remove the key or name a network"
);
}
#[test]
fn forwarded_headers_and_header_names_are_checked() {
for header in [
ForwardedHeader::Forwarded,
ForwardedHeader::XForwardedFor,
ForwardedHeader::XRealIp,
] {
round_trips(header);
}
assert_eq!(
ForwardedHeader::parse("x-real-ip").ok(),
<ForwardedHeader as Value>::parse("x-real-ip").ok()
);
assert_eq!(
<ForwardedHeader as Value>::parse("X-Real-IP").unwrap_err(),
ValueError::malformed_value(
"X-Real-IP",
"the value is forwarded, x-forwarded-for, or x-real-ip"
)
);
assert_eq!(
<ForwardedHeader as Value>::parse("")
.unwrap_err()
.to_string(),
"malformed value '': the value is forwarded, x-forwarded-for, or x-real-ip"
);
let name = HeaderName::parse("X-SSL-Client-Cert").unwrap();
assert_eq!(name.as_str(), "X-SSL-Client-Cert");
round_trips(name);
for bad in ["", "X Client", "X:Client"] {
assert_eq!(
HeaderName::try_from(bad).unwrap_err(),
ValueError::malformed_value(
bad,
"the value is a header name, one or more letters, digits, and the \
characters !#$%&'*+-.^_`|~"
),
"{bad:?}"
);
}
assert_eq!(
HeaderName::parse(r"X\sClient").unwrap_err().to_string(),
"malformed value 'X Client': the value is a header name, one or more letters, \
digits, and the characters !#$%&'*+-.^_`|~"
);
}
#[test]
fn pem_paths_refuse_an_empty_path_and_a_relative_parent() {
assert_eq!(
PemPath::parse("").unwrap_err().to_string(),
"is empty; remove the key or name a file"
);
assert_eq!(
PemPath::parse("../c.pem").unwrap_err().to_string(),
"../c.pem has a `..` component, which a relative path in a config cannot have"
);
assert_eq!(
PemPath::parse(r"\q").unwrap_err().to_string(),
r"invalid escape '\q'"
);
let path = PemPath::parse(r"\sc.pem").unwrap();
assert_eq!(path.as_path(), Path::new(" c.pem"));
round_trips(path);
round_trips(PemPath::try_from("/etc/../c.pem").unwrap());
assert_eq!(
PemPath::try_from("~/c.pem").map(PemPath::into_string),
Ok("~/c.pem".to_owned())
);
}
#[test]
fn positive_integers_and_upload_streams_keep_their_bounds() {
assert_eq!(PositiveInt::parse("1").map(PositiveInt::get), Ok(1));
assert_eq!(
PositiveInt::parse("9223372036854775807").map(PositiveInt::get),
Ok(9_223_372_036_854_775_807)
);
for bad in ["0", "-1", "-9223372036854775808"] {
assert_eq!(
PositiveInt::parse(bad).unwrap_err().to_string(),
format!("is {bad}; the value is a positive integer")
);
}
for bad in ["9223372036854775808", "+1", "1 ", "x", ""] {
assert_eq!(
PositiveInt::parse(bad).unwrap_err().to_string(),
"is not an integer",
"{bad:?}"
);
}
round_trips(PositiveInt::try_from(1).unwrap());
round_trips(PositiveInt::try_from(i64::MAX).unwrap());
assert_eq!(UploadStreams::parse("1").map(UploadStreams::get), Ok(1));
assert_eq!(UploadStreams::parse("31").map(UploadStreams::get), Ok(31));
for bad in ["0", "32", "-1", "4294967297"] {
assert_eq!(
UploadStreams::parse(bad).unwrap_err().to_string(),
format!("is {bad}; the value is 1 to 31")
);
}
assert_eq!(
UploadStreams::parse("0x4").unwrap_err().to_string(),
"is not an integer"
);
for n in [1, 16, 31] {
round_trips(UploadStreams::try_from(n).unwrap());
}
}
#[test]
fn key_group_names_drop_a_repeated_name() {
let names = KeyGroupNames::parse("b;a;b;").unwrap();
assert_eq!(names.names(), ["b", "a"]);
let names = KeyGroupNames::parse("c;a;c;b;a;c;").unwrap();
assert_eq!(names.names(), ["c", "a", "b"]);
round_trips(names);
let names = KeyGroupNames::parse(";").unwrap();
assert_eq!(names.names(), [""]);
round_trips(names);
round_trips(KeyGroupNames::try_from(vec!["a;b".to_owned(), " c".to_owned()]).unwrap());
assert_eq!(
KeyGroupNames::parse("").unwrap_err().to_string(),
"is empty; remove the key or name a key group"
);
assert_eq!(
KeyGroupNames::parse(r"k\q").unwrap_err().to_string(),
r"invalid escape '\q'"
);
assert_eq!(
KeyGroupNames::try_from(Vec::new()).unwrap_err().to_string(),
"is empty; remove the key or name a key group"
);
}
#[test]
fn collection_id_lists_are_checked() {
assert_eq!(
CollectionIdList::parse("org.ex.B;org.ex.A;org.ex.B;").map(CollectionIdList::into_ids),
Ok(vec!["org.ex.B".to_owned(), "org.ex.A".to_owned()])
);
assert_eq!(
CollectionIdList::parse("").unwrap_err().to_string(),
"holds no collection id"
);
for (raw, id) in [(";", ""), ("org.ex.A;;org.ex.B", ""), ("org/ex", "org/ex")] {
assert_eq!(
CollectionIdList::parse(raw).unwrap_err().to_string(),
format!("holds the invalid collection id '{id}'"),
"{raw:?}"
);
}
assert!(CollectionIdList::parse(r"org.ex.A\q").is_err());
round_trips(CollectionIdList::parse("org.ex.A;org.ex.B").unwrap());
}
#[test]
fn auth_items_drop_a_repeated_item() {
let items =
AuthItems::parse("ssh:a;anonymous;ssh:a;net:2001:db8::/56;net:2001:0db8::/56").unwrap();
let texts: Vec<String> = items.items().iter().map(AuthItem::to_string).collect();
assert_eq!(texts, ["ssh:a", "anonymous", "net:2001:db8::/56"]);
assert_eq!(items.format(), "ssh:a;anonymous;net:2001:db8::/56;");
round_trips(items);
let items = AuthItems::parse("").unwrap();
assert!(items.items().is_empty());
round_trips(items);
round_trips(AuthItems::parse(r"ssh:a\;b;tls:x\sy").unwrap());
let forms = "the item is anonymous, tls:*, tls:NAME, tls-sha256:HEX, \
token-sha256:HEX, basic-sha256:USER:HEX, ssh:NAME, or net:CIDR";
for (raw, text) in [("bogus", "bogus"), (";", ""), ("anonymous;;ssh:a", "")] {
assert_eq!(
AuthItems::parse(raw).unwrap_err().to_string(),
format!("malformed item '{text}': {forms}"),
"{raw:?}"
);
}
assert_eq!(
AuthItems::parse("ssh: b").unwrap_err().to_string(),
"malformed item 'ssh: b': the NAME of ssh:NAME is not empty, holds no control \
character, and does not start or end with white space"
);
assert_eq!(
AuthItems::parse(r"a\q").unwrap_err().to_string(),
r"invalid escape '\q'"
);
}
#[test]
fn allow_items_keep_each_entry_and_its_collection() {
let items = AllowItems::parse("os/**;rw:os/x;@a.b:y;wd:@a.b:z;os/**").unwrap();
let entries: Vec<(Option<&str>, String)> = items
.entries()
.map(|(id, item)| (id, item.to_string()))
.collect();
assert_eq!(
entries,
[
(None, "r:os/**".to_owned()),
(None, "rw:os/x".to_owned()),
(Some("a.b"), "r:y".to_owned()),
(Some("a.b"), "wd:z".to_owned()),
(None, "r:os/**".to_owned()),
]
);
assert_eq!(
items.format(),
"r:os/**;rw:os/x;r:@a.b:y;wd:@a.b:z;r:os/**;"
);
round_trips(items);
round_trips(AllowItems::default());
assert_eq!(AllowItems::default().format(), "");
assert_eq!(AllowItems::parse("").unwrap(), AllowItems::default());
for (raw, why) in [
("R:a", "the modes are one or more of r, w, c, t, and d"),
("rr:a", "each mode occurs at most one time"),
("@a.b", "a collection id is @ID: before the pattern"),
("@fresh:a", "the collection id fails the collection-id rule"),
] {
assert_eq!(
AllowItems::parse(raw).unwrap_err().to_string(),
format!("malformed item '{raw}': {why}"),
"{raw:?}"
);
}
assert_eq!(
AllowItems::parse(r"a\").unwrap_err().to_string(),
"value ends with a lone backslash"
);
}
#[test]
fn deny_items_keep_each_entry_and_its_collection() {
let items = DenyItems::parse("os/secret/**;@a.b:x;y;y").unwrap();
let entries: Vec<(Option<&str>, &str)> = items
.entries()
.map(|(id, pattern)| (id, pattern.as_str()))
.collect();
assert_eq!(
entries,
[
(None, "os/secret/**"),
(Some("a.b"), "x"),
(None, "y"),
(None, "y")
]
);
assert_eq!(items.format(), "os/secret/**;@a.b:x;y;y;");
round_trips(items);
round_trips(DenyItems::default());
for (raw, why) in [
("@a.b", "a collection id is @ID: before the pattern"),
("@1a.b:a", "the collection id fails the collection-id rule"),
] {
assert_eq!(
DenyItems::parse(raw).unwrap_err().to_string(),
format!("malformed item '{raw}': {why}"),
"{raw:?}"
);
}
assert!(
DenyItems::parse("r:a")
.unwrap_err()
.to_string()
.starts_with("malformed item 'r:a': ")
);
assert_eq!(
DenyItems::parse(r"a\q").unwrap_err().to_string(),
r"invalid escape '\q'"
);
}
#[test]
fn a_trust_ref_takes_trust_name_alone() {
let verify = TrustRef::parse("trust:ci").unwrap();
assert_eq!(verify.group().name(), "ci");
round_trips(verify);
let verify = TrustRef::parse(r"trust:a\sb").unwrap();
assert_eq!(verify.group().name(), "a b");
assert_eq!(verify.format(), "trust:a b");
round_trips(verify);
round_trips(TrustRef::from(GroupRef::new(" a;b").unwrap()));
let other = "the value is trust:NAME; leave out the key for no verification";
for (raw, text) in [
("off", "off"),
("", ""),
("trust:", "trust:"),
("t", "t"),
("Trust:t", "Trust:t"),
(r"of\sf", "of f"),
] {
assert_eq!(
TrustRef::parse(raw).unwrap_err().to_string(),
format!("malformed value '{text}': {other}"),
"{raw:?}"
);
}
assert_eq!(
TrustRef::parse("remote:origin").unwrap_err().to_string(),
"malformed value 'remote:origin': the remote:NAME form is removed; name a trust \
group with trust:NAME"
);
assert_eq!(
TrustRef::parse(r"trust:\q").unwrap_err().to_string(),
r"invalid escape '\q'"
);
}
}