1use std::fmt;
4use std::net::SocketAddr;
5use std::path::{Path, PathBuf};
6
7use crate::error::{ValidationError, ValidationErrorKind};
8use crate::rules;
9use crate::schema::schema;
10use crate::value::Value;
11
12#[derive(Clone, PartialEq, Eq, Hash)]
18pub struct SecretRef(String);
19
20impl SecretRef {
21 pub fn as_str(&self) -> &str {
23 &self.0
24 }
25}
26
27impl fmt::Debug for SecretRef {
28 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
29 f.write_str("SecretRef(<redacted>)")
30 }
31}
32
33#[derive(Debug, Clone, PartialEq, Eq)]
53pub struct Config {
54 node_name: String,
55 canonical_origin: Option<String>,
56 listen_address: SocketAddr,
57 state_dir: PathBuf,
58 backup_dir: PathBuf,
59 age_recipients: Vec<String>,
60 pod_admin_key_ref: Option<SecretRef>,
61 federation_egress_enabled: bool,
62 max_tenants: u32,
63 invitations_enabled: bool,
64 invitation_ttl_secs: u32,
65 max_body_bytes: u32,
66 max_outstanding_challenges: u32,
67 max_pod_body_bytes: u32,
68 admission_requests_per_minute: u32,
69 min_pod_free_bytes: u64,
70}
71
72impl Config {
73 pub(crate) fn from_values(values: &[Value]) -> Result<Self, ValidationError> {
82 let v = Lookup::new(values).expect("expected one value per schema field");
83 let non_empty = |s: &str| (!s.is_empty()).then(|| s.to_owned());
84 let listen = v.str("listen.address")?;
85 Ok(Self {
86 node_name: v.str("node.name")?.to_owned(),
87 canonical_origin: non_empty(v.str("node.canonical_origin")?),
88 listen_address: rules::parse_loopback(listen).map_err(|msg| {
89 ValidationError::at(ValidationErrorKind::InvalidValue, "listen.address", msg)
90 })?,
91 state_dir: PathBuf::from(v.str("storage.state_dir")?),
92 backup_dir: PathBuf::from(v.str("storage.backup_dir")?),
93 age_recipients: v.list("backup.age_recipients")?.to_vec(),
94 pod_admin_key_ref: non_empty(v.str("secrets.pod_admin_key_ref")?).map(SecretRef),
95 federation_egress_enabled: v.bool("federation.egress_enabled")?,
96 max_body_bytes: v.u32("limits.max_body_bytes")?,
97 max_tenants: v.u32("membership.max_tenants")?,
98 invitations_enabled: v.bool("membership.invitations_enabled")?,
99 invitation_ttl_secs: v.u32("membership.invitation_ttl_secs")?,
100 max_outstanding_challenges: v.u32("limits.max_outstanding_challenges")?,
101 max_pod_body_bytes: v.u32("limits.max_pod_body_bytes")?,
102 admission_requests_per_minute: v.u32("limits.admission_requests_per_minute")?,
103 min_pod_free_bytes: v.u64("limits.min_pod_free_bytes")?,
104 })
105 }
106
107 pub fn node_name(&self) -> &str {
109 &self.node_name
110 }
111
112 pub fn canonical_origin(&self) -> Option<&str> {
114 self.canonical_origin.as_deref()
115 }
116
117 pub fn listen_address(&self) -> SocketAddr {
119 self.listen_address
120 }
121
122 pub fn state_dir(&self) -> &Path {
124 &self.state_dir
125 }
126
127 pub fn backup_dir(&self) -> &Path {
130 &self.backup_dir
131 }
132
133 pub fn age_recipients(&self) -> &[String] {
136 &self.age_recipients
137 }
138
139 pub fn pod_admin_key_ref(&self) -> Option<&SecretRef> {
144 self.pod_admin_key_ref.as_ref()
145 }
146
147 pub fn federation_egress_enabled(&self) -> bool {
149 self.federation_egress_enabled
150 }
151
152 pub fn max_body_bytes(&self) -> u32 {
154 self.max_body_bytes
155 }
156
157 pub fn max_outstanding_challenges(&self) -> u32 {
159 self.max_outstanding_challenges
160 }
161
162 pub fn max_tenants(&self) -> u32 {
164 self.max_tenants
165 }
166
167 pub fn invitations_enabled(&self) -> bool {
169 self.invitations_enabled
170 }
171
172 pub fn invitation_ttl_secs(&self) -> u32 {
174 self.invitation_ttl_secs
175 }
176
177 pub fn max_pod_body_bytes(&self) -> u32 {
179 self.max_pod_body_bytes
180 }
181
182 pub fn admission_requests_per_minute(&self) -> u32 {
184 self.admission_requests_per_minute
185 }
186
187 pub fn min_pod_free_bytes(&self) -> u64 {
189 self.min_pod_free_bytes
190 }
191}
192
193struct Lookup<'v>(&'v [Value]);
195
196impl<'v> Lookup<'v> {
197 fn new(values: &'v [Value]) -> Option<Self> {
200 (values.len() == schema().table().len()).then_some(Self(values))
201 }
202
203 fn get(&self, path: &'static str) -> Result<&'v Value, ValidationError> {
206 let index = schema().index_of(path).ok_or_else(|| {
207 ValidationError::at(
208 ValidationErrorKind::UnknownKey,
209 path,
210 "field is not in the schema",
211 )
212 })?;
213 Ok(&self.0[index])
214 }
215
216 fn mismatch(path: &'static str, expected: &str) -> ValidationError {
217 ValidationError::at(
218 ValidationErrorKind::WrongType,
219 path,
220 format!("expected {expected}"),
221 )
222 }
223
224 fn str(&self, path: &'static str) -> Result<&'v str, ValidationError> {
225 self.get(path)?
226 .as_str()
227 .ok_or_else(|| Self::mismatch(path, "a string"))
228 }
229
230 fn list(&self, path: &'static str) -> Result<&'v [String], ValidationError> {
231 self.get(path)?
232 .as_string_list()
233 .ok_or_else(|| Self::mismatch(path, "a list of strings"))
234 }
235
236 fn bool(&self, path: &'static str) -> Result<bool, ValidationError> {
237 self.get(path)?
238 .as_bool()
239 .ok_or_else(|| Self::mismatch(path, "a boolean"))
240 }
241
242 fn u64(&self, path: &'static str) -> Result<u64, ValidationError> {
245 let i = self
246 .get(path)?
247 .as_integer()
248 .ok_or_else(|| Self::mismatch(path, "an integer"))?;
249 u64::try_from(i).map_err(|_| {
250 ValidationError::at(
251 ValidationErrorKind::OutOfRange,
252 path,
253 format!("must be between 0 and {}", i64::MAX),
254 )
255 })
256 }
257
258 fn u32(&self, path: &'static str) -> Result<u32, ValidationError> {
261 let i = self
262 .get(path)?
263 .as_integer()
264 .ok_or_else(|| Self::mismatch(path, "an integer"))?;
265 u32::try_from(i).map_err(|_| {
266 ValidationError::at(
267 ValidationErrorKind::OutOfRange,
268 path,
269 format!("must be between 0 and {}", u32::MAX),
270 )
271 })
272 }
273}
274
275#[cfg(test)]
276mod tests {
277 use super::*;
278 use crate::schema::FieldDescriptor;
279
280 fn defaults() -> Vec<Value> {
282 schema()
283 .fields()
284 .map(FieldDescriptor::default_value)
285 .collect()
286 }
287
288 fn with(path: &str, value: Value) -> Vec<Value> {
289 let mut values = defaults();
290 let i = schema().index_of(path).expect("path in schema");
291 values[i] = value;
292 values
293 }
294
295 #[test]
296 fn integer_outside_u32_is_out_of_range() {
297 for n in [-1, i64::from(u32::MAX) + 1] {
298 let values = with("limits.max_body_bytes", Value::Integer(n));
299 let e = Lookup::new(&values)
300 .expect("full value list")
301 .u32("limits.max_body_bytes")
302 .expect_err("out of range");
303 assert_eq!(e.kind(), ValidationErrorKind::OutOfRange, "{n}");
304 assert_eq!(e.message(), "must be between 0 and 4294967295", "{n}");
305 }
306 let values = with("limits.max_body_bytes", Value::Integer(4_294_967_295));
307 assert_eq!(
308 Lookup::new(&values)
309 .expect("full value list")
310 .u32("limits.max_body_bytes"),
311 Ok(u32::MAX),
312 "upper bound"
313 );
314 }
315
316 #[test]
317 fn non_integer_is_wrong_type() {
318 let values = with("limits.max_body_bytes", Value::from("many"));
319 let e = Lookup::new(&values)
320 .expect("full value list")
321 .u32("limits.max_body_bytes")
322 .expect_err("wrong type");
323 assert_eq!(e.kind(), ValidationErrorKind::WrongType, "kind");
324 assert_eq!(e.message(), "expected an integer", "message");
325 }
326
327 #[test]
328 fn unknown_path_is_unknown_key() {
329 let values = defaults();
330 let e = Lookup::new(&values)
331 .expect("full value list")
332 .get("limits.nope")
333 .expect_err("unknown");
334 assert_eq!(e.kind(), ValidationErrorKind::UnknownKey, "kind");
335 }
336
337 #[test]
338 #[should_panic(expected = "expected one value per schema field")]
339 fn short_value_list_is_a_bug_not_an_unknown_key() {
340 let mut values = defaults();
341 values.pop();
342 let _ = Config::from_values(&values);
343 }
344
345 #[test]
346 fn defaults_build_a_config() {
347 let config = Config::from_values(&defaults()).expect("defaults are valid");
348 assert_eq!(config.max_body_bytes(), 262_144, "default");
349 }
350}