Skip to main content

stratum_node_config/
document.rs

1//! Parsing and validating `stratum.toml` text.
2
3use std::fmt;
4
5use toml_edit::{DocumentMut, TableLike};
6
7use crate::config::Config;
8use crate::error::{ValidationError, ValidationErrorKind, ValidationErrors};
9use crate::public::{PublicConfig, PublicHash};
10use crate::rules;
11use crate::schema::{schema, SCHEMA_VERSION};
12use crate::value::Value;
13
14/// The largest `stratum.toml` this crate accepts, in bytes: 256 KiB.
15///
16/// [`ConfigDocument::parse`] and [`preview`](crate::preview) refuse longer
17/// text before parsing it, and `preview` also refuses an edit whose result
18/// would be longer, before diffing or validating it. A real configuration is
19/// a few kilobytes; the bound keeps parse, diff and validation work small for
20/// an HTTP caller that sends an oversized body or change.
21pub const MAX_DOCUMENT_BYTES: usize = 256 * 1024;
22
23/// The top-level key carrying the schema version.
24pub(crate) const SCHEMA_VERSION_KEY: &str = "schema_version";
25
26/// A validated `stratum.toml` document: its exact text plus the effective
27/// configuration with defaults filled in.
28///
29/// The only way to obtain one is [`ConfigDocument::parse`] (or
30/// [`Preview::document`](crate::Preview::document)), so holding a
31/// `ConfigDocument` proves the text passed every rule in the schema.
32///
33/// # Examples
34///
35/// ```
36/// use stratum_node_config::{ConfigDocument, Value};
37///
38/// let doc = ConfigDocument::parse(
39///     "schema_version = 1\n\n[node]\nname = \"alpha\"\n",
40/// )?;
41/// assert_eq!(doc.config().node_name(), "alpha");
42/// // Omitted fields take their defaults.
43/// assert_eq!(doc.value("limits.max_outstanding_challenges"), Some(&Value::Integer(16)));
44/// # Ok::<(), Box<dyn std::error::Error>>(())
45/// ```
46#[derive(Clone, PartialEq, Eq)]
47pub struct ConfigDocument {
48    text: String,
49    values: Vec<Value>,
50    config: Config,
51}
52
53impl ConfigDocument {
54    /// Parses and validates `stratum.toml` text.
55    ///
56    /// # Errors
57    ///
58    /// Returns every problem found, not just the first: a TOML syntax error
59    /// (reported alone, since nothing else can be checked), a missing or
60    /// unsupported `schema_version`, unknown keys and tables, values of the
61    /// wrong type, integers out of range, values that break a field's rule,
62    /// and cross-field conflicts. Text longer than [`MAX_DOCUMENT_BYTES`] is
63    /// refused unparsed with a single [`ValidationErrorKind::TooLarge`] error.
64    ///
65    /// # Examples
66    ///
67    /// ```
68    /// use stratum_node_config::{ConfigDocument, ValidationErrorKind};
69    ///
70    /// let text = "schema_version = 1\n[limits]\nmax_body_bytes = 1\ncolour = \"red\"\n";
71    /// let errors = ConfigDocument::parse(text).err().ok_or("expected errors")?;
72    /// let kinds: Vec<_> = errors.iter().map(|e| (e.path(), e.kind())).collect();
73    /// assert_eq!(kinds, [
74    ///     (Some("limits.colour"), ValidationErrorKind::UnknownKey),
75    ///     (Some("limits.max_body_bytes"), ValidationErrorKind::OutOfRange),
76    /// ]);
77    /// # Ok::<(), Box<dyn std::error::Error>>(())
78    /// ```
79    pub fn parse(text: &str) -> Result<Self, ValidationErrors> {
80        if text.len() > MAX_DOCUMENT_BYTES {
81            return Err(ValidationErrors::one(ValidationError::new(
82                ValidationErrorKind::TooLarge,
83                None,
84                format!("document is larger than the {MAX_DOCUMENT_BYTES}-byte limit"),
85            )));
86        }
87        let doc = parse_toml(text).map_err(ValidationErrors::one)?;
88        Self::from_toml(text.to_owned(), &doc)
89    }
90
91    /// Validates an already parsed document whose text is `text`.
92    pub(crate) fn from_toml(text: String, doc: &DocumentMut) -> Result<Self, ValidationErrors> {
93        let analysis = analyse(doc);
94        if let Some(errors) = ValidationErrors::from_vec(analysis.errors) {
95            return Err(errors);
96        }
97        // Every field has a value once analysis reports no error; collecting
98        // into `Option` keeps a missing one from shifting later indices.
99        let values: Vec<Value> = analysis
100            .values
101            .into_iter()
102            .collect::<Option<_>>()
103            .expect("analysis without errors yields a value for every field");
104        let config = Config::from_values(&values).map_err(ValidationErrors::one)?;
105        Ok(Self {
106            text,
107            values,
108            config,
109        })
110    }
111
112    /// Returns the exact document text, comments and layout included.
113    pub fn text(&self) -> &str {
114        &self.text
115    }
116
117    /// Returns the effective value of a field, with its default filled in
118    /// when the document omits it, or `None` for a path not in the schema.
119    pub fn value(&self, path: &str) -> Option<&Value> {
120        schema().index_of(path).and_then(|i| self.values.get(i))
121    }
122
123    /// Returns the typed view of the effective configuration.
124    pub fn config(&self) -> &Config {
125        &self.config
126    }
127
128    /// Returns the effective configuration without its secret-reference
129    /// fields, safe to show to anyone who may see the node's status.
130    pub fn public_config(&self) -> PublicConfig {
131        PublicConfig::from_effective(&self.values)
132    }
133
134    /// Returns the SHA-256 hash of the public configuration, as defined on
135    /// [`PublicConfig::hash`].
136    pub fn public_hash(&self) -> PublicHash {
137        self.public_config().hash()
138    }
139}
140
141/// Redacted: shows the typed configuration (whose secret reference is
142/// itself redacted) and the public hash, never the raw text.
143impl fmt::Debug for ConfigDocument {
144    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
145        f.debug_struct("ConfigDocument")
146            .field("config", &self.config)
147            .field("public_hash", &self.public_hash())
148            .finish_non_exhaustive()
149    }
150}
151
152/// Parses TOML, turning a syntax error into a [`ValidationError`].
153///
154/// The message is fixed text plus the line and column of the error. The
155/// parser's own description is deliberately dropped: it can quote the
156/// offending input, which may be a secret-reference value.
157pub(crate) fn parse_toml(text: &str) -> Result<DocumentMut, ValidationError> {
158    text.parse::<DocumentMut>().map_err(|e| {
159        let message = match e.span() {
160            Some(span) => {
161                let (line, column) = line_column(text, span.start);
162                format!("invalid toml at line {line}, column {column}")
163            }
164            None => "invalid toml".to_owned(),
165        };
166        ValidationError::new(ValidationErrorKind::Syntax, None, message)
167    })
168}
169
170/// One-based line and column (in characters) of a byte offset.
171fn line_column(text: &str, offset: usize) -> (usize, usize) {
172    let before = text.get(..offset).unwrap_or(text);
173    let line = before.matches('\n').count() + 1;
174    let column = before.rsplit('\n').next().map_or(0, |l| l.chars().count()) + 1;
175    (line, column)
176}
177
178/// The outcome of checking a syntactically valid document.
179pub(crate) struct Analysis {
180    /// Effective values in schema order: the document's value when it has
181    /// the field's type (even if it breaks a rule), the default when the
182    /// field is absent, and `None` when the document holds the wrong type.
183    pub(crate) values: Vec<Option<Value>>,
184    pub(crate) errors: Vec<ValidationError>,
185}
186
187/// Checks a parsed document against the schema, collecting every error.
188pub(crate) fn analyse(doc: &DocumentMut) -> Analysis {
189    let mut errors = Vec::new();
190    check_schema_version(doc, &mut errors);
191    check_unknown_keys(doc, &mut errors);
192
193    let mut values = Vec::with_capacity(schema().table().len());
194    for field in schema().fields() {
195        let section = doc.get(field.section()).and_then(|i| i.as_table_like());
196        let value = match section.and_then(|t| t.get(field.key())) {
197            None => Some(field.default_value()),
198            Some(item) => match Value::from_toml(item) {
199                Ok(value) => {
200                    if let Err(e) = field.validate(&value) {
201                        errors.push(e);
202                    }
203                    Some(value)
204                }
205                Err(found) => {
206                    errors.push(ValidationError::at(
207                        ValidationErrorKind::WrongType,
208                        field.path(),
209                        format!("expected {}, found {found}", type_name(field)),
210                    ));
211                    None
212                }
213            },
214        };
215        values.push(value);
216    }
217
218    if let Some(e) = check_cross_field(&values, &errors) {
219        errors.push(e);
220    }
221    Analysis { values, errors }
222}
223
224fn type_name(field: &crate::schema::FieldDescriptor) -> &'static str {
225    field.default_value().kind_name()
226}
227
228fn check_schema_version(doc: &DocumentMut, errors: &mut Vec<ValidationError>) {
229    let key = SCHEMA_VERSION_KEY;
230    match doc.get(key) {
231        None => errors.push(ValidationError::new(
232            ValidationErrorKind::MissingSchemaVersion,
233            Some(key),
234            format!("missing; add schema_version = {SCHEMA_VERSION}"),
235        )),
236        Some(item) => match item.as_integer() {
237            Some(v) if v == i64::from(SCHEMA_VERSION) => {}
238            Some(v) => errors.push(ValidationError::at(
239                ValidationErrorKind::UnsupportedSchemaVersion,
240                key,
241                format!("unsupported schema version {v}; this library supports {SCHEMA_VERSION}"),
242            )),
243            None => errors.push(ValidationError::at(
244                ValidationErrorKind::WrongType,
245                key,
246                "expected an integer",
247            )),
248        },
249    }
250}
251
252fn check_unknown_keys(doc: &DocumentMut, errors: &mut Vec<ValidationError>) {
253    for (key, item) in doc.iter() {
254        if key == SCHEMA_VERSION_KEY {
255            continue;
256        }
257        if !schema().sections().any(|s| s == key) {
258            errors.push(ValidationError::at(
259                ValidationErrorKind::UnknownKey,
260                key,
261                "unknown key",
262            ));
263            continue;
264        }
265        let Some(table) = item.as_table_like() else {
266            errors.push(ValidationError::at(
267                ValidationErrorKind::WrongType,
268                key,
269                "expected a table",
270            ));
271            continue;
272        };
273        check_unknown_in_table(key, table, errors);
274    }
275}
276
277fn check_unknown_in_table(section: &str, table: &dyn TableLike, errors: &mut Vec<ValidationError>) {
278    for (key, _) in table.iter() {
279        let path = format!("{section}.{key}");
280        if schema().field(&path).is_none() {
281            errors.push(ValidationError::at(
282                ValidationErrorKind::UnknownKey,
283                &path,
284                "unknown key",
285            ));
286        }
287    }
288}
289
290/// Applies cross-field rules to fields that are individually valid. A field
291/// that already has an error is skipped so it is reported once.
292fn check_cross_field(
293    values: &[Option<Value>],
294    errors: &[ValidationError],
295) -> Option<ValidationError> {
296    let clean = |path: &str| -> Option<&str> {
297        if errors.iter().any(|e| e.path() == Some(path)) {
298            return None;
299        }
300        schema()
301            .index_of(path)
302            .and_then(|i| values.get(i))
303            .and_then(Option::as_ref)
304            .and_then(Value::as_str)
305    };
306    let state = clean("storage.state_dir")?;
307    let backup = clean("storage.backup_dir")?;
308    rules::distinct_dirs(state, backup)
309        .err()
310        .map(|msg| ValidationError::at(ValidationErrorKind::Conflict, "storage.backup_dir", msg))
311}
312
313#[cfg(test)]
314mod tests {
315    use super::*;
316
317    #[test]
318    fn line_column_counts_from_one() {
319        assert_eq!(line_column("ab\ncd", 4), (2, 2), "second line");
320        assert_eq!(line_column("ab", 0), (1, 1), "start");
321    }
322}