use std::collections::{BTreeMap, HashMap, HashSet};
use std::path::{Path, PathBuf};
use ostrya_core::{Checksum, RefPattern};
use super::item::AuthItem;
use super::rights::{AccessModes, AccessRules, AllowItem, NamespaceRules};
use super::{ClientAccess, ClientGroup, ServerFile, ServerSettings, SummaryFiles};
use crate::config::{
Key, PemPath, RepoConfig, Section, SectionExt as _, client, refuse_removed_keys,
refuse_unknown_keys, server,
};
use crate::error::{Error, Result};
use crate::summary::summary_stem;
pub(super) const SERVER_GROUP: &str = <server::Group as crate::config::Group>::NAME;
const CLIENT_PREFIX: &str = "ex-ostrya client \"";
const TRUST_PREFIX: &str = "ex-ostrya trust \"";
const KEY_PREFIX: &str = "ex-ostrya key \"";
const RECEIVE_GROUP: &str = "ex-ostrya receive";
const RECEIVE_PREFIX: &str = "ex-ostrya receive \"";
const RESERVED_PREFIX: &str = "ex-ostrya ";
pub(crate) enum Group<'a> {
Server,
Client(&'a str),
Trust(&'a str),
Key(&'a str),
}
struct Names<'a> {
trusts: HashSet<&'a str>,
keys: HashSet<&'a str>,
}
pub(super) fn read(config: &RepoConfig) -> Result<ClientAccess> {
let keyfile = config.keyfile();
let own_id = config.collection_id();
let mut server = None;
let mut clients: Vec<(&str, &str)> = Vec::new();
let mut names = Names {
trusts: HashSet::new(),
keys: HashSet::new(),
};
for group in keyfile.groups() {
match classify(group)? {
Some(Group::Server) => server = Some(group),
Some(Group::Client(name)) => clients.push((name, group)),
Some(Group::Trust(name)) => {
names.trusts.insert(name);
}
Some(Group::Key(name)) => {
names.keys.insert(name);
}
None => {}
}
}
let server = match server {
Some(_) => parse_server(config, &names)?,
None => ServerSettings::default(),
};
let mut groups = Vec::with_capacity(clients.len());
for (name, group) in clients {
let section = Section::<client::Group>::from_parts(keyfile, group, None);
groups.push(parse_client(§ion, name, group, &names, own_id)?);
}
if groups.is_empty() {
groups = implicit_groups();
}
let by_item = index(&groups);
check_overlap(&groups, &by_item)?;
let summaries = summary_digests(&groups, &by_item, own_id);
Ok(ClientAccess {
collection_id: own_id.map(str::to_owned),
server,
groups,
by_item,
summaries,
})
}
pub(crate) fn classify(group: &str) -> Result<Option<Group<'_>>> {
if group == SERVER_GROUP {
return Ok(Some(Group::Server));
}
if group == RECEIVE_GROUP || group.starts_with(RECEIVE_PREFIX) {
return Err(Error::InvalidFormat(format!(
"[{group}] is a group of the removed receive policy; a client group \
[ex-ostrya client \"NAME\"] states the rights of a push"
)));
}
if let Some(rest) = group.strip_prefix(CLIENT_PREFIX) {
return quoted(group, rest).map(|name| Some(Group::Client(name)));
}
if let Some(rest) = group.strip_prefix(TRUST_PREFIX) {
return quoted(group, rest).map(|name| Some(Group::Trust(name)));
}
if let Some(rest) = group.strip_prefix(KEY_PREFIX) {
return quoted(group, rest).map(|name| Some(Group::Key(name)));
}
if group.starts_with(RESERVED_PREFIX) {
return Err(Error::InvalidFormat(format!(
"[{group}] is not a server, client, trust, or key group"
)));
}
Ok(None)
}
fn quoted<'a>(group: &str, rest: &'a str) -> Result<&'a str> {
match rest.strip_suffix('"') {
Some(name)
if !name.is_empty() && !name.contains('"') && !name.contains(char::is_control) =>
{
Ok(name)
}
_ => Err(Error::InvalidFormat(format!(
"malformed group name [{group}]: the quoted name ends the group name, is \
not empty, and holds no '\"' and no control character"
))),
}
}
fn parse_client(
section: &Section<'_, client::Group>,
name: &str,
header: &str,
names: &Names<'_>,
own_id: Option<&str>,
) -> Result<ClientGroup> {
refuse_removed_keys(section)?;
section.refuse_unknown_keys()?;
let auth = section
.file_value::<client::Auth>()?
.map(|items| items.into_items())
.unwrap_or_default();
if auth.is_empty() {
return Err(Error::InvalidFormat(format!(
"[{header}] needs auth, a list of one or more items"
)));
}
let mut rules = NamespaceRules::default();
for (id, item) in section.get::<client::Allow>()?.into_entries() {
rules_of(&mut rules, id, own_id).allow.push(item);
}
for (id, pattern) in section.get::<client::Deny>()?.into_entries() {
rules_of(&mut rules, id, own_id).deny.push(pattern);
}
if section.contains::<client::TlsAcceptClaim>() && !auth.iter().any(AuthItem::is_tls) {
return Err(Error::InvalidFormat(format!(
"[{header}] holds tls-accept-claim, and has no tls:*, tls:NAME, or \
tls-sha256:HEX item"
)));
}
let tls_accept_claim = section.get::<client::TlsAcceptClaim>()?;
let summary = section.get::<client::Summary>()?;
if tls_accept_claim && summary {
return Err(Error::InvalidFormat(format!(
"[{header}] sets tls-accept-claim=true and summary=true; the claims of a \
client certificate cannot give the refs of a summary"
)));
}
let verify_trust = match section.get::<client::Verify>()? {
None => None,
Some(verify) => {
let trust = verify.into_group();
if !names.trusts.contains(trust.name()) {
return Err(Error::InvalidFormat(format!(
"[{header}] verify=trust:{trust} names no [{TRUST_PREFIX}{trust}\"] group",
trust = trust.name()
)));
}
Some(trust.name().to_owned())
}
};
let allow_unsigned = match section.get::<client::AllowUnsigned>()? {
Some(false) if verify_trust.is_none() => {
return Err(Error::InvalidFormat(format!(
"[{header}] sets allow-unsigned=false, which needs verify"
)));
}
Some(value) => value,
None => verify_trust.is_none(),
};
let sign = match section.get::<client::Sign>()? {
None => Vec::new(),
Some(list) => {
let list = list.into_names();
let key = <client::Sign as Key<client::Group>>::NAME;
check_key_groups(header, key, &list, names)?;
list
}
};
Ok(ClientGroup {
name: name.to_owned(),
auth,
rules,
tls_accept_claim,
verify_trust,
allow_unsigned,
sign,
allow_privileged: section.get::<client::AllowPrivileged>()?,
disable_verify_bindings: section.get::<client::DisableVerifyBindings>()?,
summary,
implicit: false,
})
}
fn rules_of<'a>(
rules: &'a mut NamespaceRules,
id: Option<String>,
own_id: Option<&str>,
) -> &'a mut AccessRules {
match id {
Some(id) if Some(id.as_str()) != own_id => rules.collections.entry(id).or_default(),
_ => &mut rules.local,
}
}
fn check_key_groups(group: &str, key: &str, list: &[String], names: &Names<'_>) -> Result<()> {
match list.iter().find(|name| !names.keys.contains(name.as_str())) {
Some(name) => Err(Error::InvalidFormat(format!(
"[{group}] {key} names the key group '{name}', and no \
[{KEY_PREFIX}{name}\"] group exists"
))),
None => Ok(()),
}
}
pub(super) fn implicit_groups() -> Vec<ClientGroup> {
let read_all = AccessRules {
allow: vec![AllowItem {
modes: AccessModes::READ,
pattern: RefPattern::parse("**").expect("`**` is a valid pattern"),
}],
deny: Vec::new(),
};
vec![ClientGroup {
name: "anonymous".to_owned(),
auth: vec![AuthItem::Anonymous],
rules: NamespaceRules {
local: read_all.clone(),
collections: BTreeMap::new(),
other: Some(read_all),
},
tls_accept_claim: false,
verify_trust: None,
allow_unsigned: true,
sign: Vec::new(),
allow_privileged: false,
disable_verify_bindings: false,
summary: true,
implicit: true,
}]
}
pub(super) fn index(groups: &[ClientGroup]) -> HashMap<AuthItem, Vec<usize>> {
let mut by_item: HashMap<AuthItem, Vec<usize>> = HashMap::new();
for (i, group) in groups.iter().enumerate() {
for item in &group.auth {
by_item.entry(item.clone()).or_default().push(i);
}
}
by_item
}
pub(super) fn summary_digests(
groups: &[ClientGroup],
by_item: &HashMap<AuthItem, Vec<usize>>,
own_id: Option<&str>,
) -> HashMap<AuthItem, SummaryFiles> {
let digests: Vec<Option<Checksum>> = groups
.iter()
.map(|group| {
group
.summary
.then(|| Checksum::sha256(access_text(own_id, group).as_bytes()))
})
.collect();
by_item
.iter()
.filter_map(|(item, carriers)| {
let digest = digests[*carriers.first()?]?;
let files = SummaryFiles {
digest,
stem: summary_stem(item),
};
Some((item.clone(), files))
})
.collect()
}
pub(super) fn access_text(own_id: Option<&str>, group: &ClientGroup) -> String {
fn joined(mut items: Vec<String>) -> String {
items.sort();
items.dedup();
items.join(";")
}
let rules = &group.rules;
let mut namespaces: Vec<(&str, &AccessRules)> = vec![("", &rules.local)];
namespaces.extend(rules.collections.iter().map(|(id, r)| (id.as_str(), r)));
namespaces.extend(rules.other.iter().map(|r| ("*", r)));
namespaces.sort_by_key(|&(namespace, _)| namespace);
let mut text = format!("collection-id={}\n", own_id.unwrap_or(""));
for (namespace, rules) in namespaces {
let allow = joined(rules.allow.iter().map(ToString::to_string).collect());
let deny = joined(
rules
.deny
.iter()
.map(|pattern| pattern.as_str().to_owned())
.collect(),
);
let summary = group.summary;
text.push_str(&format!(
"namespace={namespace}\nallow={allow}\ndeny={deny}\nsummary={summary}\n"
));
}
text
}
fn check_overlap(groups: &[ClientGroup], by_item: &HashMap<AuthItem, Vec<usize>>) -> Result<()> {
for (i, first) in groups.iter().enumerate() {
let found = first
.auth
.iter()
.filter_map(|item| {
let carriers = &by_item[item];
let later = &carriers[carriers.partition_point(|&j| j <= i)..];
later.first().map(|&j| (j, item))
})
.min_by_key(|&(j, _)| j);
if let Some((j, item)) = found {
return Err(Error::InvalidFormat(format!(
"{} and {} both carry the item {item}; one client group carries each item",
first.header(),
groups[j].header()
)));
}
}
Ok(())
}
fn parse_server(config: &RepoConfig, names: &Names<'_>) -> Result<ServerSettings> {
refuse_unknown_keys::<server::Group>(config.keyfile(), SERVER_GROUP)?;
let listen = config.get::<server::Listen>()?.map(|v| v.into_addrs());
let trusted_proxy = config.get::<server::TrustedProxy>()?.map(|v| v.into_nets());
let trusted_proxy_header = config.get::<server::TrustedProxyHeader>()?;
let trusted_proxy_client_cert = config
.get::<server::TrustedProxyClientCert>()?
.map(|v| v.into_string());
let tls_cert = config.get::<server::TlsCert>()?.map(server_file);
let tls_key = config.get::<server::TlsKey>()?.map(server_file);
let tls_client_ca = config.get::<server::TlsClientCa>()?.map(server_file);
let proxy_protocol = config.get::<server::ProxyProtocol>()?;
let allow_cleartext_credentials = config.get::<server::AllowCleartextCredentials>()?;
let session_timeout = config.get::<server::SessionTimeout>()?.map(|v| v.get());
let max_sessions = config.get::<server::MaxSessions>()?.map(|v| v.get());
let parallel_uploads = config.get::<server::ParallelUploads>()?.map(|v| v.get());
let body_timeout = config.get::<server::BodyTimeout>()?.map(|v| v.get());
let sign_summary = match config.get::<server::SignSummary>()? {
None => None,
Some(list) => {
let list = list.into_names();
let key = <server::SignSummary as Key<server::Group>>::NAME;
check_key_groups(SERVER_GROUP, key, &list, names)?;
Some(list)
}
};
Ok(ServerSettings {
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,
})
}
fn server_file(path: PemPath) -> ServerFile {
ServerFile::Config(PathBuf::from(path.into_string()))
}
pub(super) fn parent_component(group: &str, key: &str, value: &Path) -> Error {
Error::InvalidFormat(format!(
"[{group}] {key} {} has a `..` component, which a relative path in a config \
cannot have",
value.display()
))
}
#[cfg(test)]
mod tests {
use std::net::IpAddr;
use super::*;
use crate::access::{ForwardedHeader, IpNet, Namespace};
const CORE: &str = "[core]\nrepo_version=1\nmode=archive-z2\n";
const HEX: &str = "00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff";
fn try_access(text: &str) -> Result<ClientAccess> {
let config = RepoConfig::parse(&format!("{CORE}{text}"))?;
read(&config)
}
fn access(text: &str) -> ClientAccess {
try_access(text).unwrap()
}
fn client(keys: &str, extra: &str) -> Result<ClientGroup> {
let access = try_access(&format!("[ex-ostrya client \"c\"]\n{keys}{extra}"))?;
Ok(access.groups()[0].clone())
}
fn refused(result: Result<impl std::fmt::Debug>) -> String {
match result {
Err(Error::InvalidFormat(message)) => message,
other => panic!("{other:?}"),
}
}
fn server(keys: &str, extra: &str) -> Result<ServerSettings> {
Ok(try_access(&format!("[ex-ostrya server]\n{keys}{extra}"))?
.server()
.clone())
}
#[test]
fn the_group_shapes_are_told_apart() {
assert!(matches!(
classify("ex-ostrya server").unwrap(),
Some(Group::Server)
));
assert!(matches!(
classify("ex-ostrya client \"a b\"").unwrap(),
Some(Group::Client("a b"))
));
assert!(matches!(
classify("ex-ostrya client \"a:b\"").unwrap(),
Some(Group::Client("a:b"))
));
assert!(matches!(
classify("ex-ostrya trust \"t\"").unwrap(),
Some(Group::Trust("t"))
));
assert!(matches!(
classify("ex-ostrya key \"k\"").unwrap(),
Some(Group::Key("k"))
));
for group in ["ex-ostrya", "ex-ostryax", "core", "remote \"origin\""] {
assert!(classify(group).unwrap().is_none(), "{group}");
}
}
#[test]
fn the_other_reserved_names_are_refused() {
for group in [
"ex-ostrya servers",
"ex-ostrya server \"x\"",
"ex-ostrya client",
"ex-ostrya client c",
"ex-ostrya client \"\"",
"ex-ostrya client \"a\"b\"",
"ex-ostrya client \"a\tb\"",
"ex-ostrya client \"c\" ",
"ex-ostrya clients \"c\"",
"ex-ostrya trust \"\"",
"ex-ostrya key \"a\"\"",
"ex-ostrya receive \"\"",
"ex-ostrya bogus",
"ex-ostrya ",
] {
let Err(err) = classify(group) else {
panic!("{group:?} was accepted");
};
assert!(matches!(err, Error::InvalidFormat(_)), "{group:?}: {err}");
}
}
#[test]
fn the_receive_groups_are_refused() {
for group in [
"ex-ostrya receive",
"ex-ostrya receive \"a/**\"",
"ex-ostrya receive \"\"",
] {
let message = refused(try_access(&format!(
"[{group}]\naccept=true\n[ex-ostrya client \"c\"]\nauth=anonymous\n"
)));
assert!(message.starts_with(&format!("[{group}] ")), "{message}");
assert!(message.contains("[ex-ostrya client \"NAME\"]"), "{message}");
}
let message = refused(try_access("[ex-ostrya receivex]\n"));
assert!(!message.contains("receive policy"), "{message}");
}
#[test]
fn an_unknown_key_is_refused() {
let message = refused(client("auth=anonymous\nowner=x\n", ""));
assert!(message.contains("unknown key 'owner'"), "{message}");
let message = refused(server("accept=true\n", ""));
assert!(message.contains("unknown key 'accept'"), "{message}");
let message = refused(server("allow-privileged=true\n", ""));
assert!(message.contains("allow-privileged"), "{message}");
}
#[test]
fn trust_and_key_groups_are_recorded_by_name() {
let group = client(
"auth=anonymous\nverify=trust:t\nsign=k\n",
"[ex-ostrya trust \"t\"]\nany=thing\n[ex-ostrya key \"k\"]\nother=1\n",
)
.unwrap();
assert_eq!(group.verify_trust(), Some("t"));
assert_eq!(group.sign(), ["k"]);
}
#[test]
fn auth_is_necessary() {
for keys in ["", "auth=\n", "allow=r:**\n"] {
let message = refused(client(keys, ""));
assert!(message.contains("needs auth"), "{keys:?}: {message}");
}
for keys in ["auth=;\n", "auth=anonymous;;ssh:a\n"] {
let message = refused(client(keys, ""));
assert!(message.contains("auth item ''"), "{keys:?}: {message}");
}
}
#[test]
fn a_repeated_auth_item_counts_once() {
let group = client(
"auth=ssh:a;anonymous;ssh:a;net:2001:db8::/56;net:2001:0db8::/56\n",
"",
)
.unwrap();
let texts: Vec<String> = group.auth().iter().map(ToString::to_string).collect();
assert_eq!(texts, ["ssh:a", "anonymous", "net:2001:db8::/56"]);
}
#[test]
fn a_malformed_auth_item_names_the_group_and_the_key() {
for item in [
format!("token:{HEX}"),
format!("cert:{HEX}"),
" anonymous".to_owned(),
" ssh:b".to_owned(),
"ssh:b ".to_owned(),
"ssh: b".to_owned(),
"net:10.0.0.1/24".to_owned(),
"net:::ffff:10.0.0.0/104".to_owned(),
] {
let message = refused(client(&format!("auth=ssh:a;{item}\n"), ""));
assert!(
message.starts_with(&format!(
"malformed [ex-ostrya client \"c\"] auth item '{item}': "
)),
"{message}"
);
}
let message = refused(client(&format!("auth=basic-sha256:a:b:{HEX}\n"), ""));
assert!(message.contains("USER"), "{message}");
}
#[test]
fn white_space_after_an_auth_value_is_refused() {
for keys in [
"auth=ssh:user \n",
"auth= ssh:user\tx \n",
"auth=tls:n \n",
"auth=\\sssh:user\n",
"auth=ssh:\\suser\n",
&format!("auth=basic-sha256:ci :{HEX}\n"),
] {
let message = refused(client(keys, ""));
assert!(
message.starts_with("malformed [ex-ostrya client \"c\"] auth item '"),
"{keys:?}: {message}"
);
}
let group = client("auth= ssh:user\n", "").unwrap();
assert_eq!(group.auth(), [AuthItem::Ssh("user".into())]);
}
#[test]
fn the_collection_key_is_refused() {
for value in ["*", "a.b", "a.b;c.d", "", "fresh"] {
let message = refused(client(&format!("auth=anonymous\ncollection={value}\n"), ""));
assert!(
message.starts_with("[ex-ostrya client \"c\"] holds the removed key 'collection'"),
"{message}"
);
assert!(message.contains("@ID:PATTERN"), "{message}");
}
}
#[test]
fn an_item_with_an_id_joins_its_collection() {
let group = client(
"auth=anonymous\nallow=@a.b:os/**;wd:@a.b:os/x;r:main;t:@c.d:**\n\
deny=@a.b:os/secret;secret\n",
"",
)
.unwrap();
let texts = |rules: &AccessRules| -> (Vec<String>, Vec<String>) {
(
rules.allow.iter().map(ToString::to_string).collect(),
rules.deny.iter().map(|p| p.as_str().to_owned()).collect(),
)
};
let rules = group.rules();
assert_eq!(
texts(&rules.local),
(vec!["r:main".into()], vec!["secret".into()])
);
assert_eq!(
texts(&rules.collections["a.b"]),
(
vec!["r:os/**".into(), "wd:os/x".into()],
vec!["os/secret".into()]
)
);
assert_eq!(
texts(&rules.collections["c.d"]),
(vec!["t:**".into()], vec![])
);
assert_eq!(rules.collections.len(), 2);
let longest = format!("a.{}", "b".repeat(ostrya_core::MAX_COLLECTION_ID_LEN - 2));
let group = client(&format!("auth=anonymous\nallow=@{longest}:a\n"), "").unwrap();
assert!(group.rules().collections.contains_key(&longest));
}
#[test]
fn an_item_of_the_own_collection_id_is_local() {
let config = RepoConfig::parse(&format!(
"{CORE}collection-id=own.id\n\
[ex-ostrya client \"c\"]\nauth=anonymous\nallow=w:@own.id:a;r:b\n\
deny=@own.id:a/secret\n"
))
.unwrap();
let access = read(&config).unwrap();
let rules = access.groups()[0].rules();
assert!(rules.collections.is_empty());
let allow: Vec<String> = rules.local.allow.iter().map(ToString::to_string).collect();
assert_eq!(allow, ["w:a", "r:b"]);
assert_eq!(rules.local.deny[0].as_str(), "a/secret");
}
#[test]
fn allow_and_deny_read_their_items() {
let group = client(
"auth=anonymous\nallow=os/**;rw:os/stable;dtcwr:x\ndeny=os/secret/**;y\n",
"",
)
.unwrap();
let local = &group.rules().local;
let allow: Vec<String> = local.allow.iter().map(ToString::to_string).collect();
assert_eq!(allow, ["r:os/**", "rw:os/stable", "rwctd:x"]);
let deny: Vec<&str> = local.deny.iter().map(RefPattern::as_str).collect();
assert_eq!(deny, ["os/secret/**", "y"]);
for keys in ["auth=anonymous\n", "auth=anonymous\nallow=\ndeny=\n"] {
let group = client(keys, "").unwrap();
assert_eq!(group.rules(), &NamespaceRules::default(), "{keys:?}");
assert!(group.rules().rights(&Namespace::Local, "a").is_empty());
}
}
#[test]
fn a_malformed_allow_or_deny_item_is_refused() {
for (key, item) in [
("allow", "R:a"),
("allow", "rr:a"),
("allow", ":a"),
("allow", "r:"),
("allow", "r:origin:a"),
("allow", "r:a*"),
("deny", "!a"),
("deny", "a//b"),
("deny", "r:a"),
("allow", "@a.b:r:a"),
("allow", "r:@a.b"),
("allow", "@a.b:"),
("allow", "@:a"),
("allow", "@fresh:a"),
("allow", "r:@a..b:a"),
("allow", "@a.b:@c.d:a"),
("allow", "r:@a.b:@c.d:a"),
("deny", "@a.b"),
("deny", "@a.b:"),
("deny", "@1a.b:a"),
("deny", "!@a.b:a"),
("deny", "@a.b:!a"),
] {
let message = refused(client(&format!("auth=anonymous\n{key}={item}\n"), ""));
assert!(
message.starts_with(&format!(
"malformed [ex-ostrya client \"c\"] {key} item '{item}': "
)),
"{message}"
);
}
}
#[test]
fn tls_accept_claim_needs_a_tls_item() {
for item in ["tls:*", "tls:n", &format!("tls-sha256:{HEX}")] {
let group = client(&format!("auth={item}\ntls-accept-claim=true\n"), "").unwrap();
assert!(group.tls_accept_claim(), "{item}");
let group = client(&format!("auth={item}\n"), "").unwrap();
assert!(!group.tls_accept_claim(), "{item}");
}
for value in ["true", "false", "0", "maybe", ""] {
let message = refused(client(
&format!("auth=anonymous;ssh:a;token-sha256:{HEX}\ntls-accept-claim={value}\n"),
"",
));
assert!(message.contains("tls-accept-claim"), "{value}: {message}");
}
let err = client("auth=tls:*\ntls-accept-claim=yes\n", "").unwrap_err();
assert!(matches!(err, Error::Core(_)), "{err}");
}
#[test]
fn verify_takes_a_trust_group() {
let trust = "[ex-ostrya trust \"t\"]\n";
let group = client("auth=anonymous\nverify=trust:t\n", trust).unwrap();
assert_eq!(group.verify_trust(), Some("t"));
let message = refused(client("auth=anonymous\nverify=trust:u\n", trust));
assert!(
message.contains("names no [ex-ostrya trust \"u\"]"),
"{message}"
);
let message = refused(client("auth=anonymous\nverify=remote:origin\n", trust));
assert!(message.contains("removed"), "{message}");
for value in ["off", "trust:", "", "t", "Trust:t"] {
let message = refused(client(&format!("auth=anonymous\nverify={value}\n"), trust));
assert!(message.contains("malformed"), "{value:?}: {message}");
}
}
#[test]
fn allow_unsigned_has_two_defaults() {
let trust = "[ex-ostrya trust \"t\"]\n";
let cases = [
("", true),
("allow-unsigned=true\n", true),
("verify=trust:t\n", false),
("verify=trust:t\nallow-unsigned=true\n", true),
("verify=trust:t\nallow-unsigned=false\n", false),
];
for (keys, want) in cases {
let group = client(&format!("auth=anonymous\n{keys}"), trust).unwrap();
assert_eq!(group.allow_unsigned(), want, "{keys:?}");
}
for value in ["false", "0"] {
let message = refused(client(
&format!("auth=anonymous\nallow-unsigned={value}\n"),
trust,
));
assert!(message.contains("needs verify"), "{message}");
}
}
#[test]
fn sign_and_allow_privileged() {
let keys = "[ex-ostrya key \"a\"]\n[ex-ostrya key \"b\"]\n";
let group = client("auth=anonymous\nsign=b;a;b\nallow-privileged=1\n", keys).unwrap();
assert_eq!(group.sign(), ["b", "a"]);
assert!(group.allow_privileged());
let group = client("auth=anonymous\nsign=a;b;a;b;a\n", keys).unwrap();
assert_eq!(group.sign(), ["a", "b"]);
let group = client("auth=anonymous\n", keys).unwrap();
assert!(group.sign().is_empty());
assert!(!group.allow_privileged());
let message = refused(client("auth=anonymous\nsign=a;c\n", keys));
assert!(message.contains("'c'"), "{message}");
let message = refused(client("auth=anonymous\nsign=\n", keys));
assert!(message.contains("sign is empty"), "{message}");
let err = client("auth=anonymous\nallow-privileged=yes\n", "").unwrap_err();
assert!(matches!(err, Error::Core(_)), "{err}");
}
#[test]
fn disable_verify_bindings_is_a_boolean() {
let group = client("auth=anonymous\n", "").unwrap();
assert!(!group.disable_verify_bindings());
let group = client("auth=anonymous\ndisable-verify-bindings=true\n", "").unwrap();
assert!(group.disable_verify_bindings());
let group = client("auth=anonymous\ndisable-verify-bindings=false\n", "").unwrap();
assert!(!group.disable_verify_bindings());
let err = client("auth=anonymous\ndisable-verify-bindings=yes\n", "").unwrap_err();
assert!(matches!(err, Error::Core(_)), "{err}");
}
#[test]
fn summary_is_a_boolean_that_defaults_to_false() {
assert!(!client("auth=anonymous\n", "").unwrap().summary());
assert!(
client("auth=anonymous\nsummary=true\n", "")
.unwrap()
.summary()
);
assert!(
!client("auth=anonymous\nsummary=false\n", "")
.unwrap()
.summary()
);
let err = client("auth=anonymous\nsummary=yes\n", "").unwrap_err();
assert!(matches!(err, Error::Core(_)), "{err}");
assert!(access("").groups().iter().all(ClientGroup::summary));
}
#[test]
fn the_claims_refuse_a_summary() {
let message = refused(client(
"auth=tls:*\ntls-accept-claim=true\nsummary=true\n",
"",
));
assert!(message.contains("tls-accept-claim=true"), "{message}");
assert!(message.contains("summary=true"), "{message}");
assert!(
message.starts_with("[ex-ostrya client \"c\"] "),
"{message}"
);
for keys in [
"tls-accept-claim=true\nsummary=false\n",
"tls-accept-claim=false\nsummary=true\n",
"summary=true\n",
] {
client(&format!("auth=tls:*\n{keys}"), "").unwrap();
}
}
fn digest(text: &str, item: &str) -> Option<Checksum> {
access(text).summary_digest(&AuthItem::parse(item).unwrap())
}
#[test]
fn the_access_text_of_the_implicit_group() {
let groups = implicit_groups();
let text = "namespace=\nallow=r:**\ndeny=\nsummary=true\n\
namespace=*\nallow=r:**\ndeny=\nsummary=true\n";
assert_eq!(
access_text(None, &groups[0]),
format!("collection-id=\n{text}")
);
assert_eq!(
access_text(Some("a.b"), &groups[0]),
format!("collection-id=a.b\n{text}")
);
let want = Checksum::sha256(format!("collection-id=\n{text}").as_bytes());
assert_eq!(digest("", "anonymous"), Some(want));
assert_eq!(
ClientAccess::implicit(None).summary_digest(&AuthItem::Anonymous),
Some(want)
);
assert_eq!(
ClientAccess::implicit(None).summary_files(&AuthItem::Anonymous),
Some(&SummaryFiles {
digest: want,
stem: summary_stem(&AuthItem::Anonymous),
})
);
}
#[test]
fn the_access_text_is_sorted_and_has_each_item_one_time() {
let access = access(
"[ex-ostrya client \"b\"]\nauth=ssh:u\n\
allow=r:@c.d:b;rw:@c.d:a;@c.d:b;wr:@c.d:a;d:@a.b:z\ndeny=@c.d:y;@c.d:x;@c.d:y\n\
summary=true\n",
);
assert_eq!(
access_text(None, &access.groups()[0]),
"collection-id=\n\
namespace=\nallow=\ndeny=\nsummary=true\n\
namespace=a.b\nallow=d:z\ndeny=\nsummary=true\n\
namespace=c.d\nallow=r:b;rw:a\ndeny=x;y\nsummary=true\n"
);
}
#[test]
fn the_access_digest_follows_the_rules_of_the_summary() {
let config = |name: &str, rules: &str| {
format!(
"[ex-ostrya client \"{name}\"]\nauth=ssh:u;anonymous\n{rules}summary=true\n\
[ex-ostrya client \"ci\"]\nauth=ssh:ci\nallow=r:**\n"
)
};
let rules = "allow=r:a/**;r:@c.d:**\ndeny=a/secret\n";
let base = digest(&config("one", rules), "ssh:u").unwrap();
assert_eq!(digest(&config("two", rules), "ssh:u"), Some(base));
assert_eq!(digest(&config("one", rules), "anonymous"), Some(base));
for changed in [
config("one", "allow=r:a/**;r:b;r:@c.d:**\ndeny=a/secret\n"),
config("one", "allow=rw:a/**;r:@c.d:**\ndeny=a/secret\n"),
config("one", "allow=r:a/**;r:@c.d:**\ndeny=a/secret;a/hidden\n"),
config("one", "allow=r:a/**;r:@c.d:**\n"),
config("one", "allow=r:a/**;r:@c.d:**\ndeny=@c.d:a/secret\n"),
config("one", "allow=r:a/**;r:@e.f:**\ndeny=a/secret\n"),
config("one", "allow=r:@a.b:a/**;r:@c.d:**\ndeny=a/secret\n"),
] {
assert_ne!(digest(&changed, "ssh:u"), Some(base), "{changed}");
}
assert_eq!(digest(&config("one", rules), "ssh:ci"), None);
let with_id = RepoConfig::parse(&format!(
"{CORE}collection-id=own.id\n{}",
config("one", rules)
))
.unwrap();
let own = read(&with_id).unwrap();
assert_ne!(
own.summary_digest(&AuthItem::parse("ssh:u").unwrap()),
Some(base)
);
}
#[test]
fn the_summary_files_of_each_item() {
let config = RepoConfig::parse(&format!(
"{CORE}collection-id=own.id\n\
[ex-ostrya client \"a\"]\nauth=ssh:u;anonymous;tls:t\n\
allow=r:a/**;rw:@c.d:**;r:@own.id:b\ndeny=a/secret;@c.d:x\nsummary=true\n\
[ex-ostrya client \"b\"]\nauth=ssh:v;net:10.0.0.0/8\nallow=r:**\nsummary=true\n\
[ex-ostrya client \"c\"]\nauth=ssh:ci\nallow=r:**\n"
))
.unwrap();
let access = read(&config).unwrap();
let groups = access.groups();
let files = summary_digests(groups, &index(groups), Some("own.id"));
let got: BTreeMap<String, (String, String)> = files
.into_iter()
.map(|(item, files)| (item.to_string(), (files.digest.to_hex(), files.stem)))
.collect();
let a = "a35d1510ade4c75135840ebd7a814d00c2ec6d4b8d7f1e50cf6e3d6861e6a5c7";
let b = "832513f1fec8a25366be58392d28dafd2bfad0c4b235ec0f0fe864f22663c8a5";
let want: BTreeMap<String, (String, String)> = [
(
"anonymous",
a,
"2f183a4e64493af3f377f745eda502363cd3e7ef6e4d266d444758de0a85fcc8",
),
(
"net:10.0.0.0/8",
b,
"61136f23cc1b82800a49c84b4b6f044475ec4099fe8ce8f3a8bfd6ed17cdd0cc",
),
(
"ssh:u",
a,
"643181c1b251bde6c3e3a3ef768efa50148f9e5b0cd907ad24e27a7c882ce165",
),
(
"ssh:v",
b,
"bbbc0225ad766704cf99e1e2ca135fb27babe1d1a5195a9923501b4c91a2cc84",
),
(
"tls:t",
a,
"cb6e6086d39f5feb1012154102a7f17f1e77d75d3548b829c6608ccf903dc371",
),
]
.into_iter()
.map(|(item, digest, stem)| (item.to_owned(), (digest.to_owned(), stem.to_owned())))
.collect();
assert_eq!(got, want);
}
#[test]
fn an_item_of_the_own_collection_id_keeps_the_digest() {
let digest_of = |allow: &str| {
let config = RepoConfig::parse(&format!(
"{CORE}collection-id=own.id\n\
[ex-ostrya client \"c\"]\nauth=anonymous\nallow={allow}\nsummary=true\n"
))
.unwrap();
read(&config).unwrap().summary_digest(&AuthItem::Anonymous)
};
assert_eq!(digest_of("r:@own.id:a"), digest_of("r:a"));
assert_ne!(digest_of("r:@a.b:a"), digest_of("r:a"));
}
#[test]
fn the_server_keys_parse() {
let settings = server(
"listen=0.0.0.0:8443;[::1]:0\n\
tls-cert=certs/server.pem\n\
tls-key=/etc/ostrya/server.key\n\
tls-client-ca=~/ca.pem\n\
trusted-proxy=10.0.0.0/24;2001:db8::1\n\
trusted-proxy-header=forwarded\n\
trusted-proxy-client-cert=X-SSL-Client-Cert\n\
proxy-protocol=true\n\
allow-cleartext-credentials=0\n\
session-timeout=600\n\
max-sessions=1\n\
parallel-uploads=31\n\
body-timeout=30\n\
sign-summary=k;k\n",
"[ex-ostrya key \"k\"]\n",
)
.unwrap();
assert_eq!(
settings.listen,
Some(vec![
"0.0.0.0:8443".parse().unwrap(),
"[::1]:0".parse().unwrap()
])
);
assert_eq!(
settings.tls_cert,
Some(ServerFile::Config("certs/server.pem".into()))
);
assert_eq!(
settings.tls_key,
Some(ServerFile::Config("/etc/ostrya/server.key".into()))
);
assert_eq!(
settings.tls_client_ca,
Some(ServerFile::Config("~/ca.pem".into()))
);
let proxies = settings.trusted_proxy.as_ref().unwrap();
assert_eq!(proxies.len(), 2);
assert!(proxies[0].contains("10.0.0.7".parse::<IpAddr>().unwrap()));
assert_eq!(proxies[1], IpNet::parse("2001:db8::1/128").unwrap());
assert_eq!(
settings.trusted_proxy_header,
Some(ForwardedHeader::Forwarded)
);
assert_eq!(
settings.trusted_proxy_client_cert.as_deref(),
Some("X-SSL-Client-Cert")
);
assert_eq!(settings.proxy_protocol, Some(true));
assert_eq!(settings.allow_cleartext_credentials, Some(false));
assert_eq!(settings.session_timeout, Some(600));
assert_eq!(settings.max_sessions, Some(1));
assert_eq!(settings.parallel_uploads, Some(31));
assert_eq!(settings.body_timeout, Some(30));
assert_eq!(settings.sign_summary, Some(vec!["k".to_owned()]));
}
#[test]
fn an_absent_server_key_gives_none() {
assert_eq!(server("", "").unwrap(), ServerSettings::default());
assert_eq!(access("").server(), &ServerSettings::default());
}
#[test]
fn the_malformed_server_values_are_refused() {
for keys in [
"listen=\n",
"listen=localhost:8080\n",
"listen=127.0.0.1\n",
"listen=::1:80\n",
"listen=127.0.0.1:80; [::1]:80\n",
"tls-cert=\n",
"tls-key=\n",
"tls-client-ca=\n",
"trusted-proxy=\n",
"trusted-proxy=;\n",
"trusted-proxy=10.0.0.1/24\n",
"trusted-proxy=fe80::1%eth0\n",
"trusted-proxy=::ffff:10.0.0.0/104\n",
"trusted-proxy-client-cert=\n",
"trusted-proxy-client-cert=X Client\n",
"trusted-proxy-client-cert=X:Client\n",
"trusted-proxy-header=\n",
"trusted-proxy-header=X-Forwarded-For\n",
"trusted-proxy-header=x-forwarded-proto\n",
"trusted-proxy-header=forwarded;x-real-ip\n",
"session-timeout=0\n",
"session-timeout=-1\n",
"max-sessions=0\n",
"body-timeout=0\n",
"parallel-uploads=0\n",
"parallel-uploads=32\n",
"sign-summary=nokey\n",
"sign-summary=\n",
] {
refused(server(keys, "[ex-ostrya key \"k\"]\n"));
}
for key in ["listen", "trusted-proxy", "sign-summary"] {
let message = refused(server(&format!("{key}=\n"), ""));
assert!(message.contains(&format!("{key} is empty")), "{message}");
}
for key in ["tls-cert", "tls-key", "tls-client-ca"] {
for value in ["../c.pem", "certs/../c.pem", ".."] {
let message = refused(server(&format!("{key}={value}\n"), ""));
assert_eq!(
message,
format!(
"[ex-ostrya server] {key} {value} has a `..` component, which a \
relative path in a config cannot have"
)
);
}
let settings = server(&format!("{key}=/etc/../c.pem\n"), "").unwrap();
let file = match key {
"tls-cert" => settings.tls_cert,
"tls-key" => settings.tls_key,
_ => settings.tls_client_ca,
};
assert_eq!(file, Some(ServerFile::Config("/etc/../c.pem".into())));
}
for keys in [
"session-timeout=+5\n",
"max-sessions=1.5\n",
"parallel-uploads=0x4\n",
"proxy-protocol=yes\n",
"allow-cleartext-credentials=on\n",
] {
let err = server(keys, "").unwrap_err();
assert!(matches!(err, Error::Core(_)), "{keys:?}: {err}");
}
}
#[test]
fn the_server_refusals_keep_their_texts() {
let invalid: &[(&str, &str)] = &[
(
"listen=\n",
"[ex-ostrya server] listen is empty; remove the key for the default address",
),
(
"listen=localhost:8080\n",
"malformed [ex-ostrya server] listen item 'localhost:8080': the item is \
ADDR:PORT, an IP address and a port",
),
(
"listen=127.0.0.1:80;;[::1]:81;\n",
"malformed [ex-ostrya server] listen item '': the item is ADDR:PORT, an IP \
address and a port",
),
(
"listen=127.0.0.1:80; [::1]:80\n",
"malformed [ex-ostrya server] listen item ' [::1]:80': the item is \
ADDR:PORT, an IP address and a port",
),
(
"trusted-proxy=\n",
"[ex-ostrya server] trusted-proxy is empty; remove the key or name a network",
),
(
"trusted-proxy=;\n",
"malformed [ex-ostrya server] trusted-proxy item '': the form is ADDR/LEN \
or ADDR, with an IP address",
),
(
"trusted-proxy=10.0.0.1/24\n",
"malformed [ex-ostrya server] trusted-proxy item '10.0.0.1/24': the address \
has host bits set",
),
(
"trusted-proxy-header=X-Forwarded-For\n",
"malformed [ex-ostrya server] trusted-proxy-header value 'X-Forwarded-For': \
the value is forwarded, x-forwarded-for, or x-real-ip",
),
(
"trusted-proxy-header=\n",
"malformed [ex-ostrya server] trusted-proxy-header value '': the value is \
forwarded, x-forwarded-for, or x-real-ip",
),
(
"trusted-proxy-client-cert=X Client\n",
"malformed [ex-ostrya server] trusted-proxy-client-cert value 'X Client': \
the value is a header name, one or more letters, digits, and the \
characters !#$%&'*+-.^_`|~",
),
(
"trusted-proxy-client-cert=\n",
"malformed [ex-ostrya server] trusted-proxy-client-cert value '': the value \
is a header name, one or more letters, digits, and the characters \
!#$%&'*+-.^_`|~",
),
(
"tls-cert=\n",
"[ex-ostrya server] tls-cert is empty; remove the key or name a file",
),
(
"tls-key=\n",
"[ex-ostrya server] tls-key is empty; remove the key or name a file",
),
(
"tls-client-ca=\n",
"[ex-ostrya server] tls-client-ca is empty; remove the key or name a file",
),
(
"tls-cert=a/../b\n",
"[ex-ostrya server] tls-cert a/../b has a `..` component, which a relative \
path in a config cannot have",
),
(
"session-timeout=0\n",
"[ex-ostrya server] session-timeout is 0; the value is a positive integer",
),
(
"max-sessions=-1\n",
"[ex-ostrya server] max-sessions is -1; the value is a positive integer",
),
(
"body-timeout=-9223372036854775808\n",
"[ex-ostrya server] body-timeout is -9223372036854775808; the value is a \
positive integer",
),
(
"parallel-uploads=0\n",
"[ex-ostrya server] parallel-uploads is 0; the value is 1 to 31",
),
(
"parallel-uploads=32\n",
"[ex-ostrya server] parallel-uploads is 32; the value is 1 to 31",
),
(
"sign-summary=\n",
"[ex-ostrya server] sign-summary is empty; remove the key or name a key group",
),
(
"sign-summary=k;nokey\n",
"[ex-ostrya server] sign-summary names the key group 'nokey', and no \
[ex-ostrya key \"nokey\"] group exists",
),
(
"sign-summary=;\n",
"[ex-ostrya server] sign-summary names the key group '', and no \
[ex-ostrya key \"\"] group exists",
),
(
"accept=true\n",
"[ex-ostrya server] holds the unknown key 'accept'",
),
(
"listen=bad\nzzz=1\n",
"[ex-ostrya server] holds the unknown key 'zzz'",
),
(
"zzz=1\nlisten=bad\nyyy=2\n",
"[ex-ostrya server] holds the unknown key 'zzz'",
),
(
"tls-cert=\ntrusted-proxy=\n",
"[ex-ostrya server] trusted-proxy is empty; remove the key or name a network",
),
];
for (keys, message) in invalid {
assert_eq!(
refused(server(keys, "[ex-ostrya key \"k\"]\n")),
*message,
"{keys:?}"
);
}
let core: &[(&str, &str)] = &[
(
"proxy-protocol=yes\n",
"keyfile: value 'yes' for ex-ostrya server.proxy-protocol is not a boolean",
),
(
"allow-cleartext-credentials=on\n",
"keyfile: value 'on' for ex-ostrya server.allow-cleartext-credentials is not \
a boolean",
),
(
"session-timeout=+5\n",
"keyfile: value '+5' for ex-ostrya server.session-timeout is not an integer",
),
(
"max-sessions=9223372036854775808\n",
"keyfile: value '9223372036854775808' for ex-ostrya server.max-sessions is \
not an integer",
),
(
"parallel-uploads=4 \n",
"keyfile: value '4 ' for ex-ostrya server.parallel-uploads is not an \
integer",
),
("tls-cert=a\\q\n", "keyfile: invalid escape '\\q'"),
("listen=a\\\n", "keyfile: value ends with a lone backslash"),
("sign-summary=k\\q\n", "keyfile: invalid escape '\\q'"),
];
for (keys, message) in core {
let err = server(keys, "[ex-ostrya key \"k\"]\n").unwrap_err();
assert!(matches!(err, Error::Core(_)), "{keys:?}: {err}");
assert_eq!(err.to_string(), *message, "{keys:?}");
}
}
#[test]
fn a_repeated_server_key_and_white_space_read_as_before() {
let settings = server(
"max-sessions=1\nmax-sessions=2\nbody-timeout = 7\nparallel-uploads= 4\n\
session-timeout=9223372036854775807\nlisten=127.0.0.1:80;[::1]:81;\n",
"",
)
.unwrap();
assert_eq!(settings.max_sessions, Some(2));
assert_eq!(settings.body_timeout, Some(7));
assert_eq!(settings.parallel_uploads, Some(4));
assert_eq!(settings.session_timeout, Some(9_223_372_036_854_775_807));
assert_eq!(
settings.listen,
Some(vec![
"127.0.0.1:80".parse().unwrap(),
"[::1]:81".parse().unwrap()
])
);
}
#[test]
fn the_client_refusals_keep_their_texts() {
const G: &str = "[ex-ostrya client \"c\"]";
let forms = "the item is anonymous, tls:*, tls:NAME, tls-sha256:HEX, \
token-sha256:HEX, basic-sha256:USER:HEX, ssh:NAME, or net:CIDR";
let needs_auth = format!("{G} needs auth, a list of one or more items");
let tls_item = format!(
"{G} holds tls-accept-claim, and has no tls:*, tls:NAME, or tls-sha256:HEX item"
);
let invalid: Vec<(&str, String)> = vec![
(
"collection=x\n",
format!(
"{G} holds the removed key 'collection'; an allow item or a deny item \
names the refs of a collection as @ID:PATTERN"
),
),
(
"auth=anonymous\nzzz=1\n",
format!("{G} holds the unknown key 'zzz'"),
),
("", needs_auth.clone()),
("auth=\n", needs_auth.clone()),
(
"auth=bogus\n",
format!("malformed {G} auth item 'bogus': {forms}"),
),
("auth=;\n", format!("malformed {G} auth item '': {forms}")),
(
"auth=anonymous\nallow=R:a\n",
format!(
"malformed {G} allow item 'R:a': the modes are one or more of r, w, c, \
t, and d"
),
),
(
"auth=anonymous\nallow=rr:a\n",
format!("malformed {G} allow item 'rr:a': each mode occurs at most one time"),
),
(
"auth=anonymous\ndeny=@a.b\n",
format!(
"malformed {G} deny item '@a.b': a collection id is @ID: before the pattern"
),
),
(
"auth=anonymous\ndeny=@fresh:a\n",
format!(
"malformed {G} deny item '@fresh:a': the collection id fails the \
collection-id rule"
),
),
("auth=anonymous\ntls-accept-claim=true\n", tls_item.clone()),
(
"auth=tls:*\ntls-accept-claim=true\nsummary=true\n",
format!(
"{G} sets tls-accept-claim=true and summary=true; the claims of a client \
certificate cannot give the refs of a summary"
),
),
(
"auth=anonymous\nverify=trust:u\n",
format!("{G} verify=trust:u names no [ex-ostrya trust \"u\"] group"),
),
(
"auth=anonymous\nverify=remote:origin\n",
format!(
"malformed {G} verify value 'remote:origin': the remote:NAME form is \
removed; name a trust group with trust:NAME"
),
),
(
"auth=anonymous\nverify=off\n",
format!(
"malformed {G} verify value 'off': the value is trust:NAME; leave out \
the key for no verification"
),
),
(
"auth=anonymous\nverify=trust:\n",
format!(
"malformed {G} verify value 'trust:': the value is trust:NAME; leave out \
the key for no verification"
),
),
(
"auth=anonymous\nallow-unsigned=false\n",
format!("{G} sets allow-unsigned=false, which needs verify"),
),
(
"auth=anonymous\nsign=\n",
format!("{G} sign is empty; remove the key or name a key group"),
),
(
"auth=anonymous\nsign=k;c\n",
format!(
"{G} sign names the key group 'c', and no [ex-ostrya key \"c\"] group \
exists"
),
),
(
"auth=anonymous\nsign=;\n",
format!(
"{G} sign names the key group '', and no [ex-ostrya key \"\"] group exists"
),
),
(
"zzz=1\ncollection=x\n",
format!(
"{G} holds the removed key 'collection'; an allow item or a deny item \
names the refs of a collection as @ID:PATTERN"
),
),
(
"zzz=1\nauth=;\n",
format!("{G} holds the unknown key 'zzz'"),
),
(
"allow=R:a\nauth=bogus\n",
format!("malformed {G} auth item 'bogus': {forms}"),
),
(
"auth=anonymous\ndeny=@a.b\nallow=R:a\n",
format!(
"malformed {G} allow item 'R:a': the modes are one or more of r, w, c, \
t, and d"
),
),
("auth=anonymous\ntls-accept-claim=maybe\n", tls_item),
(
"auth=anonymous\nverify=off\nallow-unsigned=false\nsign=\n",
format!(
"malformed {G} verify value 'off': the value is trust:NAME; leave out \
the key for no verification"
),
),
(
"auth=anonymous\nsign=\nallow-unsigned=false\n",
format!("{G} sets allow-unsigned=false, which needs verify"),
),
];
for (keys, message) in &invalid {
assert_eq!(
refused(client(
keys,
"[ex-ostrya trust \"t\"]\n[ex-ostrya key \"k\"]\n"
)),
*message,
"{keys:?}"
);
}
assert_eq!(
refused(try_access(
"[ex-ostrya client \"a\"]\nauth=ssh:x;anonymous\n\
[ex-ostrya client \"b\"]\nauth=ssh:y;anonymous;ssh:x\n"
)),
"[ex-ostrya client \"a\"] and [ex-ostrya client \"b\"] both carry the item ssh:x; \
one client group carries each item"
);
let core: &[(&str, &str)] = &[
("auth=a\\q\n", "keyfile: invalid escape '\\q'"),
(
"auth=anonymous\nallow=a\\\n",
"keyfile: value ends with a lone backslash",
),
(
"auth=anonymous\ndeny=a\\q\n",
"keyfile: invalid escape '\\q'",
),
(
"auth=tls:*\ntls-accept-claim=yes\n",
"keyfile: value 'yes' for ex-ostrya client \"c\".tls-accept-claim is not a \
boolean",
),
(
"auth=anonymous\nsummary=yes\nverify=off\n",
"keyfile: value 'yes' for ex-ostrya client \"c\".summary is not a boolean",
),
(
"auth=anonymous\nverify=trust:\\q\n",
"keyfile: invalid escape '\\q'",
),
(
"auth=anonymous\nverify=trust:t\nallow-unsigned=maybe\nsign=\n",
"keyfile: value 'maybe' for ex-ostrya client \"c\".allow-unsigned is not a \
boolean",
),
(
"auth=anonymous\nsign=k\\q\n",
"keyfile: invalid escape '\\q'",
),
(
"auth=anonymous\nsign=k\nallow-privileged=yes\ndisable-verify-bindings=yes\n",
"keyfile: value 'yes' for ex-ostrya client \"c\".allow-privileged is not a \
boolean",
),
(
"auth=anonymous\ndisable-verify-bindings=on\n",
"keyfile: value 'on' for ex-ostrya client \"c\".disable-verify-bindings is \
not a boolean",
),
];
for (keys, message) in core {
let err = client(keys, "[ex-ostrya trust \"t\"]\n[ex-ostrya key \"k\"]\n").unwrap_err();
assert!(matches!(err, Error::Core(_)), "{keys:?}: {err}");
assert_eq!(err.to_string(), *message, "{keys:?}");
}
let message = refused(client("auth=anonymous\nsign=\nallow-privileged=yes\n", ""));
assert_eq!(
message,
format!("{G} sign is empty; remove the key or name a key group")
);
}
#[test]
fn a_repeated_client_key_and_white_space_read_as_before() {
let extra = "[ex-ostrya trust \"t\"]\n[ex-ostrya key \"a\"]\n";
let group = client(
"auth= ssh:a\nsummary=true\nsummary=false\nsign=a;a;\nallow-privileged = 1\n",
extra,
)
.unwrap();
assert_eq!(group.auth(), [AuthItem::Ssh("a".into())]);
assert!(!group.summary());
assert_eq!(group.sign(), ["a"]);
assert!(group.allow_privileged());
assert_eq!(
refused(client("auth=anonymous\nverify=trust:t \n", extra)),
"[ex-ostrya client \"c\"] verify=trust:t names no [ex-ostrya trust \"t \"] group"
);
let group = client("auth=anonymous\nallow=a;a\ndeny=b;b\n", extra).unwrap();
assert_eq!(group.rules().local.allow.len(), 2);
assert_eq!(group.rules().local.deny.len(), 2);
}
#[test]
fn a_reference_to_a_missing_group_is_refused() {
refused(client("auth=anonymous\nverify=trust:t\n", ""));
refused(client("auth=anonymous\nsign=k\n", ""));
refused(server("sign-summary=k\n", "[ex-ostrya trust \"k\"]\n"));
refused(client(
"auth=anonymous\nverify=trust:k\n",
"[ex-ostrya key \"k\"]\n",
));
}
}