use std::collections::HashSet;
use ostrya_core::RefPattern;
use super::{
GroupRef, Value, ValueError, decode_string, decode_string_list, encode_string,
encode_string_list, trust,
};
use crate::access::{
AllowItem, AuthItem, ForwardedHeader, IpNet, is_header_name, parse_allow_item, parse_deny_item,
parse_item, parse_net,
};
#[cfg(test)]
pub(crate) fn value_error(
group: &str,
key: &str,
raw: &str,
err: ValueError,
) -> crate::error::Error {
ostrya_core::config::value_error(group, key, raw, err).into()
}
#[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, 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())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::config::{DottedOid, decode_bool, decode_integer};
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 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 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 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 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'"
);
}
fn oid_boundaries() -> Vec<(String, bool)> {
let ones = |count: usize| vec!["1"; count].join(".");
let wide = |count: usize| vec!["268435455"; count].join(".");
let mut values: Vec<(String, bool)> = [
("1.3.6.1.5.5.7.3.3", true),
("1.2.840", true),
("1.2.3.4", true),
("0.0.0.0", true),
("2.39.0.0", true),
("1.0.127.0", true),
("1.2.129", true),
("1.2.16383", true),
("1.2.16512", true),
("1.2.2097151", true),
("1.2.2113536", true),
("1.2.268435455", true),
("", false),
("1", false),
("1.2", false),
("1.2.3", false),
("3.1.1.1", false),
("0.40.1.1", false),
("1.40.1.1", false),
("2.40.1.1", false),
("2.999.1", false),
("1.2.128", false),
("1.2.16384", false),
("1.2.16511", false),
("1.2.2097152", false),
("1.2.2113535", false),
("1.2.268435456", false),
("1.3.6.1.4.1.4294967296", false),
("1.3.6.1.4.1.18446744073709551616", false),
("1..2.3", false),
("1.2.3.", false),
(".1.2.3", false),
("1.02.3.4", false),
("1.2.00.4", false),
("+1.2.3.4", false),
("1.2.3.-4", false),
("1.2.3.4 ", false),
("1.2.\u{0663}.4", false),
("codeSigning", false),
]
.into_iter()
.map(|(oid, valid)| (oid.to_owned(), valid))
.collect();
values.push((format!("1.2.{}", ones(37)), true));
values.push((format!("1.2.{}", ones(38)), false));
values.push((format!("1.2.{}.1", wide(9)), true));
values.push((format!("1.2.{}", wide(10)), false));
values
}
#[test]
fn dotted_oid_values() {
for (oid, valid) in oid_boundaries() {
match DottedOid::try_from(oid.clone()) {
Ok(read) => {
assert!(valid, "{oid:?} is valid");
assert_eq!(read.as_str(), oid);
round_trips(read);
}
Err(e) => {
assert!(!valid, "{oid:?} is not valid");
assert_eq!(
e,
ValueError::malformed_value(
oid.as_str(),
"the value is an OID in dotted form, for example 1.3.6.1.5.5.7.3.3"
),
"{oid:?}"
);
}
}
}
}
#[cfg(all(feature = "sign-spki", feature = "sign-x509"))]
#[test]
fn dotted_oid_values_are_the_ekus_of_the_path_check() {
let trust = crate::spki::X509Trust::new(Vec::<Vec<u8>>::new(), ["*"]).unwrap();
for (oid, _) in oid_boundaries() {
assert_eq!(
DottedOid::try_from(oid.clone()).is_ok(),
trust.clone().with_eku(&oid).is_ok(),
"{oid:?}"
);
}
}
}