1use std::fmt;
4use std::net::SocketAddr;
5use std::path::{Path, PathBuf};
6use std::time::Duration;
7
8use crate::error::{ValidationError, ValidationErrorKind};
9use crate::rules;
10use crate::schema::schema;
11use crate::value::Value;
12
13const SECS_PER_DAY: u64 = 86_400;
15
16#[derive(Clone, PartialEq, Eq, Hash)]
22pub struct SecretRef(String);
23
24impl SecretRef {
25 pub fn as_str(&self) -> &str {
27 &self.0
28 }
29}
30
31impl fmt::Debug for SecretRef {
32 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
33 f.write_str("SecretRef(<redacted>)")
34 }
35}
36
37#[derive(Debug, Clone, PartialEq, Eq)]
57pub struct Config {
58 node_name: String,
59 canonical_origin: Option<String>,
60 listen_address: SocketAddr,
61 state_dir: PathBuf,
62 backup_dir: PathBuf,
63 age_recipients: Vec<String>,
64 pod_admin_key_ref: Option<SecretRef>,
65 federation_egress_enabled: bool,
66 max_tenants: u32,
67 invitations_enabled: bool,
68 invitation_ttl_secs: u32,
69 removal_grace_days: u32,
70 max_body_bytes: u32,
71 max_outstanding_challenges: u32,
72 max_pod_body_bytes: u32,
73 admission_requests_per_minute: u32,
74 min_pod_free_bytes: u64,
75 pod_bytes_per_tenant: u64,
76}
77
78impl Config {
79 pub(crate) fn from_values(values: &[Value]) -> Result<Self, ValidationError> {
88 let v = Lookup::new(values).expect("expected one value per schema field");
89 let non_empty = |s: &str| (!s.is_empty()).then(|| s.to_owned());
90 let listen = v.str("listen.address")?;
91 Ok(Self {
92 node_name: v.str("node.name")?.to_owned(),
93 canonical_origin: non_empty(v.str("node.canonical_origin")?),
94 listen_address: rules::parse_loopback(listen).map_err(|msg| {
95 ValidationError::at(ValidationErrorKind::InvalidValue, "listen.address", msg)
96 })?,
97 state_dir: PathBuf::from(v.str("storage.state_dir")?),
98 backup_dir: PathBuf::from(v.str("storage.backup_dir")?),
99 age_recipients: v.list("backup.age_recipients")?.to_vec(),
100 pod_admin_key_ref: non_empty(v.str("secrets.pod_admin_key_ref")?).map(SecretRef),
101 federation_egress_enabled: v.bool("federation.egress_enabled")?,
102 max_body_bytes: v.u32("limits.max_body_bytes")?,
103 max_tenants: v.u32("membership.max_tenants")?,
104 invitations_enabled: v.bool("membership.invitations_enabled")?,
105 invitation_ttl_secs: v.u32("membership.invitation_ttl_secs")?,
106 removal_grace_days: v.u32("membership.removal_grace_days")?,
107 max_outstanding_challenges: v.u32("limits.max_outstanding_challenges")?,
108 max_pod_body_bytes: v.u32("limits.max_pod_body_bytes")?,
109 admission_requests_per_minute: v.u32("limits.admission_requests_per_minute")?,
110 min_pod_free_bytes: v.u64("limits.min_pod_free_bytes")?,
111 pod_bytes_per_tenant: v.u64("limits.pod_bytes_per_tenant")?,
112 })
113 }
114
115 pub fn node_name(&self) -> &str {
117 &self.node_name
118 }
119
120 pub fn canonical_origin(&self) -> Option<&str> {
122 self.canonical_origin.as_deref()
123 }
124
125 pub fn listen_address(&self) -> SocketAddr {
127 self.listen_address
128 }
129
130 pub fn state_dir(&self) -> &Path {
132 &self.state_dir
133 }
134
135 pub fn backup_dir(&self) -> &Path {
138 &self.backup_dir
139 }
140
141 pub fn age_recipients(&self) -> &[String] {
144 &self.age_recipients
145 }
146
147 pub fn pod_admin_key_ref(&self) -> Option<&SecretRef> {
152 self.pod_admin_key_ref.as_ref()
153 }
154
155 pub fn federation_egress_enabled(&self) -> bool {
157 self.federation_egress_enabled
158 }
159
160 pub fn max_body_bytes(&self) -> u32 {
162 self.max_body_bytes
163 }
164
165 pub fn max_outstanding_challenges(&self) -> u32 {
167 self.max_outstanding_challenges
168 }
169
170 pub fn max_tenants(&self) -> u32 {
172 self.max_tenants
173 }
174
175 pub fn invitations_enabled(&self) -> bool {
177 self.invitations_enabled
178 }
179
180 pub fn invitation_ttl_secs(&self) -> u32 {
182 self.invitation_ttl_secs
183 }
184
185 pub fn max_pod_body_bytes(&self) -> u32 {
187 self.max_pod_body_bytes
188 }
189
190 pub fn admission_requests_per_minute(&self) -> u32 {
192 self.admission_requests_per_minute
193 }
194
195 pub fn min_pod_free_bytes(&self) -> u64 {
197 self.min_pod_free_bytes
198 }
199
200 pub fn removal_grace_days(&self) -> u32 {
220 self.removal_grace_days
221 }
222
223 pub fn removal_grace(&self) -> Duration {
241 Duration::from_secs(u64::from(self.removal_grace_days) * SECS_PER_DAY)
242 }
243
244 pub fn pod_bytes_per_tenant(&self) -> u64 {
258 self.pod_bytes_per_tenant
259 }
260
261 pub fn is_over_quota(&self, pod_bytes: u64) -> bool {
287 self.pod_bytes_per_tenant > 0 && pod_bytes > self.pod_bytes_per_tenant
288 }
289}
290
291struct Lookup<'v>(&'v [Value]);
293
294impl<'v> Lookup<'v> {
295 fn new(values: &'v [Value]) -> Option<Self> {
298 (values.len() == schema().table().len()).then_some(Self(values))
299 }
300
301 fn get(&self, path: &'static str) -> Result<&'v Value, ValidationError> {
304 let index = schema().index_of(path).ok_or_else(|| {
305 ValidationError::at(
306 ValidationErrorKind::UnknownKey,
307 path,
308 "field is not in the schema",
309 )
310 })?;
311 Ok(&self.0[index])
312 }
313
314 fn mismatch(path: &'static str, expected: &str) -> ValidationError {
315 ValidationError::at(
316 ValidationErrorKind::WrongType,
317 path,
318 format!("expected {expected}"),
319 )
320 }
321
322 fn str(&self, path: &'static str) -> Result<&'v str, ValidationError> {
323 self.get(path)?
324 .as_str()
325 .ok_or_else(|| Self::mismatch(path, "a string"))
326 }
327
328 fn list(&self, path: &'static str) -> Result<&'v [String], ValidationError> {
329 self.get(path)?
330 .as_string_list()
331 .ok_or_else(|| Self::mismatch(path, "a list of strings"))
332 }
333
334 fn bool(&self, path: &'static str) -> Result<bool, ValidationError> {
335 self.get(path)?
336 .as_bool()
337 .ok_or_else(|| Self::mismatch(path, "a boolean"))
338 }
339
340 fn u64(&self, path: &'static str) -> Result<u64, ValidationError> {
343 let i = self
344 .get(path)?
345 .as_integer()
346 .ok_or_else(|| Self::mismatch(path, "an integer"))?;
347 u64::try_from(i).map_err(|_| {
348 ValidationError::at(
349 ValidationErrorKind::OutOfRange,
350 path,
351 format!("must be between 0 and {}", i64::MAX),
352 )
353 })
354 }
355
356 fn u32(&self, path: &'static str) -> Result<u32, ValidationError> {
359 let i = self
360 .get(path)?
361 .as_integer()
362 .ok_or_else(|| Self::mismatch(path, "an integer"))?;
363 u32::try_from(i).map_err(|_| {
364 ValidationError::at(
365 ValidationErrorKind::OutOfRange,
366 path,
367 format!("must be between 0 and {}", u32::MAX),
368 )
369 })
370 }
371}
372
373#[cfg(test)]
374mod tests {
375 use super::*;
376 use crate::schema::FieldDescriptor;
377
378 fn defaults() -> Vec<Value> {
380 schema()
381 .fields()
382 .map(FieldDescriptor::default_value)
383 .collect()
384 }
385
386 fn with(path: &str, value: Value) -> Vec<Value> {
387 let mut values = defaults();
388 let i = schema().index_of(path).expect("path in schema");
389 values[i] = value;
390 values
391 }
392
393 #[test]
394 fn integer_outside_u32_is_out_of_range() {
395 for n in [-1, i64::from(u32::MAX) + 1] {
396 let values = with("limits.max_body_bytes", Value::Integer(n));
397 let e = Lookup::new(&values)
398 .expect("full value list")
399 .u32("limits.max_body_bytes")
400 .expect_err("out of range");
401 assert_eq!(e.kind(), ValidationErrorKind::OutOfRange, "{n}");
402 assert_eq!(e.message(), "must be between 0 and 4294967295", "{n}");
403 }
404 let values = with("limits.max_body_bytes", Value::Integer(4_294_967_295));
405 assert_eq!(
406 Lookup::new(&values)
407 .expect("full value list")
408 .u32("limits.max_body_bytes"),
409 Ok(u32::MAX),
410 "upper bound"
411 );
412 }
413
414 #[test]
415 fn non_integer_is_wrong_type() {
416 let values = with("limits.max_body_bytes", Value::from("many"));
417 let e = Lookup::new(&values)
418 .expect("full value list")
419 .u32("limits.max_body_bytes")
420 .expect_err("wrong type");
421 assert_eq!(e.kind(), ValidationErrorKind::WrongType, "kind");
422 assert_eq!(e.message(), "expected an integer", "message");
423 }
424
425 #[test]
426 fn unknown_path_is_unknown_key() {
427 let values = defaults();
428 let e = Lookup::new(&values)
429 .expect("full value list")
430 .get("limits.nope")
431 .expect_err("unknown");
432 assert_eq!(e.kind(), ValidationErrorKind::UnknownKey, "kind");
433 }
434
435 #[test]
436 #[should_panic(expected = "expected one value per schema field")]
437 fn short_value_list_is_a_bug_not_an_unknown_key() {
438 let mut values = defaults();
439 values.pop();
440 let _ = Config::from_values(&values);
441 }
442
443 #[test]
444 fn defaults_build_a_config() {
445 let config = Config::from_values(&defaults()).expect("defaults are valid");
446 assert_eq!(config.max_body_bytes(), 262_144, "default");
447 }
448}