1use std::collections::BTreeMap;
10
11use serde::Serialize;
12use serde_json::{Map, Value};
13
14use crate::names::{Sensitivity, sensitivity};
15use crate::redact::{self, HIDDEN};
16use crate::session::{Error, Session};
17
18pub const PREFIX: &str = "/api/v0/generic/";
20
21pub const MODULES: &[(&str, &str, bool)] = &[
24 (
25 "box",
26 "name, LEDs, night time, UPnP and DHCP lease times",
27 true,
28 ),
29 (
30 "connections",
31 "internet connections, with IPv4 and IPv6 DNS",
32 true,
33 ),
34 ("dnscfg", "DNS servers and DNS over TLS", true),
35 (
36 "dns_excepted_domains",
37 "domains excepted from DNS rebind protection",
38 true,
39 ),
40 (
41 "eth_ports",
42 "LAN ports, their speed and energy saving",
43 true,
44 ),
45 ("forwardrules", "whether a host is exposed", true),
46 ("ipv6", "IPv6 of the home network, MTU and DHCPv6", true),
47 (
48 MESH,
49 "whether mesh devices choose the best connection themselves, and the role in the mesh",
50 true,
51 ),
52 ("route", "static IPv4 routes", true),
53 (
54 "sync_groups",
55 "IPv4 and IPv6 modes of the internet connection",
56 true,
57 ),
58 ("time", "time server and time zone", true),
59 ("dect", "DECT and its handsets", false),
60 (
61 "filter_profile",
62 "access profiles of the parental controls",
63 false,
64 ),
65 (
66 "inetstat",
67 "online counter: traffic by day, week and month",
68 false,
69 ),
70 ("landevice", "hosts of the home network", false),
71 ("mobiled", "mobile modem", false),
72 ("plc", "powerline energy saving", false),
73 ("tam", "answering machines", false),
74 ("user", "users of the parental controls", false),
75 ("vpn", "VPN connections", false),
76 ("wlan", "wireless networks and their clients", false),
77];
78
79pub const MESH: &str = "mesh";
82
83pub const MESH_FIELDS: &[(&str, &[&str])] = &[
87 ("wlan", &["backhaul_steering"]),
88 ("nexus", &["role", "is_master"]),
89];
90
91#[derive(Debug, Default, Serialize)]
93pub struct Settings {
94 pub modules: BTreeMap<String, Value>,
96 #[serde(skip_serializing_if = "BTreeMap::is_empty")]
98 pub unavailable: BTreeMap<String, String>,
99}
100
101pub async fn settings(session: &Session, modules: &[String]) -> Settings {
104 let defaults: Vec<String> = MODULES
105 .iter()
106 .filter(|(_, _, default)| *default)
107 .map(|(name, _, _)| (*name).to_owned())
108 .collect();
109 let modules = if modules.is_empty() {
110 &defaults
111 } else {
112 modules
113 };
114 let mut settings = Settings::default();
115 for name in modules {
116 let value = if name == MESH {
117 mesh(session).await
118 } else {
119 module(session, name).await
120 };
121 match value {
122 Ok(value) => {
123 settings.modules.insert(name.clone(), value);
124 }
125 Err(e) => {
126 settings.unavailable.insert(name.clone(), e.to_string());
127 }
128 }
129 }
130 settings
131}
132
133pub async fn module(session: &Session, name: &str) -> Result<Value, Error> {
140 let valid = !name.is_empty()
141 && name
142 .chars()
143 .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_');
144 if !valid {
145 return Err(Error::Invalid {
146 what: "the module name",
147 reason: format!("{name:?} is not a module"),
148 });
149 }
150 parse(&session.get(&format!("{PREFIX}{name}")).await?)
151}
152
153pub async fn mesh(session: &Session) -> Result<Value, Error> {
160 let mut modules = Vec::new();
161 let mut first = None;
162 for (name, _) in MESH_FIELDS {
163 match module(session, name).await {
164 Ok(value) => modules.push((*name, value)),
165 Err(e) => {
166 first.get_or_insert(e);
167 }
168 }
169 }
170 match first {
171 Some(e) if modules.is_empty() => Err(e),
172 _ => Ok(mesh_of(&modules)),
173 }
174}
175
176fn mesh_of(modules: &[(&str, Value)]) -> Value {
178 let mut mesh = Map::new();
179 for (name, value) in modules {
180 let fields = MESH_FIELDS
181 .iter()
182 .filter(|(module, _)| module == name)
183 .flat_map(|(_, fields)| fields.iter());
184 for field in fields {
185 if let Some(found) = value.get(field) {
186 mesh.insert((*field).to_owned(), found.clone());
187 }
188 }
189 }
190 Value::Object(mesh)
191}
192
193pub fn parse(json: &str) -> Result<Value, Error> {
199 let value = serde_json::from_str(json).map_err(|e| Error::Invalid {
200 what: "the settings API",
201 reason: e.to_string(),
202 })?;
203 Ok(hide(value))
204}
205
206pub fn hide(value: Value) -> Value {
210 match value {
211 Value::Object(object) => Value::Object(
212 object
213 .into_iter()
214 .map(|(name, value)| {
215 let value = if secret(&name) {
216 Value::String(HIDDEN.to_owned())
217 } else {
218 hide(value)
219 };
220 (name, value)
221 })
222 .collect(),
223 ),
224 Value::Array(items) => Value::Array(items.into_iter().map(hide).collect()),
225 Value::String(text) if PRIVATE.iter().any(|p| text.contains(p)) => {
226 Value::String(HIDDEN.to_owned())
227 }
228 Value::String(text) => Value::String(redact::value("", &text)),
229 other => other,
230 }
231}
232
233const SECRET_PARTS: &[&str] = &["psk", "passw", "secret", "privatekey", "private_key"];
236
237const PRIVATE: &[&str] = &["PrivateKey", "PRIVATE KEY"];
239
240fn secret(name: &str) -> bool {
244 let lower = name.to_ascii_lowercase();
245 sensitivity(name) != Sensitivity::Plain
246 || SECRET_PARTS.iter().any(|part| lower.contains(part))
247 || (lower.starts_with("wg_") && lower.ends_with("config"))
248}
249
250#[cfg(test)]
251mod tests {
252 use serde_json::json;
253
254 use super::*;
255
256 #[test]
257 fn hides_secrets_at_any_depth() {
258 let value = json!({
259 "name": "box",
260 "password": "secret",
261 "accounts": [{"username": "user", "psk": {"value": "key"}, "pin_enabled": "1"}],
262 "url": "/x.lua?sid=0123",
263 "mtu": 1492,
264 "pskvalue": "wlan key",
265 "guest_pskvalue": "guest key",
266 "wg_slave_config": "[Interface]",
267 "dns_domains": "[Interface]\nPrivateKey = abc",
268 "ip4_is_private": "1",
269 });
270 assert_eq!(
271 hide(value),
272 json!({
273 "name": "box",
274 "password": "***",
275 "accounts": [{"username": "***", "psk": "***", "pin_enabled": "1"}],
276 "url": "/x.lua?sid=***",
277 "mtu": 1492,
278 "pskvalue": "***",
279 "guest_pskvalue": "***",
280 "wg_slave_config": "***",
281 "dns_domains": "***",
282 "ip4_is_private": "1",
283 })
284 );
285 }
286
287 #[test]
288 fn puts_the_mesh_together() {
289 let modules = [
290 (
291 "wlan",
292 json!({"backhaul_steering": "1", "pskvalue": "***", "ssid": "wlan-1"}),
293 ),
294 (
295 "nexus",
296 json!({"role": "auto", "is_master": "1", "peers": []}),
297 ),
298 ];
299 assert_eq!(
300 mesh_of(&modules),
301 json!({"backhaul_steering": "1", "role": "auto", "is_master": "1"})
302 );
303 assert_eq!(
305 mesh_of(&modules[1..]),
306 json!({"role": "auto", "is_master": "1"})
307 );
308 }
309
310 #[test]
311 fn rejects_invalid_json() {
312 assert!(matches!(parse("<html>"), Err(Error::Invalid { .. })));
313 }
314}