1use std::collections::BTreeMap;
22use std::io;
23use std::path::{Path, PathBuf};
24
25use serde::{Deserialize, Deserializer, Serialize, Serializer};
26use tr064::Fingerprint;
27
28use crate::identity::Targets;
29use crate::secrets::command::PasswordCommand;
30
31#[derive(Debug, thiserror::Error)]
33pub enum Error {
34 #[error("cannot read {}", path.display())]
36 Read {
37 path: PathBuf,
39 source: io::Error,
41 },
42 #[error("{} is not a valid configuration", path.display())]
44 Parse {
45 path: PathBuf,
47 source: toml::de::Error,
49 },
50 #[error("cannot write {}", path.display())]
52 Write {
53 path: PathBuf,
55 source: io::Error,
57 },
58 #[error("there is no profile named {0}")]
60 UnknownProfile(String),
61}
62
63#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
65#[serde(deny_unknown_fields)]
66pub struct Config {
67 #[serde(default, skip_serializing_if = "Option::is_none")]
69 pub default_profile: Option<String>,
70 #[serde(
72 default,
73 rename = "profile",
74 skip_serializing_if = "BTreeMap::is_empty"
75 )]
76 pub profiles: BTreeMap<String, Profile>,
77 #[serde(default, skip_serializing_if = "Targets::is_empty")]
79 pub write: Targets,
80}
81
82#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
84#[serde(deny_unknown_fields)]
85pub struct Profile {
86 pub host: String,
89 #[serde(default, skip_serializing_if = "Option::is_none")]
91 pub username: Option<String>,
92 #[serde(
94 default,
95 skip_serializing_if = "Option::is_none",
96 serialize_with = "serialize_fingerprint",
97 deserialize_with = "deserialize_fingerprint"
98 )]
99 pub fingerprint: Option<Fingerprint>,
100 #[serde(default, skip_serializing_if = "Option::is_none")]
103 pub password_command: Option<PasswordCommand>,
104}
105
106#[expect(clippy::ref_option, reason = "the signature serde expects")]
107fn serialize_fingerprint<S: Serializer>(
108 fingerprint: &Option<Fingerprint>,
109 serializer: S,
110) -> Result<S::Ok, S::Error> {
111 fingerprint.map(|f| f.to_string()).serialize(serializer)
112}
113
114fn deserialize_fingerprint<'de, D: Deserializer<'de>>(
115 deserializer: D,
116) -> Result<Option<Fingerprint>, D::Error> {
117 Option::<String>::deserialize(deserializer)?
118 .map(|s| s.parse().map_err(serde::de::Error::custom))
119 .transpose()
120}
121
122impl Config {
123 pub fn default_path() -> Option<PathBuf> {
127 crate::dirs::config().map(|dir| dir.join("config.toml"))
128 }
129
130 pub fn load(path: &Path) -> Result<Self, Error> {
133 let text = match std::fs::read_to_string(path) {
134 Ok(text) => text,
135 Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(Self::default()),
136 Err(source) => {
137 return Err(Error::Read {
138 path: path.to_owned(),
139 source,
140 });
141 }
142 };
143 toml::from_str(&text).map_err(|source| Error::Parse {
144 path: path.to_owned(),
145 source,
146 })
147 }
148
149 pub fn save(&self, path: &Path) -> Result<(), Error> {
152 let write = |source| Error::Write {
153 path: path.to_owned(),
154 source,
155 };
156 let text = toml::to_string(self)
157 .map_err(io::Error::other)
158 .map_err(write)?;
159 std::fs::create_dir_all(path.parent().unwrap_or(Path::new(""))).map_err(write)?;
161 let temporary = path.with_extension("toml.tmp");
162 std::fs::write(&temporary, text).map_err(write)?;
163 std::fs::rename(&temporary, path).map_err(write)
164 }
165
166 pub fn writable_by_others(path: &Path) -> bool {
170 #[cfg(unix)]
171 {
172 use std::os::unix::fs::PermissionsExt as _;
173 std::fs::metadata(path).is_ok_and(|m| m.permissions().mode() & 0o022 != 0)
174 }
175 #[cfg(not(unix))]
176 {
177 let _ = path;
178 false
179 }
180 }
181
182 pub fn profile_name<'a>(&'a self, name: Option<&'a str>) -> Option<&'a str> {
185 name.or(self.default_profile.as_deref())
186 }
187
188 pub fn profile(&self, name: Option<&str>) -> Result<Option<(&str, &Profile)>, Error> {
191 let Some(name) = self.profile_name(name) else {
192 return Ok(None);
193 };
194 self.profiles
195 .get_key_value(name)
196 .map(|(name, profile)| Some((name.as_str(), profile)))
197 .ok_or_else(|| Error::UnknownProfile(name.to_owned()))
198 }
199}
200
201#[cfg(test)]
202mod tests {
203 use super::*;
204 use crate::identity::Identity;
205
206 const FINGERPRINT: &str = "00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF";
207
208 fn home() -> Profile {
209 Profile {
210 host: "192.168.178.1".to_owned(),
211 username: Some("agent".to_owned()),
212 fingerprint: Some(FINGERPRINT.parse().unwrap()),
213 password_command: Some(
214 vec!["pass".to_owned(), "fritz".to_owned()]
215 .try_into()
216 .unwrap(),
217 ),
218 }
219 }
220
221 #[test]
222 fn round_trips_through_a_file() {
223 let dir = tempfile::tempdir().unwrap();
224 let path = dir.path().join("nested/config.toml");
225 let config = Config {
226 default_profile: Some("home".to_owned()),
227 profiles: BTreeMap::from([
228 ("home".to_owned(), home()),
229 (
230 "lab".to_owned(),
231 Profile {
232 host: "lab.example".to_owned(),
233 ..Profile::default()
234 },
235 ),
236 ]),
237 write: Targets {
238 allow: Vec::new(),
239 deny: vec![Identity::of("uuid:home", "1")],
240 },
241 };
242 config.save(&path).unwrap();
243 let text = std::fs::read_to_string(&path).unwrap();
244 assert!(
245 text.contains(&format!("fingerprint = \"{FINGERPRINT}\"")),
246 "{text}"
247 );
248 assert!(text.contains("[write]\ndeny = [\""), "{text}");
249 assert!(
250 text.contains("password_command = [\"pass\", \"fritz\"]"),
251 "{text}"
252 );
253 assert!(!dir.path().join("nested/config.toml.tmp").exists());
254 assert_eq!(Config::load(&path).unwrap(), config);
255 }
256
257 #[test]
258 fn treats_a_missing_file_as_empty() {
259 let dir = tempfile::tempdir().unwrap();
260 let config = Config::load(&dir.path().join("config.toml")).unwrap();
261 assert_eq!(config, Config::default());
262 }
263
264 #[test]
265 fn reports_unreadable_and_invalid_files() {
266 let dir = tempfile::tempdir().unwrap();
267 let error = Config::load(dir.path()).unwrap_err();
268 assert!(matches!(error, Error::Read { .. }), "{error:?}");
269
270 let path = dir.path().join("config.toml");
271 for text in [
272 "[profile.home]\nhost = \"fritz.box\"\nfingerprint = \"00\"\n",
273 "unknown = 1\n",
274 "[write]\nallow = [\"00\"]\n",
275 "[profile.home]\nhost = \"fritz.box\"\npassword_command = []\n",
276 ] {
277 std::fs::write(&path, text).unwrap();
278 let error = Config::load(&path).unwrap_err();
279 assert!(matches!(error, Error::Parse { .. }), "{error:?}");
280 assert_eq!(
281 error.to_string(),
282 format!("{} is not a valid configuration", path.display())
283 );
284 }
285 }
286
287 #[test]
288 fn reports_unwritable_files() {
289 let dir = tempfile::tempdir().unwrap();
290 let file = dir.path().join("file");
291 std::fs::write(&file, "").unwrap();
292 let error = Config::default()
293 .save(&file.join("config.toml"))
294 .unwrap_err();
295 assert!(matches!(error, Error::Write { .. }), "{error:?}");
296 }
297
298 #[test]
299 fn selects_profiles() {
300 let mut config = Config {
301 default_profile: None,
302 profiles: BTreeMap::from([("home".to_owned(), home())]),
303 write: Targets::default(),
304 };
305 assert_eq!(config.profile(None).unwrap(), None);
306 assert_eq!(
307 config.profile(Some("home")).unwrap(),
308 Some(("home", &home()))
309 );
310 let error = config.profile(Some("lab")).unwrap_err();
311 assert_eq!(error.to_string(), "there is no profile named lab");
312
313 config.default_profile = Some("home".to_owned());
314 assert_eq!(config.profile(None).unwrap(), Some(("home", &home())));
315 assert_eq!(config.profile_name(Some("lab")), Some("lab"));
316 }
317
318 #[test]
319 fn tells_whether_others_may_write() {
320 let dir = tempfile::tempdir().unwrap();
321 let path = dir.path().join("config.toml");
322 assert!(!Config::writable_by_others(&path));
323 Config::default().save(&path).unwrap();
324 #[cfg(unix)]
325 {
326 use std::os::unix::fs::PermissionsExt as _;
327 let set = |mode| {
328 std::fs::set_permissions(&path, std::fs::Permissions::from_mode(mode)).unwrap();
329 };
330 set(0o600);
331 assert!(!Config::writable_by_others(&path));
332 set(0o620);
333 assert!(Config::writable_by_others(&path));
334 set(0o602);
335 assert!(Config::writable_by_others(&path));
336 }
337 #[cfg(not(unix))]
338 assert!(!Config::writable_by_others(&path));
339 }
340
341 #[test]
342 fn has_a_default_path() {
343 let path = Config::default_path().unwrap();
344 assert!(path.ends_with("config.toml"), "{}", path.display());
345 }
346}