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`. A nested board section, such
76/// as `webBoards.notes`, must already exist: a board removed meanwhile is
77/// not recreated. A Space's own top-level section, such as `tsxSpaces`, is
78/// created on its first save.
79pub(super) fn write(
80    root: &mut Map<String, Value>,
81    edits: &[BoardFieldEdits],
82) -> Result<(), SettingsError> {
83    for edit in edits {
84        if let [key] = edit.section.as_slice() {
85            root.entry(key.clone())
86                .or_insert_with(|| Value::Object(Map::new()));
87        }
88        let board = object_at(root, &edit.section).ok_or(SettingsError::Validation {
89            field: "board settings",
90            reason: "the board is no longer in the config file",
91        })?;
92        apply(
93            board,
94            VALUES,
95            edit.values.iter().map(|(key, value)| (key, value.clone())),
96        );
97        apply(
98            board,
99            SECRETS,
100            edit.secrets.iter().filter_map(|(key, edit)| match edit {
101                TokenEdit::Keep => None,
102                TokenEdit::Replace(secret) => Some((key, Some(secret.expose().into()))),
103                TokenEdit::Clear => Some((key, None)),
104            }),
105        );
106        apply(
107            board,
108            "permissions",
109            edit.permissions
110                .iter()
111                .map(|(key, on)| (key, Some(Value::Bool(*on)))),
112        );
113    }
114    Ok(())
115}
116
117/// Set or remove keys of `board.name`, leaving out the object once empty.
118fn apply<'k>(
119    board: &mut Map<String, Value>,
120    name: &str,
121    changes: impl Iterator<Item = (&'k String, Option<Value>)>,
122) {
123    let mut object = board
124        .remove(name)
125        .and_then(|value| match value {
126            Value::Object(object) => Some(object),
127            _ => None,
128        })
129        .unwrap_or_default();
130    for (key, change) in changes {
131        match change {
132            Some(value) => object.insert(key.clone(), value),
133            None => object.remove(key),
134        };
135    }
136    if !object.is_empty() {
137        board.insert(name.to_owned(), Value::Object(object));
138    }
139}
140
141fn object_at<'r>(
142    root: &'r mut Map<String, Value>,
143    path: &[String],
144) -> Option<&'r mut Map<String, Value>> {
145    path.iter()
146        .try_fold(root, |object, key| object.get_mut(key)?.as_object_mut())
147}
148
149#[cfg(test)]
150mod tests {
151    use std::collections::BTreeMap;
152
153    use serde_json::{Map, Value, json};
154
155    use super::{BoardFieldEdits, secret_keys, secret_present, validate, values, write};
156    use crate::{Secret, settings::TokenEdit};
157
158    fn root() -> Map<String, Value> {
159        match json!({"webBoards": {"notes": {
160            "path": "/apps/notes",
161            "settings": {"endpoint": "https://old.example", "limit": 3},
162            "secrets": {"token": "old"}
163        }}, "github": {"token": "gh"}})
164        {
165            Value::Object(root) => root,
166            _ => unreachable!(),
167        }
168    }
169
170    fn section() -> Vec<String> {
171        vec!["webBoards".into(), "notes".into()]
172    }
173
174    #[test]
175    fn values_and_secret_presence_are_read_from_the_section() {
176        let root = root();
177        assert_eq!(values(&root, &section())["limit"], json!(3));
178        assert!(secret_present(&root, &section(), "token"));
179        assert!(!secret_present(&root, &section(), "other"));
180        assert!(values(&root, &["webBoards".into(), "missing".into()]).is_empty());
181        assert_eq!(secret_keys(&root, &section()), ["token"]);
182        assert!(secret_keys(&root, &["webBoards".into(), "missing".into()]).is_empty());
183    }
184
185    #[test]
186    fn edits_set_remove_and_keep_values_and_secrets() {
187        let mut root = root();
188        write(
189            &mut root,
190            &[BoardFieldEdits {
191                section: section(),
192                values: BTreeMap::from([
193                    ("endpoint".into(), Some(json!("https://new.example"))),
194                    ("limit".into(), None),
195                    ("compact".into(), Some(json!(true))),
196                ]),
197                secrets: BTreeMap::from([
198                    ("token".into(), TokenEdit::Keep),
199                    ("key".into(), TokenEdit::Replace(Secret::new("k"))),
200                ]),
201                permissions: BTreeMap::new(),
202            }],
203        )
204        .unwrap();
205        let notes = &root["webBoards"]["notes"];
206        assert_eq!(
207            notes["settings"],
208            json!({"endpoint": "https://new.example", "compact": true})
209        );
210        assert_eq!(notes["secrets"], json!({"token": "old", "key": "k"}));
211        assert_eq!(notes["path"], json!("/apps/notes"));
212        assert_eq!(root["github"]["token"], json!("gh"));
213    }
214
215    #[test]
216    fn clearing_the_last_secret_removes_the_object() {
217        let mut root = root();
218        let edit = BoardFieldEdits {
219            section: section(),
220            secrets: BTreeMap::from([("token".into(), TokenEdit::Clear)]),
221            ..Default::default()
222        };
223        write(&mut root, &[edit]).unwrap();
224        assert!(root["webBoards"]["notes"].get("secrets").is_none());
225        let missing = BoardFieldEdits {
226            section: vec!["webBoards".into(), "gone".into()],
227            ..Default::default()
228        };
229        assert!(write(&mut root, &[missing]).is_err());
230    }
231
232    #[test]
233    fn a_top_level_section_is_created_but_a_missing_board_is_refused() {
234        let mut root = root();
235        let edit = |section: Vec<String>| BoardFieldEdits {
236            section,
237            values: BTreeMap::from([("roots".into(), Some(json!("key")))]),
238            ..Default::default()
239        };
240        write(&mut root, &[edit(vec!["tsxSpaces".into()])]).unwrap();
241        assert_eq!(root["tsxSpaces"]["settings"]["roots"], json!("key"));
242        let missing = edit(vec!["webBoards".into(), "missing".into()]);
243        assert!(write(&mut root, &[missing]).is_err());
244        assert!(
245            !root["webBoards"]
246                .as_object()
247                .unwrap()
248                .contains_key("missing")
249        );
250    }
251
252    #[test]
253    fn blank_replacement_secrets_are_refused() {
254        let edit = BoardFieldEdits {
255            section: section(),
256            secrets: BTreeMap::from([("token".into(), TokenEdit::Replace(Secret::new(" ")))]),
257            ..Default::default()
258        };
259        assert!(validate(&[edit]).is_err());
260        assert!(validate(&[BoardFieldEdits::default()]).is_err());
261    }
262}