Skip to main content

stratum_node_config/
public.rs

1//! The public view of the effective configuration and its hash.
2
3use std::fmt;
4use std::fmt::Write as _;
5
6use serde::ser::{Serialize, SerializeMap, Serializer};
7use sha2::{Digest, Sha256};
8
9use crate::document::SCHEMA_VERSION_KEY;
10use crate::schema::{schema, SCHEMA_VERSION};
11use crate::value::Value;
12
13/// The version of the public-configuration hash format.
14///
15/// It is mixed into every hash as the prefix line
16/// `stratum.public-config.v1`, so a change to the encoding can never produce
17/// a hash that collides with one made under an earlier format.
18pub const PUBLIC_HASH_VERSION: u32 = 1;
19
20/// The effective configuration with every secret-reference field removed.
21///
22/// Entries are held in byte order of their dotted paths. Serialises as a
23/// JSON object whose first key is `schema_version`, followed by each dotted
24/// path mapped to its value, so a client can recompute
25/// [`PublicConfig::hash`] from the JSON alone.
26///
27/// # Examples
28///
29/// ```
30/// use stratum_node_config::{schema, ConfigDocument, Value};
31///
32/// let doc = ConfigDocument::parse(&schema().seed_text())?;
33/// let public = doc.public_config();
34/// assert_eq!(public.get("listen.address"), Some(&Value::from("127.0.0.1:7460")));
35/// assert_eq!(public.get("secrets.pod_admin_key_ref"), None);
36/// # Ok::<(), Box<dyn std::error::Error>>(())
37/// ```
38#[derive(Debug, Clone, PartialEq, Eq)]
39pub struct PublicConfig {
40    entries: Vec<(&'static str, Value)>,
41}
42
43impl PublicConfig {
44    /// Builds the public view from effective values in schema order.
45    pub(crate) fn from_effective(values: &[Value]) -> Self {
46        let mut entries: Vec<(&'static str, Value)> = schema()
47            .fields()
48            .zip(values)
49            .filter(|(field, _)| !field.is_secret_ref())
50            .map(|(field, value)| (field.path(), value.clone()))
51            .collect();
52        entries.sort_by(|a, b| a.0.as_bytes().cmp(b.0.as_bytes()));
53        Self { entries }
54    }
55
56    /// Returns the value at a dotted path, or `None` for secret-reference
57    /// fields and paths not in the schema.
58    pub fn get(&self, path: &str) -> Option<&Value> {
59        self.entries
60            .iter()
61            .find(|(p, _)| *p == path)
62            .map(|(_, v)| v)
63    }
64
65    /// Iterates over `(path, value)` pairs in byte order of the path.
66    pub fn iter(&self) -> PublicIter<'_> {
67        PublicIter {
68            inner: self.entries.iter(),
69        }
70    }
71
72    /// Returns the number of fields in the public view.
73    pub fn len(&self) -> usize {
74        self.entries.len()
75    }
76
77    /// Returns `true` if the public view has no fields.
78    pub fn is_empty(&self) -> bool {
79        self.entries.is_empty()
80    }
81
82    /// Returns the canonical TOML text the hash is computed over.
83    ///
84    /// The text is valid TOML. Its first line is
85    /// `schema_version = <SCHEMA_VERSION>`. Every public field follows, one
86    /// per line, as `<dotted.path> = <value>\n`, in byte order of the path.
87    /// Values use a fixed encoding that does not depend on any TOML library:
88    /// booleans are `true`/`false`; integers are decimal with a leading `-`
89    /// when negative; strings are double-quoted with `"` and `\`
90    /// backslash-escaped and every ASCII control character written as
91    /// `\uXXXX` in upper-case hex, all other characters as literal UTF-8;
92    /// lists are `[`, the encoded strings separated by `", "`, then `]`.
93    /// Because no encoded value contains a raw newline and every string is
94    /// delimited and escaped, distinct configurations give distinct texts.
95    ///
96    /// # Examples
97    ///
98    /// ```
99    /// use stratum_node_config::{schema, ConfigDocument};
100    ///
101    /// let doc = ConfigDocument::parse(&schema().seed_text())?;
102    /// let text = doc.public_config().canonical_text();
103    /// assert!(text.starts_with("schema_version = 1\nbackup.age_recipients = []\n"));
104    /// # Ok::<(), Box<dyn std::error::Error>>(())
105    /// ```
106    pub fn canonical_text(&self) -> String {
107        let mut out = format!("{SCHEMA_VERSION_KEY} = {SCHEMA_VERSION}\n");
108        for (path, value) in &self.entries {
109            out.push_str(path);
110            out.push_str(" = ");
111            value.write_canonical(&mut out);
112            out.push('\n');
113        }
114        out
115    }
116
117    /// Returns the public-configuration hash.
118    ///
119    /// The hash is `SHA-256("stratum.public-config.v1\n" ‖ canonical_text)`,
120    /// where the prefix carries [`PUBLIC_HASH_VERSION`] and `canonical_text`
121    /// is [`PublicConfig::canonical_text`] encoded as UTF-8. Changing a
122    /// secret reference never changes it; changing any other field's
123    /// effective value, the schema version, or a default that a document
124    /// relies on always does.
125    pub fn hash(&self) -> PublicHash {
126        let mut hasher = Sha256::new();
127        hasher.update(format!("stratum.public-config.v{PUBLIC_HASH_VERSION}\n").as_bytes());
128        hasher.update(self.canonical_text().as_bytes());
129        PublicHash(hasher.finalize().into())
130    }
131}
132
133impl Serialize for PublicConfig {
134    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
135        let mut map = serializer.serialize_map(Some(self.entries.len() + 1))?;
136        map.serialize_entry(SCHEMA_VERSION_KEY, &SCHEMA_VERSION)?;
137        for (path, value) in &self.entries {
138            map.serialize_entry(path, value)?;
139        }
140        map.end()
141    }
142}
143
144impl<'a> IntoIterator for &'a PublicConfig {
145    type Item = (&'static str, &'a Value);
146    type IntoIter = PublicIter<'a>;
147
148    fn into_iter(self) -> Self::IntoIter {
149        self.iter()
150    }
151}
152
153/// Iterator over a [`PublicConfig`]'s `(path, value)` pairs, returned by
154/// [`PublicConfig::iter`].
155#[derive(Debug, Clone)]
156pub struct PublicIter<'a> {
157    inner: std::slice::Iter<'a, (&'static str, Value)>,
158}
159
160impl<'a> Iterator for PublicIter<'a> {
161    type Item = (&'static str, &'a Value);
162
163    fn next(&mut self) -> Option<Self::Item> {
164        self.inner.next().map(|(p, v)| (*p, v))
165    }
166
167    fn size_hint(&self) -> (usize, Option<usize>) {
168        self.inner.size_hint()
169    }
170}
171
172impl ExactSizeIterator for PublicIter<'_> {}
173
174impl std::iter::FusedIterator for PublicIter<'_> {}
175
176/// A SHA-256 public-configuration hash, from [`PublicConfig::hash`].
177///
178/// `Display` and `Serialize` give 64 lowercase hex digits.
179#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
180pub struct PublicHash([u8; 32]);
181
182impl PublicHash {
183    /// Returns the raw 32 digest bytes.
184    pub fn as_bytes(&self) -> &[u8; 32] {
185        &self.0
186    }
187
188    /// Returns the hash as 64 lowercase hex digits.
189    pub fn to_hex(&self) -> String {
190        let mut s = String::with_capacity(64);
191        for b in self.0 {
192            // Writing to a String cannot fail.
193            let _ = write!(s, "{b:02x}");
194        }
195        s
196    }
197}
198
199impl fmt::Display for PublicHash {
200    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
201        f.write_str(&self.to_hex())
202    }
203}
204
205impl fmt::Debug for PublicHash {
206    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
207        write!(f, "PublicHash({})", self.to_hex())
208    }
209}
210
211impl Serialize for PublicHash {
212    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
213        serializer.serialize_str(&self.to_hex())
214    }
215}