Skip to main content

fritz_core/
anonymize.rs

1//! Turning raw captures into fixtures that can be published.
2//!
3//! [`anonymize`] replaces personal values with placeholders: addresses,
4//! UUIDs, e-mail addresses and MyFRITZ! names wherever they appear, and the
5//! values of arguments and XML elements whose names point to personal data,
6//! like host names, WLAN names and phone numbers. The same value always gets
7//! the same placeholder, so the answers stay consistent with each other. The
8//! mapping is never stored.
9//!
10//! Before anything is written, the result is searched for every replaced
11//! value and for private patterns, like one's own name or street. If any of
12//! them is still there, nothing is written. [`check`] searches existing
13//! fixtures for values the anonymizer would replace and for private
14//! patterns, and reports where it found them, but never the values.
15
16use std::collections::HashMap;
17use std::fmt;
18use std::fs;
19use std::io;
20use std::path::{Path, PathBuf};
21
22use serde_json::Value;
23
24mod addresses;
25mod leftovers;
26mod mapper;
27mod rules;
28
29use mapper::Mapper;
30
31/// A kind of personal value.
32#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
33pub enum Kind {
34    Mac,
35    Ipv4,
36    Ipv6,
37    Uuid,
38    Email,
39    MyFritz,
40    Device,
41    Wlan,
42    Name,
43    User,
44    Phone,
45    Provider,
46    Server,
47    Url,
48    Id,
49    Serial,
50    Log,
51    /// A line of the private patterns.
52    Private,
53}
54
55impl Kind {
56    /// A short name like `MAC address`.
57    pub fn label(self) -> &'static str {
58        match self {
59            Kind::Mac => "MAC address",
60            Kind::Ipv4 => "IPv4 address",
61            Kind::Ipv6 => "IPv6 address",
62            Kind::Uuid => "UUID",
63            Kind::Email => "e-mail address",
64            Kind::MyFritz => "MyFRITZ! name",
65            Kind::Device => "device name",
66            Kind::Wlan => "WLAN name",
67            Kind::Name => "name",
68            Kind::User => "user name",
69            Kind::Phone => "phone number",
70            Kind::Provider => "provider name",
71            Kind::Server => "server name",
72            Kind::Url => "URL",
73            Kind::Id => "identifier",
74            Kind::Serial => "serial number",
75            Kind::Log => "event log",
76            Kind::Private => "private pattern",
77        }
78    }
79}
80
81impl fmt::Display for Kind {
82    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
83        f.write_str(self.label())
84    }
85}
86
87/// A file that contains a value of a kind it must not contain.
88#[derive(Debug, Clone, PartialEq, Eq)]
89pub struct Finding {
90    /// The path of the file, relative to the directory searched.
91    pub file: PathBuf,
92    pub kind: Kind,
93}
94
95impl fmt::Display for Finding {
96    /// A line like `responses/Hosts1/GetGenericHostEntry@0.json: MAC address`.
97    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
98        write!(f, "{}: {}", self.file.display(), self.kind)
99    }
100}
101
102/// Why anonymizing or checking failed.
103#[derive(Debug, thiserror::Error)]
104pub enum Error {
105    #[error("cannot read or write {}", path.display())]
106    Io {
107        path: PathBuf,
108        #[source]
109        source: io::Error,
110    },
111    #[error("{} is not valid JSON", path.display())]
112    Json {
113        path: PathBuf,
114        #[source]
115        source: serde_json::Error,
116    },
117    /// Replaced values or private patterns are still in the result, which
118    /// was therefore not written.
119    #[error("{} personal values remain after anonymizing", .0.len())]
120    Leftovers(Vec<Finding>),
121}
122
123/// Anonymizes the raw capture in `raw` into the new directory `out` and
124/// returns the number of files written. Lines of `private` are searched for
125/// in the result, regardless of case.
126///
127/// # Errors
128///
129/// [`Error::Leftovers`] when replaced values or private patterns remain,
130/// and the errors of reading, parsing and writing, including when `out`
131/// exists. Nothing is written unless the result is clean.
132pub fn anonymize(raw: &Path, out: &Path, private: &[String]) -> Result<usize, Error> {
133    let files = read_tree(raw)?;
134    let mut mapper = Mapper::new(descriptions(&files, Path::new("")));
135    let files = files
136        .into_iter()
137        .map(|(file, text)| {
138            let anonymized = anonymize_file(&mut mapper, &file, &text, raw)?;
139            Ok((file, anonymized))
140        })
141        .collect::<Result<Vec<_>, Error>>()?;
142    let needles = leftovers::needles(&mapper.replaced, private);
143    let findings = search(&files, &needles);
144    if !findings.is_empty() {
145        return Err(Error::Leftovers(findings));
146    }
147    let io_error = |path: &Path| {
148        let path = path.to_owned();
149        move |source| Error::Io { path, source }
150    };
151    let parent = out.parent().unwrap_or(out);
152    fs::create_dir_all(parent).map_err(io_error(parent))?;
153    fs::create_dir(out).map_err(io_error(out))?;
154    for (file, text) in &files {
155        let path = out.join(file);
156        let parent = path.parent().unwrap_or(out);
157        fs::create_dir_all(parent).map_err(io_error(parent))?;
158        fs::write(&path, text).map_err(io_error(&path))?;
159    }
160    Ok(files.len())
161}
162
163/// Searches the files in `dir` for values the anonymizer would replace and
164/// for lines of `private`, and returns where it found them. `dir` can be
165/// one fixture or a directory with several, like `fixtures/<model>/<fw>/`.
166///
167/// # Errors
168///
169/// The errors of reading and parsing the files.
170pub fn check(dir: &Path, private: &[String]) -> Result<Vec<Finding>, Error> {
171    let needles = leftovers::needles(&[], private);
172    let mut findings = Vec::new();
173    let files = read_tree(dir)?;
174    let mut protocols = HashMap::new();
175    for (file, text) in &files {
176        let root = fixture_root(file);
177        let protocol = protocols
178            .entry(root)
179            .or_insert_with(|| Mapper::new(descriptions(&files, root)));
180        let mut mapper = protocol.fresh();
181        anonymize_file(&mut mapper, file, text, dir)?;
182        let mut kinds: Vec<Kind> = mapper.replaced.iter().map(|(kind, _)| *kind).collect();
183        kinds.extend(leftovers::find(text, &needles));
184        kinds.sort_unstable();
185        kinds.dedup();
186        findings.extend(kinds.into_iter().map(|kind| Finding {
187            file: file.clone(),
188            kind,
189        }));
190    }
191    Ok(findings)
192}
193
194/// Reads private patterns from a file: one text per line, without empty
195/// lines and comments starting with `#`.
196///
197/// # Errors
198///
199/// The errors of reading the file.
200pub fn read_private_patterns(path: &Path) -> io::Result<Vec<String>> {
201    Ok(fs::read_to_string(path)?
202        .lines()
203        .map(str::trim)
204        .filter(|line| !line.is_empty() && !line.starts_with('#'))
205        .map(str::to_owned)
206        .collect())
207}
208
209/// The texts of the service descriptions of the fixture at `root`.
210fn descriptions<'a>(
211    files: &'a [(PathBuf, String)],
212    root: &'a Path,
213) -> impl Iterator<Item = &'a str> {
214    files
215        .iter()
216        .filter(move |(file, _)| is_description(file) && fixture_root(file) == root)
217        .map(|(_, text)| text.as_str())
218}
219
220/// Whether a file is a service description, which lies in `scpd/`.
221fn is_description(file: &Path) -> bool {
222    file.parent().is_some_and(|dir| dir.ends_with("scpd"))
223}
224
225/// The directory of the fixture or capture a file belongs to: the one
226/// above its `scpd/`, `responses/` or `lists/` directory, else its own
227/// directory.
228fn fixture_root(file: &Path) -> &Path {
229    file.ancestors()
230        .skip(1)
231        .find(|dir| {
232            ["scpd", "responses", "lists"]
233                .iter()
234                .any(|d| dir.ends_with(d))
235        })
236        .unwrap_or(file)
237        .parent()
238        .unwrap_or(file)
239}
240
241/// Where the needles are in the files.
242fn search(files: &[(PathBuf, String)], needles: &[leftovers::Needle]) -> Vec<Finding> {
243    files
244        .iter()
245        .flat_map(|(file, text)| {
246            leftovers::find(text, needles)
247                .into_iter()
248                .map(|kind| Finding {
249                    file: file.clone(),
250                    kind,
251                })
252        })
253        .collect()
254}
255
256/// Anonymizes one file of a capture, depending on what it is: the service
257/// descriptions under `scpd/` only describe actions, so only values
258/// anywhere are replaced there. Answers in JSON are replaced by argument
259/// name, and other XML documents by element name.
260fn anonymize_file(
261    mapper: &mut Mapper,
262    file: &Path,
263    text: &str,
264    dir: &Path,
265) -> Result<String, Error> {
266    if is_description(file) {
267        return Ok(mapper.text(text));
268    }
269    match file.extension().and_then(|e| e.to_str()) {
270        Some("json") => {
271            let json_error = |source| Error::Json {
272                path: dir.join(file),
273                source,
274            };
275            let mut value: Value = serde_json::from_str(text).map_err(json_error)?;
276            anonymize_json(mapper, &mut value, None);
277            let mut text = serde_json::to_string_pretty(&value).map_err(json_error)?;
278            text.push('\n');
279            Ok(text)
280        }
281        Some("xml") => Ok(mapper.xml(text)),
282        _ => Ok(mapper.text(text)),
283    }
284}
285
286/// Replaces the strings in a JSON value. `name` is the key of the value in
287/// its object.
288fn anonymize_json(mapper: &mut Mapper, value: &mut Value, name: Option<&str>) {
289    match value {
290        Value::String(text) => {
291            *text = match name {
292                Some(name) => mapper.argument(name, text),
293                None => mapper.text(text),
294            };
295        }
296        Value::Array(items) => {
297            for item in items {
298                anonymize_json(mapper, item, None);
299            }
300        }
301        Value::Object(entries) => {
302            for (key, item) in entries.iter_mut() {
303                anonymize_json(mapper, item, Some(key));
304            }
305        }
306        _ => {}
307    }
308}
309
310/// The text files below `dir`, by path relative to it, sorted. Hidden files
311/// like `.DS_Store` are left out.
312fn read_tree(dir: &Path) -> Result<Vec<(PathBuf, String)>, Error> {
313    let mut files = Vec::new();
314    let mut pending = vec![PathBuf::new()];
315    while let Some(relative) = pending.pop() {
316        // Collecting the components drops the trailing slash of `dir/`.
317        let path: PathBuf = dir.join(&relative).components().collect();
318        let io_error = |source| Error::Io {
319            path: path.clone(),
320            source,
321        };
322        if path.is_dir() {
323            for entry in fs::read_dir(&path).map_err(io_error)? {
324                let name = entry.map_err(io_error)?.file_name();
325                if !name.to_string_lossy().starts_with('.') {
326                    pending.push(relative.join(name));
327                }
328            }
329        } else {
330            files.push((relative, fs::read_to_string(&path).map_err(io_error)?));
331        }
332    }
333    files.sort();
334    Ok(files)
335}