mod claim;
mod item;
mod read;
mod reader;
mod rights;
use std::borrow::Cow;
use std::collections::HashMap;
use std::fmt;
use std::net::SocketAddr;
use std::path::{Path, PathBuf};
pub use claim::{Claim, ClaimError, ClaimRule, Claims, MAX_CLAIMS};
pub use item::{AuthItem, IpNet};
pub use read::ReadAccess;
pub(crate) use read::reads;
#[cfg(feature = "receive")]
pub(crate) use reader::{Group, classify};
pub use rights::{AccessModes, AccessRules, AllowItem};
use ostrya_core::Checksum;
use crate::config::RepoConfig;
use crate::error::{Error, Result};
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Namespace {
Local,
Collection(String),
}
impl Namespace {
pub(crate) fn of(collection: Option<&str>, own: Option<&str>) -> Namespace {
match collection {
Some(id) if Some(id) != own => Namespace::Collection(id.to_owned()),
_ => Namespace::Local,
}
}
#[cfg(feature = "receive")]
pub(crate) fn collection(&self) -> Option<&str> {
match self {
Namespace::Local => None,
Namespace::Collection(id) => Some(id),
}
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub enum CollectionScope {
#[default]
Local,
Ids(Vec<String>),
AllOther,
}
impl CollectionScope {
pub fn covers(&self, namespace: &Namespace) -> bool {
match (self, namespace) {
(CollectionScope::Local, Namespace::Local) => true,
(CollectionScope::Ids(ids), Namespace::Collection(id)) => ids.contains(id),
(CollectionScope::AllOther, Namespace::Collection(id)) => {
ostrya_core::is_collection_id(id)
}
_ => false,
}
}
fn overlaps(&self, other: &CollectionScope) -> bool {
match (self, other) {
(CollectionScope::Local, CollectionScope::Local)
| (CollectionScope::AllOther, CollectionScope::AllOther) => true,
(CollectionScope::Ids(a), CollectionScope::Ids(b)) => a.iter().any(|id| b.contains(id)),
_ => false,
}
}
}
#[derive(Debug, Clone)]
pub struct ClientGroup {
name: String,
auth: Vec<AuthItem>,
scope: CollectionScope,
rules: AccessRules,
tls_accept_claim: bool,
verify_trust: Option<String>,
allow_unsigned: bool,
sign: Vec<String>,
allow_privileged: bool,
summary: bool,
implicit: bool,
}
impl ClientGroup {
pub fn name(&self) -> &str {
&self.name
}
pub fn auth(&self) -> &[AuthItem] {
&self.auth
}
pub fn scope(&self) -> &CollectionScope {
&self.scope
}
pub fn rules(&self) -> &AccessRules {
&self.rules
}
pub fn tls_accept_claim(&self) -> bool {
self.tls_accept_claim
}
pub fn verify_trust(&self) -> Option<&str> {
self.verify_trust.as_deref()
}
pub fn allow_unsigned(&self) -> bool {
self.allow_unsigned
}
pub fn sign(&self) -> &[String] {
&self.sign
}
pub fn allow_privileged(&self) -> bool {
self.allow_privileged
}
pub fn summary(&self) -> bool {
self.summary
}
pub fn is_implicit(&self) -> bool {
self.implicit
}
pub fn covers(&self, namespace: &Namespace) -> bool {
self.scope.covers(namespace)
}
fn header(&self) -> String {
format!("[ex-ostrya client \"{}\"]", self.name)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ForwardedHeader {
Forwarded,
XForwardedFor,
XRealIp,
}
impl ForwardedHeader {
pub fn parse(text: &str) -> Result<ForwardedHeader> {
match text {
"forwarded" => Ok(ForwardedHeader::Forwarded),
"x-forwarded-for" => Ok(ForwardedHeader::XForwardedFor),
"x-real-ip" => Ok(ForwardedHeader::XRealIp),
_ => Err(Error::InvalidFormat(format!(
"malformed trusted-proxy-header value '{text}': the value is forwarded, \
x-forwarded-for, or x-real-ip"
))),
}
}
pub fn as_str(self) -> &'static str {
match self {
ForwardedHeader::Forwarded => "forwarded",
ForwardedHeader::XForwardedFor => "x-forwarded-for",
ForwardedHeader::XRealIp => "x-real-ip",
}
}
}
impl fmt::Display for ForwardedHeader {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
pub fn is_header_name(name: &str) -> bool {
!name.is_empty()
&& name
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&b))
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ServerSettings {
pub listen: Option<Vec<SocketAddr>>,
pub tls_cert: Option<PathBuf>,
pub tls_key: Option<PathBuf>,
pub tls_client_ca: Option<PathBuf>,
pub trusted_proxy: Option<Vec<IpNet>>,
pub trusted_proxy_header: Option<ForwardedHeader>,
pub trusted_proxy_client_cert: Option<String>,
pub proxy_protocol: Option<bool>,
pub allow_cleartext_credentials: Option<bool>,
pub session_timeout: Option<u64>,
pub max_sessions: Option<u64>,
pub parallel_uploads: Option<u32>,
pub body_timeout: Option<u64>,
pub sign_summary: Option<Vec<String>>,
}
impl ServerSettings {
pub fn overridden_by(&self, flags: &ServerSettings) -> ServerSettings {
fn pick<T: Clone>(flag: &Option<T>, key: &Option<T>) -> Option<T> {
flag.as_ref().or(key.as_ref()).cloned()
}
let 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,
} = flags;
let mut merged = ServerSettings {
listen: pick(listen, &self.listen),
tls_cert: pick(tls_cert, &self.tls_cert),
tls_key: pick(tls_key, &self.tls_key),
tls_client_ca: pick(tls_client_ca, &self.tls_client_ca),
trusted_proxy: pick(trusted_proxy, &self.trusted_proxy),
trusted_proxy_header: pick(trusted_proxy_header, &self.trusted_proxy_header),
trusted_proxy_client_cert: pick(
trusted_proxy_client_cert,
&self.trusted_proxy_client_cert,
),
proxy_protocol: pick(proxy_protocol, &self.proxy_protocol),
allow_cleartext_credentials: pick(
allow_cleartext_credentials,
&self.allow_cleartext_credentials,
),
session_timeout: pick(session_timeout, &self.session_timeout),
max_sessions: pick(max_sessions, &self.max_sessions),
parallel_uploads: pick(parallel_uploads, &self.parallel_uploads),
body_timeout: pick(body_timeout, &self.body_timeout),
sign_summary: pick(sign_summary, &self.sign_summary),
};
if tls_client_ca.is_none()
&& merged.tls_cert.is_none()
&& merged.trusted_proxy_client_cert.is_none()
{
merged.tls_client_ca = None;
}
merged
}
}
#[derive(Debug, Clone)]
pub struct ClientAccess {
collection_id: Option<String>,
server: ServerSettings,
groups: Vec<ClientGroup>,
by_item: HashMap<AuthItem, Vec<usize>>,
summaries: HashMap<AuthItem, SummaryFiles>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct SummaryFiles {
pub(crate) digest: Checksum,
pub(crate) stem: String,
}
impl ClientAccess {
pub fn from_config(config: &RepoConfig, repo_dir: &Path) -> Result<ClientAccess> {
reader::read(config, repo_dir)
}
pub fn implicit(collection_id: Option<&str>) -> ClientAccess {
let groups = reader::implicit_groups();
let by_item = reader::index(&groups);
let summaries = reader::summary_digests(&groups, &by_item, collection_id);
ClientAccess {
collection_id: collection_id.map(str::to_owned),
server: ServerSettings::default(),
groups,
by_item,
summaries,
}
}
pub fn server(&self) -> &ServerSettings {
&self.server
}
pub fn groups(&self) -> &[ClientGroup] {
&self.groups
}
pub fn groups_of<'a>(&'a self, item: &'a AuthItem) -> impl Iterator<Item = &'a ClientGroup> {
self.carriers(item).iter().map(|&i| &self.groups[i])
}
fn carriers(&self, item: &AuthItem) -> &[usize] {
self.by_item.get(item).map_or(&[], Vec::as_slice)
}
pub fn summary_digest(&self, item: &AuthItem) -> Option<Checksum> {
self.summaries.get(item).map(|files| files.digest)
}
pub(crate) fn summary_files(&self, item: &AuthItem) -> Option<&SummaryFiles> {
self.summaries.get(item)
}
pub fn namespace(&self, collection: Option<&str>) -> Namespace {
Namespace::of(collection, self.collection_id.as_deref())
}
pub fn select(&self, item: &AuthItem, namespace: &Namespace) -> Option<&ClientGroup> {
self.select_index(item, namespace).map(|i| &self.groups[i])
}
pub(crate) fn select_index(&self, item: &AuthItem, namespace: &Namespace) -> Option<usize> {
let mut carriers = self.carriers(item).iter().copied();
let scope = |i: usize| &self.groups[i].scope;
match namespace {
Namespace::Local => carriers.find(|&i| *scope(i) == CollectionScope::Local),
Namespace::Collection(id) => {
if !ostrya_core::is_collection_id(id)
|| Some(id.as_str()) == self.collection_id.as_deref()
{
return None;
}
carriers
.clone()
.find(|&i| matches!(scope(i), CollectionScope::Ids(ids) if ids.contains(id)))
.or_else(|| carriers.find(|&i| *scope(i) == CollectionScope::AllOther))
}
}
}
pub fn claim_rules(&self, claims: &Claims, namespace: &Namespace) -> Option<AccessRules> {
let namespace = match namespace {
Namespace::Collection(id) if Some(id.as_str()) == self.collection_id.as_deref() => {
&Namespace::Local
}
other => other,
};
let mut rules = AccessRules::default();
let mut found = false;
for claim in claims.as_slice() {
let names = match (&claim.namespace, namespace) {
(Namespace::Local, Namespace::Local) => true,
(Namespace::Collection(id), Namespace::Local) => {
Some(id.as_str()) == self.collection_id.as_deref()
}
(Namespace::Collection(id), Namespace::Collection(wanted)) => id == wanted,
(Namespace::Local, Namespace::Collection(_)) => false,
};
if !names {
continue;
}
found = true;
match &claim.rule {
ClaimRule::Allow(item) => rules.allow.push(item.clone()),
ClaimRule::Deny(pattern) => rules.deny.push(pattern.clone()),
}
}
found.then_some(rules)
}
pub fn effective_rules<'g>(
&self,
group: &'g ClientGroup,
namespace: &Namespace,
claims: Option<&Claims>,
) -> Cow<'g, AccessRules> {
match claims {
Some(claims) if group.tls_accept_claim => match self.claim_rules(claims, namespace) {
Some(rules) => Cow::Owned(rules),
None => Cow::Borrowed(&group.rules),
},
_ => Cow::Borrowed(&group.rules),
}
}
pub fn has_client_groups(&self) -> bool {
!self.groups.iter().all(ClientGroup::is_implicit)
}
fn is_own_collection(&self, id: &str) -> bool {
Some(id) == self.collection_id.as_deref()
}
pub fn items(&self) -> impl Iterator<Item = &AuthItem> {
self.groups.iter().enumerate().flat_map(move |(i, group)| {
group
.auth
.iter()
.filter(move |item| self.carriers(item).first() == Some(&i))
})
}
pub fn check_server(&self, merged: &ServerSettings) -> Result<()> {
if merged.tls_client_ca.is_none() && merged.trusted_proxy_client_cert.is_some() {
return Err(Error::InvalidFormat(
"trusted-proxy-client-cert is set, and the server has no tls-client-ca".to_owned(),
));
}
if merged.trusted_proxy_client_cert.is_some() && merged.trusted_proxy.is_none() {
return Err(Error::InvalidFormat(
"trusted-proxy-client-cert is set, and the server has no trusted-proxy".to_owned(),
));
}
match (&merged.trusted_proxy, &merged.trusted_proxy_header) {
(Some(_), None) => {
return Err(Error::InvalidFormat(
"trusted-proxy is set, and the server has no trusted-proxy-header".to_owned(),
));
}
(None, Some(_)) => {
return Err(Error::InvalidFormat(
"trusted-proxy-header is set, and the server has no trusted-proxy".to_owned(),
));
}
_ => {}
}
match (&merged.tls_cert, &merged.tls_key) {
(Some(_), None) => {
return Err(Error::InvalidFormat(
"tls-cert is set, and tls-key is not".to_owned(),
));
}
(None, Some(_)) => {
return Err(Error::InvalidFormat(
"tls-key is set, and tls-cert is not".to_owned(),
));
}
_ => {}
}
if merged.tls_client_ca.is_some()
&& merged.tls_cert.is_none()
&& merged.trusted_proxy_client_cert.is_none()
{
return Err(Error::InvalidFormat(
"tls-client-ca is set, and tls-cert and trusted-proxy-client-cert are not"
.to_owned(),
));
}
Ok(())
}
}
const _: fn() = || {
fn assert_send_sync<T: Send + Sync>() {}
assert_send_sync::<ClientAccess>();
assert_send_sync::<ClientGroup>();
assert_send_sync::<ServerSettings>();
assert_send_sync::<Namespace>();
assert_send_sync::<CollectionScope>();
assert_send_sync::<AuthItem>();
assert_send_sync::<IpNet>();
assert_send_sync::<ForwardedHeader>();
assert_send_sync::<AccessModes>();
assert_send_sync::<AllowItem>();
assert_send_sync::<AccessRules>();
assert_send_sync::<Claims>();
assert_send_sync::<Claim>();
assert_send_sync::<ClaimRule>();
assert_send_sync::<ClaimError>();
assert_send_sync::<ReadAccess>();
};
#[cfg(test)]
mod tests {
use super::*;
const CORE: &str = "[core]\nrepo_version=1\nmode=archive-z2\n";
fn access(text: &str) -> ClientAccess {
try_access(text).unwrap()
}
fn try_access(text: &str) -> Result<ClientAccess> {
let config = RepoConfig::parse(&format!("{CORE}{text}"))?;
ClientAccess::from_config(&config, Path::new("/srv/repo"))
}
fn item(text: &str) -> AuthItem {
AuthItem::parse(text).unwrap()
}
fn collection(id: &str) -> Namespace {
Namespace::Collection(id.to_owned())
}
fn selected<'a>(access: &'a ClientAccess, item_text: &str, ns: &Namespace) -> Option<&'a str> {
access.select(&item(item_text), ns).map(ClientGroup::name)
}
#[test]
fn the_example_config_selects_its_groups() {
let access = access(
r#"
[ex-ostrya server]
listen=0.0.0.0:8443
tls-cert=/etc/ostrya/server.pem
tls-key=/etc/ostrya/server.key
tls-client-ca=/etc/ostrya/clients-ca.pem
trusted-proxy=10.0.0.0/24
trusted-proxy-header=x-forwarded-for
[ex-ostrya client "public"]
auth=anonymous
allow=r:**
[ex-ostrya client "public-collections"]
auth=anonymous
collection=*
allow=r:**
[ex-ostrya client "developer"]
auth=ssh:user
allow=cd:devel/user/**
[ex-ostrya client "developer-release"]
auth=ssh:user
collection=com.company.client
allow=c:role/client/main/head;t:role/client/release/**
sign=release-key
[ex-ostrya client "mirror"]
auth=tls:mirror.example.com
collection=com.company.os
allow=w:os/stable;w:os/beta;t:os/release/**
verify=trust:release
[ex-ostrya client "farm"]
auth=net:10.0.1.0/24;net:2001:db8::/56
allow=r:devel/**
[ex-ostrya client "ci-cert"]
auth=tls:*
tls-accept-claim=true
allow=r:release/**
[ex-ostrya trust "release"]
sign-verify=ed25519
verification-ed25519-file=/etc/ostrya/release.ed25519
[ex-ostrya key "release-key"]
type=ed25519
secret-key-file=/etc/ostrya/release.secret
"#,
);
access.check_server(access.server()).unwrap();
assert_eq!(access.groups().len(), 7);
assert!(access.groups().iter().all(|g| !g.is_implicit()));
let os = collection("com.company.os");
let client = collection("com.company.client");
let other = collection("org.example.other");
let local = Namespace::Local;
assert_eq!(selected(&access, "anonymous", &local), Some("public"));
assert_eq!(
selected(&access, "anonymous", &os),
Some("public-collections")
);
assert_eq!(selected(&access, "ssh:user", &local), Some("developer"));
assert_eq!(
selected(&access, "ssh:user", &client),
Some("developer-release")
);
assert_eq!(selected(&access, "ssh:user", &other), None);
assert_eq!(
selected(&access, "tls:mirror.example.com", &os),
Some("mirror")
);
assert_eq!(selected(&access, "tls:mirror.example.com", &local), None);
assert_eq!(selected(&access, "tls:*", &local), Some("ci-cert"));
assert_eq!(selected(&access, "tls:*", &os), None);
assert_eq!(selected(&access, "net:10.0.1.0/24", &local), Some("farm"));
assert_eq!(
selected(&access, "net:2001:0db8::/56", &local),
Some("farm")
);
let mirror = access.select(&item("tls:mirror.example.com"), &os).unwrap();
assert_eq!(mirror.verify_trust(), Some("release"));
assert!(!mirror.allow_unsigned());
assert!(mirror.rules().opens_push_session());
assert_eq!(
mirror.rules().rights("os/stable"),
AccessModes::parse("rw").unwrap()
);
let release = access.select(&item("ssh:user"), &client).unwrap();
assert_eq!(release.sign(), ["release-key"]);
assert!(release.allow_unsigned());
let ci = access.select(&item("tls:*"), &local).unwrap();
assert!(ci.tls_accept_claim());
assert!(!ci.rules().opens_push_session());
assert_eq!(
access.server().trusted_proxy,
Some(vec![IpNet::parse("10.0.0.0/24").unwrap()])
);
assert_eq!(
access.server().trusted_proxy_header,
Some(ForwardedHeader::XForwardedFor)
);
}
#[test]
fn a_config_with_no_client_group_has_the_implicit_groups() {
for text in [
"",
"[ex-ostrya server]\nlisten=127.0.0.1:0\n",
"[ex-ostrya key \"k\"]\ntype=ed25519\n",
] {
let access = access(text);
let groups = access.groups();
assert_eq!(groups.len(), 2, "{text:?}");
assert_eq!(groups[0].name(), "anonymous");
assert_eq!(groups[0].scope(), &CollectionScope::Local);
assert_eq!(groups[1].name(), "anonymous-collections");
assert_eq!(groups[1].scope(), &CollectionScope::AllOther);
for group in groups {
assert!(group.is_implicit());
assert_eq!(group.auth(), [AuthItem::Anonymous]);
assert_eq!(group.rules().allow.len(), 1);
assert_eq!(group.rules().allow[0].to_string(), "r:**");
assert!(group.rules().deny.is_empty());
assert!(group.allow_unsigned());
assert!(!group.rules().opens_push_session());
}
assert_eq!(
selected(&access, "anonymous", &Namespace::Local),
Some("anonymous")
);
assert_eq!(
selected(&access, "anonymous", &collection("a.b")),
Some("anonymous-collections")
);
}
}
#[test]
fn the_implicit_access_has_the_groups_of_a_config_with_no_client_group() {
let from_config = access("");
for id in [None, Some("a.b"), Some("a\\b"), Some(" a.b")] {
let implicit = ClientAccess::implicit(id);
assert_eq!(
format!("{:?}", implicit.groups()),
format!("{:?}", from_config.groups()),
"{id:?}"
);
assert_eq!(implicit.server(), from_config.server(), "{id:?}");
assert!(!implicit.has_client_groups(), "{id:?}");
if let Some(id) = id {
assert_eq!(implicit.namespace(Some(id)), Namespace::Local, "{id:?}");
}
}
assert_eq!(
ClientAccess::implicit(None).namespace(Some("a.b")),
collection("a.b")
);
}
#[test]
fn one_client_group_removes_the_implicit_groups() {
let access = access("[ex-ostrya client \"c\"]\nauth=ssh:c\n");
assert_eq!(access.groups().len(), 1);
assert!(!access.groups()[0].is_implicit());
assert_eq!(selected(&access, "anonymous", &Namespace::Local), None);
}
#[test]
fn an_exact_collection_wins_over_the_wildcard() {
let access = access(
"[ex-ostrya client \"exact\"]\nauth=ssh:u\ncollection=a.b;c.d\n\
[ex-ostrya client \"any\"]\nauth=ssh:u\ncollection=*\n\
[ex-ostrya client \"local\"]\nauth=ssh:u\n",
);
assert_eq!(
selected(&access, "ssh:u", &collection("a.b")),
Some("exact")
);
assert_eq!(
selected(&access, "ssh:u", &collection("c.d")),
Some("exact")
);
assert_eq!(selected(&access, "ssh:u", &collection("e.f")), Some("any"));
assert_eq!(selected(&access, "ssh:u", &Namespace::Local), Some("local"));
assert_eq!(selected(&access, "ssh:v", &Namespace::Local), None);
}
#[test]
fn the_selection_never_falls_back_to_another_item() {
let access = access(
"[ex-ostrya client \"name\"]\nauth=tls:n\ncollection=a.b\n\
[ex-ostrya client \"any\"]\nauth=tls:*\n\
[ex-ostrya client \"anon\"]\nauth=anonymous\ncollection=*\n",
);
assert_eq!(selected(&access, "tls:n", &Namespace::Local), None);
assert_eq!(selected(&access, "tls:n", &collection("c.d")), None);
assert_eq!(selected(&access, "tls:*", &collection("a.b")), None);
assert_eq!(selected(&access, "tls:n", &collection("a.b")), Some("name"));
}
#[test]
fn the_own_id_and_an_invalid_id_select_no_collection_group() {
let config = RepoConfig::parse(
"[core]\nrepo_version=1\nmode=archive-z2\ncollection-id=own.id\n\
[ex-ostrya client \"any\"]\nauth=anonymous\ncollection=*\n\
[ex-ostrya client \"local\"]\nauth=anonymous\n",
)
.unwrap();
let access = ClientAccess::from_config(&config, Path::new("/r")).unwrap();
assert_eq!(access.namespace(Some("own.id")), Namespace::Local);
assert_eq!(access.namespace(None), Namespace::Local);
assert_eq!(access.namespace(Some("a.b")), collection("a.b"));
assert_eq!(access.namespace(Some("bad")), collection("bad"));
assert_eq!(selected(&access, "anonymous", &collection("own.id")), None);
assert_eq!(selected(&access, "anonymous", &collection("bad")), None);
assert_eq!(selected(&access, "anonymous", &collection("a..b")), None);
assert_eq!(
selected(&access, "anonymous", &collection("a.b")),
Some("any")
);
let ns = access.namespace(Some("own.id"));
assert_eq!(selected(&access, "anonymous", &ns), Some("local"));
let any = &access.groups()[0];
assert!(any.covers(&collection("a.b")));
assert!(!any.covers(&collection("bad")));
assert!(!any.covers(&Namespace::Local));
}
#[test]
fn with_no_own_id_each_id_maps_to_its_collection() {
let access = access("");
assert_eq!(access.namespace(Some("a.b")), collection("a.b"));
assert_eq!(access.namespace(None), Namespace::Local);
}
#[test]
fn the_claim_rules_hold_the_claims_of_one_namespace() {
let config = RepoConfig::parse(&format!("{CORE}collection-id=own.id\n")).unwrap();
let access = ClientAccess::from_config(&config, Path::new("/r")).unwrap();
let claims = Claims::parse([
"ostrya:ref:w:main",
"ostrya:collection:a.b:t:os/**",
"ostrya:ref:!secret/**",
"ostrya:collection:own.id:d:devel/**",
"ostrya:collection:a.b:!os/secret",
])
.unwrap();
let local = access.claim_rules(&claims, &Namespace::Local).unwrap();
let allow: Vec<String> = local.allow.iter().map(AllowItem::to_string).collect();
assert_eq!(allow, ["w:main", "d:devel/**"]);
assert_eq!(local.deny.len(), 1);
assert_eq!(local.deny[0].as_str(), "secret/**");
assert_eq!(local.rights("main"), AccessModes::parse("rw").unwrap());
assert_eq!(local.rights("secret/a"), AccessModes::NONE);
let ab = access.claim_rules(&claims, &collection("a.b")).unwrap();
let allow: Vec<String> = ab.allow.iter().map(AllowItem::to_string).collect();
assert_eq!(allow, ["t:os/**"]);
assert_eq!(ab.rights("os/secret"), AccessModes::NONE);
assert!(access.claim_rules(&claims, &collection("c.d")).is_none());
assert!(
access
.claim_rules(&Claims::default(), &Namespace::Local)
.is_none()
);
let collections_only = Claims::parse(["ostrya:collection:a.b:w:main"]).unwrap();
assert!(
access
.claim_rules(&collections_only, &Namespace::Local)
.is_none()
);
let deny_only = Claims::parse(["ostrya:ref:!secret/**"]).unwrap();
let rules = access.claim_rules(&deny_only, &Namespace::Local).unwrap();
assert!(rules.allow.is_empty());
assert_eq!(rules.rights("main"), AccessModes::NONE);
let no_own_id = self::access("");
let own = Claims::parse(["ostrya:collection:own.id:w:main"]).unwrap();
assert!(no_own_id.claim_rules(&own, &Namespace::Local).is_none());
assert!(no_own_id.claim_rules(&own, &collection("own.id")).is_some());
}
#[test]
fn the_own_collection_id_gives_the_claim_rules_of_the_local_refs() {
let config = RepoConfig::parse(&format!("{CORE}collection-id=own.id\n")).unwrap();
let access = ClientAccess::from_config(&config, Path::new("/r")).unwrap();
let claims = Claims::parse([
"ostrya:ref:w:main",
"ostrya:collection:own.id:d:devel/**",
"ostrya:collection:a.b:t:os/**",
"ostrya:ref:!secret/**",
])
.unwrap();
let own = access.claim_rules(&claims, &collection("own.id")).unwrap();
let allow: Vec<String> = own.allow.iter().map(AllowItem::to_string).collect();
assert_eq!(allow, ["w:main", "d:devel/**"]);
assert_eq!(own.deny.len(), 1);
assert_eq!(Some(own), access.claim_rules(&claims, &Namespace::Local));
let refs_only = Claims::parse(["ostrya:ref:w:main"]).unwrap();
assert!(
access
.claim_rules(&refs_only, &collection("own.id"))
.is_some()
);
}
#[test]
fn groups_of_gives_each_group_of_an_item() {
let access = access(
"[ex-ostrya client \"a\"]\nauth=ssh:u;anonymous\n\
[ex-ostrya client \"b\"]\nauth=ssh:v\n\
[ex-ostrya client \"c\"]\nauth=ssh:u\ncollection=*\n",
);
let ssh = item("ssh:u");
let names: Vec<&str> = access.groups_of(&ssh).map(ClientGroup::name).collect();
assert_eq!(names, ["a", "c"]);
assert_eq!(access.groups_of(&item("ssh:w")).count(), 0);
}
#[test]
fn items_gives_each_item_one_time() {
let access = access(
"[ex-ostrya client \"a\"]\nauth=ssh:u;anonymous\n\
[ex-ostrya client \"b\"]\nauth=net:2001:0db8::/56;ssh:v\n\
[ex-ostrya client \"c\"]\nauth=ssh:u;net:2001:db8::/56;tls:*\ncollection=*\n",
);
let items: Vec<String> = access.items().map(AuthItem::to_string).collect();
assert_eq!(
items,
["ssh:u", "anonymous", "net:2001:db8::/56", "ssh:v", "tls:*"]
);
let implicit = self::access("");
let items: Vec<&AuthItem> = implicit.items().collect();
assert_eq!(items, [&AuthItem::Anonymous]);
}
#[test]
fn an_item_in_two_overlapping_groups_is_refused() {
for (a, b) in [
("", ""),
("collection=a.b\n", "collection=c.d;a.b\n"),
("collection=*\n", "collection=*\n"),
] {
let text = format!(
"[ex-ostrya client \"one\"]\nauth=ssh:u\n{a}\
[ex-ostrya client \"two\"]\nauth=anonymous;ssh:u\n{b}"
);
let Err(Error::InvalidFormat(message)) = try_access(&text) else {
panic!("{a:?} {b:?} was accepted");
};
assert!(message.contains("ssh:u"), "{message}");
assert!(message.contains("\"one\""), "{message}");
assert!(message.contains("\"two\""), "{message}");
}
let text = "[ex-ostrya client \"one\"]\nauth=net:2001:db8::/56\n\
[ex-ostrya client \"two\"]\nauth=net:2001:0db8::/56\n";
assert!(try_access(text).is_err());
}
#[test]
fn an_item_in_two_disjoint_groups_is_accepted() {
for (a, b) in [
("", "collection=*\n"),
("", "collection=a.b\n"),
("collection=a.b\n", "collection=c.d\n"),
("collection=a.b\n", "collection=*\n"),
] {
let text = format!(
"[ex-ostrya client \"one\"]\nauth=ssh:u\n{a}\
[ex-ostrya client \"two\"]\nauth=ssh:u\n{b}"
);
try_access(&text).unwrap();
}
}
fn settings() -> ServerSettings {
ServerSettings {
tls_cert: Some("/c.pem".into()),
tls_key: Some("/k.pem".into()),
tls_client_ca: Some("/ca.pem".into()),
..ServerSettings::default()
}
}
fn check(access: &ClientAccess, merged: &ServerSettings) -> String {
match access.check_server(merged) {
Err(Error::InvalidFormat(message)) => message,
other => panic!("{merged:?}: {other:?}"),
}
}
#[test]
fn a_proxy_certificate_header_needs_the_client_ca() {
for item_text in [
"tls:*",
"tls:n",
"tls-sha256:0000000000000000000000000000000000000000000000000000000000000000",
] {
let access = access(&format!("[ex-ostrya client \"c\"]\nauth={item_text}\n"));
access.check_server(&settings()).unwrap();
access.check_server(&ServerSettings::default()).unwrap();
let merged = ServerSettings {
tls_client_ca: None,
..settings()
};
access.check_server(&merged).unwrap();
}
let access = access("[ex-ostrya client \"c\"]\nauth=anonymous\n");
access.check_server(&ServerSettings::default()).unwrap();
let proxy = Some(vec![IpNet::parse("10.0.0.0/24").unwrap()]);
let merged = ServerSettings {
trusted_proxy_client_cert: Some("X-Client-Cert".into()),
trusted_proxy: proxy.clone(),
..ServerSettings::default()
};
let message = check(&access, &merged);
assert!(message.contains("trusted-proxy-client-cert"), "{message}");
assert!(message.contains("tls-client-ca"), "{message}");
let merged = ServerSettings {
trusted_proxy_client_cert: Some("X-Client-Cert".into()),
trusted_proxy: proxy,
trusted_proxy_header: Some(ForwardedHeader::XForwardedFor),
tls_client_ca: Some("/ca.pem".into()),
..ServerSettings::default()
};
access.check_server(&merged).unwrap();
}
#[test]
fn a_proxy_certificate_header_needs_a_trusted_proxy() {
let anonymous = access("[ex-ostrya client \"c\"]\nauth=anonymous\n");
let merged = ServerSettings {
trusted_proxy_client_cert: Some("X-Client-Cert".into()),
tls_client_ca: Some("/ca.pem".into()),
..ServerSettings::default()
};
let message = check(&anonymous, &merged);
assert_eq!(
message,
"trusted-proxy-client-cert is set, and the server has no trusted-proxy"
);
let configured = access(
"[ex-ostrya server]\ntls-client-ca=/ca.pem\n\
trusted-proxy-client-cert=X-Client-Cert\n",
);
let message = check(&configured, configured.server());
assert!(message.contains("no trusted-proxy"), "{message}");
}
#[test]
fn a_trusted_proxy_and_its_header_go_together() {
let anonymous = access("[ex-ostrya client \"c\"]\nauth=anonymous\n");
let proxy = Some(vec![IpNet::parse("10.0.0.0/24").unwrap()]);
let merged = ServerSettings {
trusted_proxy: proxy.clone(),
..ServerSettings::default()
};
assert_eq!(
check(&anonymous, &merged),
"trusted-proxy is set, and the server has no trusted-proxy-header"
);
let merged = ServerSettings {
trusted_proxy_header: Some(ForwardedHeader::Forwarded),
..ServerSettings::default()
};
assert_eq!(
check(&anonymous, &merged),
"trusted-proxy-header is set, and the server has no trusted-proxy"
);
let merged = ServerSettings {
trusted_proxy: proxy,
trusted_proxy_header: Some(ForwardedHeader::XRealIp),
..ServerSettings::default()
};
anonymous.check_server(&merged).unwrap();
let configured = access("[ex-ostrya server]\ntrusted-proxy-header=x-real-ip\n");
let message = check(&configured, configured.server());
assert!(message.contains("no trusted-proxy"), "{message}");
let configured = access("[ex-ostrya server]\ntrusted-proxy=10.0.0.0/8\n");
let flags = ServerSettings {
trusted_proxy_header: Some(ForwardedHeader::Forwarded),
..ServerSettings::default()
};
let merged = configured.server().overridden_by(&flags);
configured.check_server(&merged).unwrap();
}
#[test]
fn a_forwarded_header_has_three_names() {
for (text, header) in [
("forwarded", ForwardedHeader::Forwarded),
("x-forwarded-for", ForwardedHeader::XForwardedFor),
("x-real-ip", ForwardedHeader::XRealIp),
] {
assert_eq!(ForwardedHeader::parse(text).unwrap(), header);
assert_eq!(header.to_string(), text);
}
for text in [
"",
"Forwarded",
"X-Real-IP",
"x-forwarded-proto",
" forwarded",
] {
let err = ForwardedHeader::parse(text).unwrap_err();
assert!(matches!(err, Error::InvalidFormat(_)), "{text:?}: {err}");
}
}
#[test]
fn a_header_name_is_an_http_token() {
for name in ["X-Client-Cert", "ssl_client_cert", "a!#$%&'*+-.^_`|~9"] {
assert!(is_header_name(name), "{name}");
}
for name in ["", "a b", "a:b", "a\"b", "a(b", "a/b", "\u{e9}", "a\tb"] {
assert!(!is_header_name(name), "{name:?}");
}
}
#[test]
fn a_flag_overrides_its_key() {
let net = |text: &str| IpNet::parse(text).unwrap();
let keys = ServerSettings {
listen: Some(vec![
"127.0.0.1:1".parse().unwrap(),
"127.0.0.1:2".parse().unwrap(),
]),
tls_cert: Some("/key/c.pem".into()),
tls_key: Some("/key/k.pem".into()),
tls_client_ca: Some("/key/ca.pem".into()),
trusted_proxy: Some(vec![net("10.0.0.0/8"), net("10.1.0.0/16")]),
trusted_proxy_header: Some(ForwardedHeader::Forwarded),
trusted_proxy_client_cert: Some("X-Key".into()),
proxy_protocol: Some(false),
allow_cleartext_credentials: Some(true),
session_timeout: Some(1),
max_sessions: Some(2),
parallel_uploads: Some(3),
body_timeout: Some(4),
sign_summary: Some(vec!["a".into(), "b".into()]),
};
let flags = ServerSettings {
listen: Some(vec!["127.0.0.1:3".parse().unwrap()]),
tls_cert: Some("flag/c.pem".into()),
tls_key: Some("flag/k.pem".into()),
tls_client_ca: Some("flag/ca.pem".into()),
trusted_proxy: Some(vec![net("192.0.2.0/24")]),
trusted_proxy_header: Some(ForwardedHeader::XRealIp),
trusted_proxy_client_cert: Some("X-Flag".into()),
proxy_protocol: Some(true),
allow_cleartext_credentials: Some(false),
session_timeout: Some(10),
max_sessions: Some(20),
parallel_uploads: Some(30),
body_timeout: Some(40),
sign_summary: Some(vec!["c".into()]),
};
assert_eq!(keys.overridden_by(&flags), flags);
assert_eq!(keys.overridden_by(&ServerSettings::default()), keys);
assert_eq!(ServerSettings::default().overridden_by(&flags), flags);
let one = ServerSettings {
max_sessions: Some(20),
..ServerSettings::default()
};
let merged = keys.overridden_by(&one);
assert_eq!(merged.max_sessions, Some(20));
assert_eq!(
merged,
ServerSettings {
max_sessions: Some(20),
..keys.clone()
}
);
}
#[test]
fn a_plain_server_ignores_the_client_ca_key() {
let ca = |path: &str| ServerSettings {
tls_client_ca: Some(path.into()),
..ServerSettings::default()
};
let merged = ca("/key/ca.pem").overridden_by(&ServerSettings::default());
assert_eq!(merged, ServerSettings::default());
access("").check_server(&merged).unwrap();
let merged = ca("/key/ca.pem").overridden_by(&ca("flag/ca.pem"));
assert_eq!(merged, ca("flag/ca.pem"));
assert!(check(&access(""), &merged).contains("tls-client-ca"));
let flags = ServerSettings {
tls_cert: Some("flag/c.pem".into()),
tls_key: Some("flag/k.pem".into()),
..ServerSettings::default()
};
let merged = ca("/key/ca.pem").overridden_by(&flags);
assert_eq!(merged.tls_client_ca, Some("/key/ca.pem".into()));
let keys = ServerSettings {
trusted_proxy_client_cert: Some("X-Key".into()),
..ca("/key/ca.pem")
};
let merged = keys.overridden_by(&ServerSettings::default());
assert_eq!(merged.tls_client_ca, Some("/key/ca.pem".into()));
}
#[test]
fn the_tls_files_go_together() {
let access = access("");
let merged = ServerSettings {
tls_key: None,
..settings()
};
assert!(check(&access, &merged).contains("tls-key"));
let merged = ServerSettings {
tls_cert: None,
..settings()
};
assert!(check(&access, &merged).contains("tls-cert"));
let merged = ServerSettings {
tls_client_ca: Some("/ca.pem".into()),
..ServerSettings::default()
};
assert!(check(&access, &merged).contains("tls-client-ca"));
let merged = ServerSettings {
tls_client_ca: None,
..settings()
};
access.check_server(&merged).unwrap();
}
}