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