Skip to main content

dort_core/
discovery.rs

1//! Bounded discovery under hidden HOME entries.
2use crate::{
3    Result,
4    context::HostContext,
5    observation::{self, Entry, Kind, LinkState},
6};
7use serde::Serialize;
8use std::path::{Path, PathBuf};
9
10const MAX_DEPTH: usize = 8;
11const MAX_ENTRIES: usize = 100_000;
12
13#[derive(Debug, Clone, Serialize)]
14pub struct Candidate {
15    pub entry: Entry,
16    pub link_state: Option<LinkState>,
17    pub supported_for_adoption: bool,
18}
19
20#[derive(Debug, Clone, Serialize)]
21pub struct Discovery {
22    pub candidates: Vec<Candidate>,
23    pub warnings: Vec<String>,
24    pub sensitivity_notice: &'static str,
25}
26
27/// Ephemeral selected-file disclosure. Deliberately not Debug, Clone or Serialize.
28pub struct SelectedContent {
29    text: String,
30    followed: Option<PathBuf>,
31}
32impl SelectedContent {
33    pub fn text(&self) -> &str {
34        &self.text
35    }
36    /// Link target whose content these bytes came from, when preview followed one.
37    pub fn followed(&self) -> Option<&Path> {
38        self.followed.as_deref()
39    }
40}
41
42fn preview(
43    path: &Path,
44    entry: &observation::Entry,
45) -> std::result::Result<SelectedContent, &'static str> {
46    let fp = entry.fingerprint.as_ref().ok_or("File unavailable")?;
47    if fp.mode & 0o7000 != 0 {
48        return Err("Special permission bits; content withheld");
49    }
50    if fp.size < 0 || fp.size > 65536 {
51        return Err("Content withheld: exceeds 64 KiB preview limit");
52    }
53    let handle = observation::parent_handle(path).map_err(|_| "Unsafe parent; content withheld")?;
54    if !same_parents(&handle.parents, &entry.parents) {
55        return Err("Parent changed; content withheld");
56    }
57    let bytes = observation::read_checked_bounded(&handle, path, fp, 65536)
58        .map_err(|_| "File changed or unavailable; content withheld")?;
59    if observation::inspect(path, false).ok().is_none_or(|after| {
60        after.kind != Kind::Regular
61            || after.fingerprint.as_ref() != Some(fp)
62            || !same_parents(&after.parents, &entry.parents)
63    }) {
64        return Err("File or parent changed; content withheld");
65    }
66    let text = std::str::from_utf8(&bytes).map_err(|_| "Binary/non-UTF-8 content withheld")?;
67    if text
68        .chars()
69        .any(|c| c.is_control() && !matches!(c, '\n' | '\r' | '\t' | '\u{1b}'))
70    {
71        return Err("Binary content withheld");
72    }
73    Ok(SelectedContent {
74        text: text.to_owned(),
75        followed: None,
76    })
77}
78
79/// Preview any selected path, following one link so its target content is shown.
80pub fn selected_content_path(
81    host: &HostContext,
82    repository: Option<&Path>,
83    path: &Path,
84) -> std::result::Result<SelectedContent, &'static str> {
85    let _ = (host, repository);
86    let entry =
87        observation::inspect(path, false).map_err(|_| "File unavailable; content withheld")?;
88    match entry.kind {
89        Kind::Regular => preview(path, &entry),
90        Kind::Symlink => {
91            let target =
92                observation::link_path(&entry).ok_or("Unreadable link; content withheld")?;
93            let followed =
94                observation::inspect(&target, false).map_err(|_| "Link target unavailable")?;
95            if followed.kind != Kind::Regular {
96                return Err("Link target is not a regular file");
97            }
98            let mut content = preview(&target, &followed)?;
99            content.followed = Some(target);
100            Ok(content)
101        }
102        Kind::Missing => Err("File missing; content withheld"),
103        _ => Err("Only regular files or links to them can be previewed"),
104    }
105}
106
107/// Only the selected eligible discovery entry may be read. Errors never contain bytes.
108pub fn selected_content(
109    host: &HostContext,
110    repository: Option<&Path>,
111    expected: &Entry,
112) -> std::result::Result<SelectedContent, &'static str> {
113    let path = &expected.path;
114    let relative = path.strip_prefix(&host.home).map_err(|_| "Outside HOME")?;
115    if crate::discovery_ignore::Rules::load(host)
116        .map_err(|_| "Discovery preferences unavailable; content withheld")?
117        .excludes(relative)
118    {
119        return Err("Ignored path; content withheld");
120    }
121    let count = relative.components().count();
122    if count == 0
123        || count > MAX_DEPTH
124        || !relative.as_os_str().as_encoded_bytes().starts_with(b".")
125        || excluded(path, &host.home)
126        || path.starts_with(&host.config_dir)
127        || path.starts_with(&host.state_dir)
128        || host.target_path(path, repository).is_err()
129    {
130        return Err("Protected or excluded path; content withheld");
131    }
132    let current =
133        observation::inspect(path, false).map_err(|_| "File unavailable; content withheld")?;
134    if current.path != expected.path
135        || current.kind != expected.kind
136        || current.fingerprint != expected.fingerprint
137        || current.link_target != expected.link_target
138        || !same_parents(&current.parents, &expected.parents)
139    {
140        return Err("Changed or ineligible file; content withheld");
141    }
142    match current.kind {
143        Kind::Regular => {
144            let fp = current.fingerprint.as_ref().ok_or("File unavailable")?;
145            if fp.links != 1 || fp.uid != rustix::process::geteuid().as_raw() {
146                return Err("Only owned, single-link ordinary files can be previewed");
147            }
148            preview(path, &current)
149        }
150        Kind::Symlink => {
151            let target =
152                observation::link_path(&current).ok_or("Unreadable link; content withheld")?;
153            let followed =
154                observation::inspect(&target, false).map_err(|_| "Link target unavailable")?;
155            if followed.kind != Kind::Regular {
156                return Err("Link target is not a regular file");
157            }
158            let mut content = preview(&target, &followed)?;
159            content.followed = Some(target);
160            Ok(content)
161        }
162        _ => Err("Changed or ineligible file; content withheld"),
163    }
164}
165
166fn same_parents(a: &[observation::Parent], b: &[observation::Parent]) -> bool {
167    // Directory timestamps/size/link counts change when unrelated siblings change;
168    // retain identity, ownership and permissions, as in existing approval guards.
169    a.len() == b.len()
170        && a.iter().zip(b).all(|(a, b)| {
171            let (x, y) = (&a.fingerprint, &b.fingerprint);
172            a.path == b.path
173                && x.device == y.device
174                && x.inode == y.inode
175                && x.mode == y.mode
176                && x.uid == y.uid
177                && x.gid == y.gid
178        })
179}
180
181pub fn discover(host: &HostContext, repository: Option<&Path>) -> Result<Discovery> {
182    let ignores = crate::discovery_ignore::Rules::load(host)?;
183    let mut report = Discovery {
184        candidates: vec![],
185        warnings: vec![],
186        sensitivity_notice: "Metadata-only exclusions are a heuristic, not a guarantee that files contain no secrets. Adoption requires a separate content review.",
187    };
188    let mut remaining = MAX_ENTRIES;
189    walk(
190        &host.home,
191        0,
192        host,
193        repository,
194        &ignores,
195        &mut remaining,
196        &mut report,
197    )?;
198    report
199        .candidates
200        .sort_by(|a, b| a.entry.path.cmp(&b.entry.path));
201    report.warnings.sort();
202    Ok(report)
203}
204
205fn excluded(path: &Path, home: &Path) -> bool {
206    observation::sensitive_path(path)
207        || path
208            .strip_prefix(home)
209            .unwrap_or(path)
210            .components()
211            .any(|part| {
212                let name = part.as_os_str().to_string_lossy().to_ascii_lowercase();
213                [
214                    ".cache",
215                    "cache",
216                    "caches",
217                    ".local",
218                    ".git",
219                    ".cargo",
220                    ".rustup",
221                    ".npm",
222                    "node_modules",
223                    "target",
224                    "dist",
225                    "build",
226                    "logs",
227                    "history",
228                    ".zsh_history",
229                    ".bash_history",
230                    ".docker",
231                    "google",
232                    "chromium",
233                    "chrome",
234                    "firefox",
235                    "bravesoftware",
236                    "microsoft-edge",
237                    "opera",
238                    "vivaldi",
239                    "librewolf",
240                    "safari",
241                    ".mozilla",
242                    ".vscode",
243                    "browser",
244                    "browsers",
245                    "keyring",
246                    "keyrings",
247                    ".ds_store",
248                    "generated",
249                    "__pycache__",
250                    ".venv",
251                    "venv",
252                    "tmp",
253                    "temp",
254                ]
255                .contains(&name.as_str())
256            })
257}
258
259fn walk(
260    root: &Path,
261    depth: usize,
262    host: &HostContext,
263    repository: Option<&Path>,
264    ignores: &crate::discovery_ignore::Rules,
265    remaining: &mut usize,
266    report: &mut Discovery,
267) -> Result<()> {
268    for name in observation::names(root, MAX_ENTRIES)? {
269        if *remaining == 0 {
270            return Err(crate::Error::Invalid(
271                "discovery entry limit exceeded".into(),
272            ));
273        }
274        *remaining -= 1;
275        if depth == 0 && !name.as_encoded_bytes().starts_with(b".") {
276            continue;
277        }
278        let path: PathBuf = root.join(name);
279        if ignores.excludes(path.strip_prefix(&host.home).expect("discovery under HOME"))
280            || excluded(&path, &host.home)
281            || path.starts_with(&host.config_dir)
282            || path.starts_with(&host.state_dir)
283            || repository.is_some_and(|repo| path.starts_with(repo))
284        {
285            continue;
286        }
287        let protected_container = host.target_path(&path, repository).is_err();
288        observation::validate_output_path(&path)?;
289        let entry = match observation::inspect(&path, false) {
290            Ok(entry) => entry,
291            Err(error) => {
292                report.warnings.push(error.to_string());
293                continue;
294            }
295        };
296        let recurse = entry.kind == Kind::Directory && depth + 1 < MAX_DEPTH;
297        let link_state = if entry.kind == Kind::Symlink {
298            Some(observation::link_state(&entry)?)
299        } else {
300            None
301        };
302        let supported_for_adoption = entry.kind == Kind::Regular
303            && entry.fingerprint.as_ref().is_some_and(|f| {
304                f.links == 1 && f.uid == rustix::process::geteuid().as_raw() && f.mode & 0o7000 == 0
305            });
306        if !protected_container {
307            report.candidates.push(Candidate {
308                entry,
309                link_state,
310                supported_for_adoption,
311            });
312        }
313        if recurse {
314            // A substituted parent is refused by the next descriptor walk, never traversed.
315            if let Err(error) = walk(
316                &path,
317                depth + 1,
318                host,
319                repository,
320                ignores,
321                remaining,
322                report,
323            ) {
324                report.warnings.push(error.to_string());
325            }
326        }
327    }
328    Ok(())
329}
330
331#[cfg(test)]
332mod tests {
333    use super::*;
334    use crate::platform::{Architecture, Platform};
335
336    #[test]
337    fn larger_scan_still_enforces_directory_and_shared_recursive_budgets() {
338        let sandbox = tempfile::tempdir().unwrap();
339        let home = sandbox.path().canonicalize().unwrap().join("home");
340        for directory in [".a", ".b"] {
341            std::fs::create_dir_all(home.join(directory)).unwrap();
342            std::fs::write(home.join(directory).join("settings"), "ordinary settings").unwrap();
343        }
344        let host =
345            HostContext::new(home, None, None, Platform::Linux, Architecture::X86_64).unwrap();
346        let mut report = discover(&host, None).unwrap();
347        assert_eq!(report.candidates.len(), 4);
348        report.candidates.clear();
349        // Exercise exhaustion with a small shared budget, not 100,001 fixture files.
350        let mut remaining = 3;
351        walk(
352            &host.home,
353            0,
354            &host,
355            None,
356            &crate::discovery_ignore::Rules::default(),
357            &mut remaining,
358            &mut report,
359        )
360        .unwrap();
361        assert_eq!(remaining, 0);
362        assert_eq!(report.candidates.len(), 3);
363        assert!(
364            report
365                .warnings
366                .iter()
367                .any(|warning| warning.contains("limit"))
368        );
369        // The descriptor-relative directory reader independently enforces its cap.
370        assert!(observation::names(&host.home, 1).is_err());
371        assert_eq!(observation::names(&host.home, 2).unwrap().len(), 2);
372    }
373}