stratum_node_config/
config.rs1use 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_body_bytes: u32,
63 max_outstanding_challenges: u32,
64}
65
66impl Config {
67 pub(crate) fn from_values(values: &[Value]) -> Result<Self, ValidationError> {
76 let v = Lookup::new(values).expect("expected one value per schema field");
77 let non_empty = |s: &str| (!s.is_empty()).then(|| s.to_owned());
78 let listen = v.str("listen.address")?;
79 Ok(Self {
80 node_name: v.str("node.name")?.to_owned(),
81 canonical_origin: non_empty(v.str("node.canonical_origin")?),
82 listen_address: rules::parse_loopback(listen).map_err(|msg| {
83 ValidationError::at(ValidationErrorKind::InvalidValue, "listen.address", msg)
84 })?,
85 state_dir: PathBuf::from(v.str("storage.state_dir")?),
86 backup_dir: PathBuf::from(v.str("storage.backup_dir")?),
87 age_recipients: v.list("backup.age_recipients")?.to_vec(),
88 pod_admin_key_ref: non_empty(v.str("secrets.pod_admin_key_ref")?).map(SecretRef),
89 federation_egress_enabled: v.bool("federation.egress_enabled")?,
90 max_body_bytes: v.u32("limits.max_body_bytes")?,
91 max_outstanding_challenges: v.u32("limits.max_outstanding_challenges")?,
92 })
93 }
94
95 pub fn node_name(&self) -> &str {
97 &self.node_name
98 }
99
100 pub fn canonical_origin(&self) -> Option<&str> {
102 self.canonical_origin.as_deref()
103 }
104
105 pub fn listen_address(&self) -> SocketAddr {
107 self.listen_address
108 }
109
110 pub fn state_dir(&self) -> &Path {
112 &self.state_dir
113 }
114
115 pub fn backup_dir(&self) -> &Path {
118 &self.backup_dir
119 }
120
121 pub fn age_recipients(&self) -> &[String] {
124 &self.age_recipients
125 }
126
127 pub fn pod_admin_key_ref(&self) -> Option<&SecretRef> {
129 self.pod_admin_key_ref.as_ref()
130 }
131
132 pub fn federation_egress_enabled(&self) -> bool {
134 self.federation_egress_enabled
135 }
136
137 pub fn max_body_bytes(&self) -> u32 {
139 self.max_body_bytes
140 }
141
142 pub fn max_outstanding_challenges(&self) -> u32 {
144 self.max_outstanding_challenges
145 }
146}
147
148struct Lookup<'v>(&'v [Value]);
150
151impl<'v> Lookup<'v> {
152 fn new(values: &'v [Value]) -> Option<Self> {
155 (values.len() == schema().table().len()).then_some(Self(values))
156 }
157
158 fn get(&self, path: &'static str) -> Result<&'v Value, ValidationError> {
161 let index = schema().index_of(path).ok_or_else(|| {
162 ValidationError::at(
163 ValidationErrorKind::UnknownKey,
164 path,
165 "field is not in the schema",
166 )
167 })?;
168 Ok(&self.0[index])
169 }
170
171 fn mismatch(path: &'static str, expected: &str) -> ValidationError {
172 ValidationError::at(
173 ValidationErrorKind::WrongType,
174 path,
175 format!("expected {expected}"),
176 )
177 }
178
179 fn str(&self, path: &'static str) -> Result<&'v str, ValidationError> {
180 self.get(path)?
181 .as_str()
182 .ok_or_else(|| Self::mismatch(path, "a string"))
183 }
184
185 fn list(&self, path: &'static str) -> Result<&'v [String], ValidationError> {
186 self.get(path)?
187 .as_string_list()
188 .ok_or_else(|| Self::mismatch(path, "a list of strings"))
189 }
190
191 fn bool(&self, path: &'static str) -> Result<bool, ValidationError> {
192 self.get(path)?
193 .as_bool()
194 .ok_or_else(|| Self::mismatch(path, "a boolean"))
195 }
196
197 fn u32(&self, path: &'static str) -> Result<u32, ValidationError> {
200 let i = self
201 .get(path)?
202 .as_integer()
203 .ok_or_else(|| Self::mismatch(path, "an integer"))?;
204 u32::try_from(i).map_err(|_| {
205 ValidationError::at(
206 ValidationErrorKind::OutOfRange,
207 path,
208 format!("must be between 0 and {}", u32::MAX),
209 )
210 })
211 }
212}
213
214#[cfg(test)]
215mod tests {
216 use super::*;
217 use crate::schema::FieldDescriptor;
218
219 fn defaults() -> Vec<Value> {
221 schema()
222 .fields()
223 .map(FieldDescriptor::default_value)
224 .collect()
225 }
226
227 fn with(path: &str, value: Value) -> Vec<Value> {
228 let mut values = defaults();
229 let i = schema().index_of(path).expect("path in schema");
230 values[i] = value;
231 values
232 }
233
234 #[test]
235 fn integer_outside_u32_is_out_of_range() {
236 for n in [-1, i64::from(u32::MAX) + 1] {
237 let values = with("limits.max_body_bytes", Value::Integer(n));
238 let e = Lookup::new(&values)
239 .expect("full value list")
240 .u32("limits.max_body_bytes")
241 .expect_err("out of range");
242 assert_eq!(e.kind(), ValidationErrorKind::OutOfRange, "{n}");
243 assert_eq!(e.message(), "must be between 0 and 4294967295", "{n}");
244 }
245 let values = with("limits.max_body_bytes", Value::Integer(4_294_967_295));
246 assert_eq!(
247 Lookup::new(&values)
248 .expect("full value list")
249 .u32("limits.max_body_bytes"),
250 Ok(u32::MAX),
251 "upper bound"
252 );
253 }
254
255 #[test]
256 fn non_integer_is_wrong_type() {
257 let values = with("limits.max_body_bytes", Value::from("many"));
258 let e = Lookup::new(&values)
259 .expect("full value list")
260 .u32("limits.max_body_bytes")
261 .expect_err("wrong type");
262 assert_eq!(e.kind(), ValidationErrorKind::WrongType, "kind");
263 assert_eq!(e.message(), "expected an integer", "message");
264 }
265
266 #[test]
267 fn unknown_path_is_unknown_key() {
268 let values = defaults();
269 let e = Lookup::new(&values)
270 .expect("full value list")
271 .get("limits.nope")
272 .expect_err("unknown");
273 assert_eq!(e.kind(), ValidationErrorKind::UnknownKey, "kind");
274 }
275
276 #[test]
277 #[should_panic(expected = "expected one value per schema field")]
278 fn short_value_list_is_a_bug_not_an_unknown_key() {
279 let mut values = defaults();
280 values.pop();
281 let _ = Config::from_values(&values);
282 }
283
284 #[test]
285 fn defaults_build_a_config() {
286 let config = Config::from_values(&defaults()).expect("defaults are valid");
287 assert_eq!(config.max_body_bytes(), 262_144, "default");
288 }
289}