Skip to main content

dort_core/
discovery.rs

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