use std::fmt;
use std::net::SocketAddr;
use std::path::{Path, PathBuf};
use std::time::Duration;
use crate::error::{ValidationError, ValidationErrorKind};
use crate::rules;
use crate::schema::schema;
use crate::value::Value;
const SECS_PER_DAY: u64 = 86_400;
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct SecretRef(String);
impl SecretRef {
pub fn as_str(&self) -> &str {
&self.0
}
}
impl fmt::Debug for SecretRef {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("SecretRef(<redacted>)")
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Config {
node_name: String,
canonical_origin: Option<String>,
listen_address: SocketAddr,
state_dir: PathBuf,
backup_dir: PathBuf,
age_recipients: Vec<String>,
pod_admin_key_ref: Option<SecretRef>,
federation_egress_enabled: bool,
max_tenants: u32,
invitations_enabled: bool,
invitation_ttl_secs: u32,
removal_grace_days: u32,
max_body_bytes: u32,
max_outstanding_challenges: u32,
max_pod_body_bytes: u32,
admission_requests_per_minute: u32,
min_pod_free_bytes: u64,
pod_bytes_per_tenant: u64,
}
impl Config {
pub(crate) fn from_values(values: &[Value]) -> Result<Self, ValidationError> {
let v = Lookup::new(values).expect("expected one value per schema field");
let non_empty = |s: &str| (!s.is_empty()).then(|| s.to_owned());
let listen = v.str("listen.address")?;
Ok(Self {
node_name: v.str("node.name")?.to_owned(),
canonical_origin: non_empty(v.str("node.canonical_origin")?),
listen_address: rules::parse_loopback(listen).map_err(|msg| {
ValidationError::at(ValidationErrorKind::InvalidValue, "listen.address", msg)
})?,
state_dir: PathBuf::from(v.str("storage.state_dir")?),
backup_dir: PathBuf::from(v.str("storage.backup_dir")?),
age_recipients: v.list("backup.age_recipients")?.to_vec(),
pod_admin_key_ref: non_empty(v.str("secrets.pod_admin_key_ref")?).map(SecretRef),
federation_egress_enabled: v.bool("federation.egress_enabled")?,
max_body_bytes: v.u32("limits.max_body_bytes")?,
max_tenants: v.u32("membership.max_tenants")?,
invitations_enabled: v.bool("membership.invitations_enabled")?,
invitation_ttl_secs: v.u32("membership.invitation_ttl_secs")?,
removal_grace_days: v.u32("membership.removal_grace_days")?,
max_outstanding_challenges: v.u32("limits.max_outstanding_challenges")?,
max_pod_body_bytes: v.u32("limits.max_pod_body_bytes")?,
admission_requests_per_minute: v.u32("limits.admission_requests_per_minute")?,
min_pod_free_bytes: v.u64("limits.min_pod_free_bytes")?,
pod_bytes_per_tenant: v.u64("limits.pod_bytes_per_tenant")?,
})
}
pub fn node_name(&self) -> &str {
&self.node_name
}
pub fn canonical_origin(&self) -> Option<&str> {
self.canonical_origin.as_deref()
}
pub fn listen_address(&self) -> SocketAddr {
self.listen_address
}
pub fn state_dir(&self) -> &Path {
&self.state_dir
}
pub fn backup_dir(&self) -> &Path {
&self.backup_dir
}
pub fn age_recipients(&self) -> &[String] {
&self.age_recipients
}
pub fn pod_admin_key_ref(&self) -> Option<&SecretRef> {
self.pod_admin_key_ref.as_ref()
}
pub fn federation_egress_enabled(&self) -> bool {
self.federation_egress_enabled
}
pub fn max_body_bytes(&self) -> u32 {
self.max_body_bytes
}
pub fn max_outstanding_challenges(&self) -> u32 {
self.max_outstanding_challenges
}
pub fn max_tenants(&self) -> u32 {
self.max_tenants
}
pub fn invitations_enabled(&self) -> bool {
self.invitations_enabled
}
pub fn invitation_ttl_secs(&self) -> u32 {
self.invitation_ttl_secs
}
pub fn max_pod_body_bytes(&self) -> u32 {
self.max_pod_body_bytes
}
pub fn admission_requests_per_minute(&self) -> u32 {
self.admission_requests_per_minute
}
pub fn min_pod_free_bytes(&self) -> u64 {
self.min_pod_free_bytes
}
pub fn removal_grace_days(&self) -> u32 {
self.removal_grace_days
}
pub fn removal_grace(&self) -> Duration {
Duration::from_secs(u64::from(self.removal_grace_days) * SECS_PER_DAY)
}
pub fn pod_bytes_per_tenant(&self) -> u64 {
self.pod_bytes_per_tenant
}
pub fn is_over_quota(&self, pod_bytes: u64) -> bool {
self.pod_bytes_per_tenant > 0 && pod_bytes > self.pod_bytes_per_tenant
}
}
struct Lookup<'v>(&'v [Value]);
impl<'v> Lookup<'v> {
fn new(values: &'v [Value]) -> Option<Self> {
(values.len() == schema().table().len()).then_some(Self(values))
}
fn get(&self, path: &'static str) -> Result<&'v Value, ValidationError> {
let index = schema().index_of(path).ok_or_else(|| {
ValidationError::at(
ValidationErrorKind::UnknownKey,
path,
"field is not in the schema",
)
})?;
Ok(&self.0[index])
}
fn mismatch(path: &'static str, expected: &str) -> ValidationError {
ValidationError::at(
ValidationErrorKind::WrongType,
path,
format!("expected {expected}"),
)
}
fn str(&self, path: &'static str) -> Result<&'v str, ValidationError> {
self.get(path)?
.as_str()
.ok_or_else(|| Self::mismatch(path, "a string"))
}
fn list(&self, path: &'static str) -> Result<&'v [String], ValidationError> {
self.get(path)?
.as_string_list()
.ok_or_else(|| Self::mismatch(path, "a list of strings"))
}
fn bool(&self, path: &'static str) -> Result<bool, ValidationError> {
self.get(path)?
.as_bool()
.ok_or_else(|| Self::mismatch(path, "a boolean"))
}
fn u64(&self, path: &'static str) -> Result<u64, ValidationError> {
let i = self
.get(path)?
.as_integer()
.ok_or_else(|| Self::mismatch(path, "an integer"))?;
u64::try_from(i).map_err(|_| {
ValidationError::at(
ValidationErrorKind::OutOfRange,
path,
format!("must be between 0 and {}", i64::MAX),
)
})
}
fn u32(&self, path: &'static str) -> Result<u32, ValidationError> {
let i = self
.get(path)?
.as_integer()
.ok_or_else(|| Self::mismatch(path, "an integer"))?;
u32::try_from(i).map_err(|_| {
ValidationError::at(
ValidationErrorKind::OutOfRange,
path,
format!("must be between 0 and {}", u32::MAX),
)
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::schema::FieldDescriptor;
fn defaults() -> Vec<Value> {
schema()
.fields()
.map(FieldDescriptor::default_value)
.collect()
}
fn with(path: &str, value: Value) -> Vec<Value> {
let mut values = defaults();
let i = schema().index_of(path).expect("path in schema");
values[i] = value;
values
}
#[test]
fn integer_outside_u32_is_out_of_range() {
for n in [-1, i64::from(u32::MAX) + 1] {
let values = with("limits.max_body_bytes", Value::Integer(n));
let e = Lookup::new(&values)
.expect("full value list")
.u32("limits.max_body_bytes")
.expect_err("out of range");
assert_eq!(e.kind(), ValidationErrorKind::OutOfRange, "{n}");
assert_eq!(e.message(), "must be between 0 and 4294967295", "{n}");
}
let values = with("limits.max_body_bytes", Value::Integer(4_294_967_295));
assert_eq!(
Lookup::new(&values)
.expect("full value list")
.u32("limits.max_body_bytes"),
Ok(u32::MAX),
"upper bound"
);
}
#[test]
fn non_integer_is_wrong_type() {
let values = with("limits.max_body_bytes", Value::from("many"));
let e = Lookup::new(&values)
.expect("full value list")
.u32("limits.max_body_bytes")
.expect_err("wrong type");
assert_eq!(e.kind(), ValidationErrorKind::WrongType, "kind");
assert_eq!(e.message(), "expected an integer", "message");
}
#[test]
fn unknown_path_is_unknown_key() {
let values = defaults();
let e = Lookup::new(&values)
.expect("full value list")
.get("limits.nope")
.expect_err("unknown");
assert_eq!(e.kind(), ValidationErrorKind::UnknownKey, "kind");
}
#[test]
#[should_panic(expected = "expected one value per schema field")]
fn short_value_list_is_a_bug_not_an_unknown_key() {
let mut values = defaults();
values.pop();
let _ = Config::from_values(&values);
}
#[test]
fn defaults_build_a_config() {
let config = Config::from_values(&defaults()).expect("defaults are valid");
assert_eq!(config.max_body_bytes(), 262_144, "default");
}
}