Skip to main content

subspace_core/settings/
board_fields.rs

1//! Settings a board declares at run time, such as from a web board's
2//! manifest. They live in the board's own config section: values under
3//! `settings` and credentials under `secrets`.
4
5use std::collections::BTreeMap;
6
7use serde_json::{Map, Value};
8
9use super::{SettingsError, TokenEdit};
10
11const VALUES: &str = "settings";
12const SECRETS: &str = "secrets";
13
14/// Changes to one board's own settings.
15#[derive(Clone, Default)]
16pub struct BoardFieldEdits {
17    /// The board's config section, such as `["webBoards", "notes"]`.
18    pub section: Vec<String>,
19    /// A value to write, or `None` to remove the key.
20    pub values: BTreeMap<String, Option<Value>>,
21    pub secrets: BTreeMap<String, TokenEdit>,
22    pub permissions: BTreeMap<String, bool>,
23}
24
25/// The saved values of the board at `section`.
26pub(super) fn values(root: &Map<String, Value>, section: &[String]) -> Map<String, Value> {
27    child(root, section, VALUES).cloned().unwrap_or_default()
28}
29
30/// Whether the board at `section` has a saved secret `key`. The value
31/// itself never leaves the settings file.
32pub(super) fn secret_present(root: &Map<String, Value>, section: &[String], key: &str) -> bool {
33    child(root, section, SECRETS).is_some_and(|secrets| secrets.contains_key(key))
34}
35
36pub(super) fn secret_keys(root: &Map<String, Value>, section: &[String]) -> Vec<String> {
37    child(root, section, SECRETS)
38        .map(|secrets| secrets.keys().cloned().collect())
39        .unwrap_or_default()
40}
41
42pub(super) fn permission(root: &Map<String, Value>, section: &[String], key: &str) -> bool {
43    child(root, section, "permissions")
44        .and_then(|permissions| permissions.get(key))
45        .and_then(Value::as_bool)
46        == Some(true)
47}
48
49fn child<'r>(
50    root: &'r Map<String, Value>,
51    section: &[String],
52    name: &str,
53) -> Option<&'r Map<String, Value>> {
54    let mut object = root;
55    for key in section.iter().map(String::as_str).chain([name]) {
56        object = object.get(key)?.as_object()?;
57    }
58    Some(object)
59}
60
61pub(super) fn validate(edits: &[BoardFieldEdits]) -> Result<(), SettingsError> {
62    let blank = edits.iter().flat_map(|edit| edit.secrets.values()).any(
63        |edit| matches!(edit, TokenEdit::Replace(secret) if secret.expose().trim().is_empty()),
64    );
65    let sectionless = edits.iter().any(|edit| edit.section.is_empty());
66    if blank || sectionless {
67        return Err(SettingsError::Validation {
68            field: "board settings",
69            reason: "a replacement secret cannot be blank",
70        });
71    }
72    Ok(())
73}
74
75/// Apply `edits` to the config file's `root`. The boards must already exist.
76pub(super) fn write(
77    root: &mut Map<String, Value>,
78    edits: &[BoardFieldEdits],
79) -> Result<(), SettingsError> {
80    for edit in edits {
81        let board = object_at(root, &edit.section).ok_or(SettingsError::Validation {
82            field: "board settings",
83            reason: "the board is no longer in the config file",
84        })?;
85        apply(
86            board,
87            VALUES,
88            edit.values.iter().map(|(key, value)| (key, value.clone())),
89        );
90        apply(
91            board,
92            SECRETS,
93            edit.secrets.iter().filter_map(|(key, edit)| match edit {
94                TokenEdit::Keep => None,
95                TokenEdit::Replace(secret) => Some((key, Some(secret.expose().into()))),
96                TokenEdit::Clear => Some((key, None)),
97            }),
98        );
99        apply(
100            board,
101            "permissions",
102            edit.permissions
103                .iter()
104                .map(|(key, on)| (key, Some(Value::Bool(*on)))),
105        );
106    }
107    Ok(())
108}
109
110/// Set or remove keys of `board.name`, leaving out the object once empty.
111fn apply<'k>(
112    board: &mut Map<String, Value>,
113    name: &str,
114    changes: impl Iterator<Item = (&'k String, Option<Value>)>,
115) {
116    let mut object = board
117        .remove(name)
118        .and_then(|value| match value {
119            Value::Object(object) => Some(object),
120            _ => None,
121        })
122        .unwrap_or_default();
123    for (key, change) in changes {
124        match change {
125            Some(value) => object.insert(key.clone(), value),
126            None => object.remove(key),
127        };
128    }
129    if !object.is_empty() {
130        board.insert(name.to_owned(), Value::Object(object));
131    }
132}
133
134fn object_at<'r>(
135    root: &'r mut Map<String, Value>,
136    path: &[String],
137) -> Option<&'r mut Map<String, Value>> {
138    path.iter()
139        .try_fold(root, |object, key| object.get_mut(key)?.as_object_mut())
140}
141
142#[cfg(test)]
143mod tests {
144    use std::collections::BTreeMap;
145
146    use serde_json::{Map, Value, json};
147
148    use super::{BoardFieldEdits, secret_keys, secret_present, validate, values, write};
149    use crate::{Secret, settings::TokenEdit};
150
151    fn root() -> Map<String, Value> {
152        match json!({"webBoards": {"notes": {
153            "path": "/apps/notes",
154            "settings": {"endpoint": "https://old.example", "limit": 3},
155            "secrets": {"token": "old"}
156        }}, "github": {"token": "gh"}})
157        {
158            Value::Object(root) => root,
159            _ => unreachable!(),
160        }
161    }
162
163    fn section() -> Vec<String> {
164        vec!["webBoards".into(), "notes".into()]
165    }
166
167    #[test]
168    fn values_and_secret_presence_are_read_from_the_section() {
169        let root = root();
170        assert_eq!(values(&root, &section())["limit"], json!(3));
171        assert!(secret_present(&root, &section(), "token"));
172        assert!(!secret_present(&root, &section(), "other"));
173        assert!(values(&root, &["webBoards".into(), "missing".into()]).is_empty());
174        assert_eq!(secret_keys(&root, &section()), ["token"]);
175        assert!(secret_keys(&root, &["webBoards".into(), "missing".into()]).is_empty());
176    }
177
178    #[test]
179    fn edits_set_remove_and_keep_values_and_secrets() {
180        let mut root = root();
181        write(
182            &mut root,
183            &[BoardFieldEdits {
184                section: section(),
185                values: BTreeMap::from([
186                    ("endpoint".into(), Some(json!("https://new.example"))),
187                    ("limit".into(), None),
188                    ("compact".into(), Some(json!(true))),
189                ]),
190                secrets: BTreeMap::from([
191                    ("token".into(), TokenEdit::Keep),
192                    ("key".into(), TokenEdit::Replace(Secret::new("k"))),
193                ]),
194                permissions: BTreeMap::new(),
195            }],
196        )
197        .unwrap();
198        let notes = &root["webBoards"]["notes"];
199        assert_eq!(
200            notes["settings"],
201            json!({"endpoint": "https://new.example", "compact": true})
202        );
203        assert_eq!(notes["secrets"], json!({"token": "old", "key": "k"}));
204        assert_eq!(notes["path"], json!("/apps/notes"));
205        assert_eq!(root["github"]["token"], json!("gh"));
206    }
207
208    #[test]
209    fn clearing_the_last_secret_removes_the_object() {
210        let mut root = root();
211        let edit = BoardFieldEdits {
212            section: section(),
213            secrets: BTreeMap::from([("token".into(), TokenEdit::Clear)]),
214            ..Default::default()
215        };
216        write(&mut root, &[edit]).unwrap();
217        assert!(root["webBoards"]["notes"].get("secrets").is_none());
218        let missing = BoardFieldEdits {
219            section: vec!["webBoards".into(), "gone".into()],
220            ..Default::default()
221        };
222        assert!(write(&mut root, &[missing]).is_err());
223    }
224
225    #[test]
226    fn blank_replacement_secrets_are_refused() {
227        let edit = BoardFieldEdits {
228            section: section(),
229            secrets: BTreeMap::from([("token".into(), TokenEdit::Replace(Secret::new(" ")))]),
230            ..Default::default()
231        };
232        assert!(validate(&[edit]).is_err());
233        assert!(validate(&[BoardFieldEdits::default()]).is_err());
234    }
235}