dort-core 0.2.0

UI-independent planning and guarded filesystem services for Dort
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
//! Package-manager checks. Passive reads and planning do not call them.
//! Checks can run configuration and plugin code and change caches.
use crate::model::Provider;
use serde::{Deserialize, Serialize};
use std::{
    io::Read,
    os::unix::process::CommandExt,
    path::{Component, Path, PathBuf},
    process::{Command, Stdio},
    thread,
    time::{Duration, Instant},
};

mod catalog;
mod npm_discovery;

const LIMIT: usize = 4 * 1024 * 1024;
const TIMEOUT: Duration = Duration::from_secs(10);
pub const WARNING: &str = "Runs a local package-manager program. It can run configuration and plugin code, and change caches or logs. No packages are installed. Results are what the package manager reports; Dort does not verify ownership or command identity.";

/// Fixed provider inventory protocols.
/// Managed npm checks require an explicit runtime/Node/CLI/prefix binding.
/// Standalone npm inventory has a separate read-only PATH-based capability.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Query {
    BrewFormulae,
    NpmGlobals,
}
impl Query {
    pub fn provider(self) -> Provider {
        match self {
            Self::BrewFormulae => Provider::Brew,
            Self::NpmGlobals => Provider::Npm,
        }
    }
    fn arguments(self) -> Vec<String> {
        let args: &[&str] = match self {
            Self::BrewFormulae => &["info", "--json=v2", "--installed", "--formula"],
            Self::NpmGlobals => &[
                "ls",
                "--global",
                "--json",
                "--depth=0",
                "--offline",
                "--ignore-scripts",
                "--logs-max=0",
                "--update-notifier=false",
                "--audit=false",
                "--fund=false",
            ],
        };
        args.iter().map(|s| (*s).to_owned()).collect()
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, thiserror::Error)]
#[serde(rename_all = "snake_case")]
pub enum Failure {
    #[error("inspection requires absolute UTF-8 paths without dot components")]
    InvalidPath,
    #[error("inspection requires an explicit nonempty trusted executable search path")]
    InvalidSearchPath,
    #[error(
        "npm inspection requires an explicit declared runtime, Node, npm CLI and prefix binding"
    )]
    InvalidNpmBinding,
    #[error("provider executable unavailable or could not start")]
    Unavailable,
    #[error("provider pipe setup/read failed")]
    Pipe,
    #[error("provider wait failed")]
    Wait,
    #[error("provider query exceeded time limit")]
    Timeout,
    #[error("provider query exceeded output limit")]
    OutputLimit,
    #[error("provider query failed; raw output withheld")]
    QueryFailed,
    #[error("provider returned malformed or unsupported metadata; raw output withheld")]
    Malformed,
    #[error("package database contains incomplete or repair-required packages")]
    IncompletePackages,
}

/// Whitelisted metadata only. No raw stdout/stderr, configuration or environment values.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Installation {
    /// Provider-reported identifier, not inferred from a binary name.
    pub package: String,
    pub version: String,
}

/// A failed observation is never represented as a healthy empty catalog.
#[derive(Debug, Serialize)]
#[serde(tag = "state", rename_all = "snake_case")]
pub enum Observation {
    Complete { installations: Vec<Installation> },
    Unavailable { reason: Failure },
}
#[derive(Debug, Serialize)]
pub struct Report {
    pub description: Description,
    pub observation: Observation,
}
/// Explicit caller-selected scope, not proof that Node is installed/owned by Dort.
/// The npm launcher is never run: the selected Node executes the selected CLI script.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct NpmBinding {
    pub runtime_tool: String,
    pub node: PathBuf,
    pub npm_cli: PathBuf,
    pub prefix: PathBuf,
}

/// Inspectable description; deserializing a report never grants execution authority.
#[derive(Debug, Clone, Serialize)]
pub struct Description {
    pub query: Query,
    pub executable: PathBuf,
    pub arguments: Vec<String>,
    pub working_directory: &'static str,
    pub home: PathBuf,
    pub trusted_search_path: Vec<PathBuf>,
    pub npm_binding: Option<NpmBinding>,
    /// Reported global prefix for standalone inventory, never a runtime binding.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub npm_global_prefix: Option<PathBuf>,
    pub warning: &'static str,
    pub output_limit_bytes: usize,
    pub timeout_seconds: u64,
}
/// An in-memory capability with fixed arguments and no arbitrary environment/command API.
/// Constructing/describing it does not discover paths, read files or start a process.
pub struct Preview {
    description: Description,
    prefix_probe: Option<Description>,
}
/// Single-use authority, deliberately not Clone/Debug/Serialize/Deserialize.
pub struct Approval(Preview);

pub(super) fn absolute(path: &Path) -> bool {
    path.is_absolute()
        && path.to_str().is_some()
        && path.components().all(|c| matches!(c, Component::RootDir | Component::Normal(_)))
        && !path.as_os_str().as_encoded_bytes().contains(&0)
        // Path::components normalizes interior '.'; reject it in the supplied spelling too.
        && !path.to_str().unwrap_or("").split('/').any(|c| c == "." || c == "..")
}
impl Preview {
    /// All paths are explicit application-boundary trust decisions, never manifest strings.
    /// The query runs at /, not in a repository. The caller must not probe PATH candidates
    /// to decide whether they are trustworthy. No trust is persisted here.
    pub fn new(
        query: Query,
        executable: PathBuf,
        home: PathBuf,
        trusted_search_path: Vec<PathBuf>,
    ) -> Result<Self, Failure> {
        if query == Query::NpmGlobals {
            return Err(Failure::InvalidNpmBinding);
        }
        Self::with_binding(query, executable, home, trusted_search_path, None)
    }
    /// Standalone inventory through a trusted npm program from the application PATH.
    /// Approval covers prefix discovery and a global list scoped to that reported prefix.
    /// It grants no declared-runtime or installation authority.
    pub fn npm_inventory(
        executable: PathBuf,
        home: PathBuf,
        trusted_search_path: Vec<PathBuf>,
    ) -> Result<Self, Failure> {
        let mut preview = Self::with_binding(
            Query::NpmGlobals,
            executable,
            home,
            trusted_search_path,
            None,
        )?;
        preview.description.warning = npm_discovery::WARNING;
        let mut probe = preview.description.clone();
        probe.arguments = npm_discovery::prefix_arguments();
        probe.output_limit_bytes = npm_discovery::PREFIX_LIMIT;
        preview.prefix_probe = Some(probe);
        Ok(preview)
    }
    /// The binding must name a runtime declared in this manifest. No version,
    /// executable identity or installed-runtime association is inferred from it.
    pub fn npm(
        manifest: &crate::Manifest,
        binding: NpmBinding,
        home: PathBuf,
        trusted_search_path: Vec<PathBuf>,
    ) -> Result<Self, Failure> {
        if !manifest.tools.iter().any(|t| t.id == binding.runtime_tool) {
            return Err(Failure::InvalidNpmBinding);
        }
        Self::npm_probe(binding, home, trusted_search_path)
    }
    /// Historical metadata inspection only. Does not assert a current declaration,
    /// runtime satisfaction or installation eligibility. Never an install capability.
    pub(crate) fn npm_probe(
        binding: NpmBinding,
        home: PathBuf,
        trusted_search_path: Vec<PathBuf>,
    ) -> Result<Self, Failure> {
        if binding.runtime_tool.is_empty()
            || binding.runtime_tool.len() > 256
            || !binding
                .runtime_tool
                .bytes()
                .all(|b| b.is_ascii_alphanumeric() || b"._-".contains(&b))
        {
            return Err(Failure::InvalidNpmBinding);
        }
        if !absolute(&binding.node) || !absolute(&binding.npm_cli) || !absolute(&binding.prefix) {
            return Err(Failure::InvalidPath);
        }
        Self::with_binding(
            Query::NpmGlobals,
            binding.node.clone(),
            home,
            trusted_search_path,
            Some(binding),
        )
    }
    fn with_binding(
        query: Query,
        executable: PathBuf,
        home: PathBuf,
        trusted_search_path: Vec<PathBuf>,
        npm_binding: Option<NpmBinding>,
    ) -> Result<Self, Failure> {
        if !absolute(&executable) || !absolute(&home) {
            return Err(Failure::InvalidPath);
        }
        if trusted_search_path.is_empty()
            || trusted_search_path.iter().any(|p| !absolute(p))
            || std::env::join_paths(&trusted_search_path).is_err()
        {
            return Err(Failure::InvalidSearchPath);
        }
        let mut arguments = query.arguments();
        if let Some(binding) = &npm_binding {
            arguments.insert(
                0,
                binding
                    .npm_cli
                    .to_str()
                    .ok_or(Failure::InvalidPath)?
                    .to_owned(),
            );
            arguments.push("--prefix".into());
            arguments.push(
                binding
                    .prefix
                    .to_str()
                    .ok_or(Failure::InvalidPath)?
                    .to_owned(),
            );
        }
        Ok(Self {
            prefix_probe: None,
            description: Description {
                query,
                executable,
                arguments,
                working_directory: "/",
                home,
                trusted_search_path,
                npm_binding,
                npm_global_prefix: None,
                warning: WARNING,
                output_limit_bytes: LIMIT,
                timeout_seconds: TIMEOUT.as_secs(),
            },
        })
    }
    pub fn description(&self) -> &Description {
        &self.description
    }
    pub fn prefix_probe(&self) -> Option<&Description> {
        self.prefix_probe.as_ref()
    }
    /// Presentation calls this only after deliberate approval of this exact live preview.
    /// This is inspection authority only, never installation/mutation approval.
    pub fn approve(self) -> Approval {
        Approval(self)
    }
}
impl Approval {
    pub fn inspect(self) -> Report {
        let Preview {
            mut description,
            prefix_probe,
        } = self.0;
        let result = if let Some(probe) = prefix_probe {
            npm_discovery::inspect(&probe, &mut description)
        } else {
            run_bounded(command(&description), LIMIT, TIMEOUT)
                .and_then(|bytes| catalog::parse(description.query, &bytes))
        };
        Report {
            description,
            observation: match result {
                Ok(installations) => Observation::Complete { installations },
                Err(reason) => Observation::Unavailable { reason },
            },
        }
    }
}
fn command(d: &Description) -> Command {
    let mut command = Command::new(&d.executable);
    command
        .env_clear()
        .env("HOME", &d.home)
        .env("XDG_CONFIG_HOME", d.home.join(".config"))
        .env("XDG_CACHE_HOME", d.home.join(".cache"))
        .env("XDG_DATA_HOME", d.home.join(".local/share"))
        .env("XDG_STATE_HOME", d.home.join(".local/state"))
        .env(
            "PATH",
            std::env::join_paths(&d.trusted_search_path).expect("validated search path"),
        )
        .env("LC_ALL", "C")
        .env("LANG", "C")
        .env("NO_COLOR", "1")
        .current_dir(d.working_directory)
        .args(&d.arguments);
    match d.query {
        Query::BrewFormulae => {
            command
                .env("HOMEBREW_NO_AUTO_UPDATE", "1")
                .env("HOMEBREW_NO_ANALYTICS", "1")
                .env("HOMEBREW_NO_ENV_HINTS", "1")
                .env("HOMEBREW_NO_INSTALL_FROM_API", "1");
        }
        Query::NpmGlobals => {}
    }
    command
}

// Private raw payloads never implement Debug/Serialize or escape on errors. Concurrent,
// nonblocking drains bound combined stdout/stderr even if a descendant holds a pipe.
pub(crate) fn run_bounded(
    mut command: Command,
    limit: usize,
    timeout: Duration,
) -> Result<Vec<u8>, Failure> {
    command
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .process_group(0);
    let mut child = command.spawn().map_err(|_| Failure::Unavailable)?;
    let result = (|| {
        let mut stdout = child.stdout.take().ok_or(Failure::Pipe)?;
        let mut stderr = child.stderr.take().ok_or(Failure::Pipe)?;
        use rustix::fs::{OFlags, fcntl_getfl, fcntl_setfl};
        for pipe in [&stdout as &dyn std::os::fd::AsFd, &stderr] {
            let flags = fcntl_getfl(pipe).map_err(|_| Failure::Pipe)?;
            fcntl_setfl(pipe, flags | OFlags::NONBLOCK).map_err(|_| Failure::Pipe)?;
        }
        let start = Instant::now();
        let mut bytes = Vec::new();
        let mut total = 0usize;
        let (mut out_done, mut err_done) = (false, false);
        loop {
            if start.elapsed() >= timeout {
                return Err(Failure::Timeout);
            }
            for (pipe, done, keep) in [
                (&mut stdout as &mut dyn Read, &mut out_done, true),
                (&mut stderr as &mut dyn Read, &mut err_done, false),
            ] {
                if *done {
                    continue;
                }
                let mut buffer = [0; 8192];
                match pipe.read(&mut buffer) {
                    Ok(0) => *done = true,
                    Ok(count) => {
                        total += count;
                        if total > limit {
                            return Err(Failure::OutputLimit);
                        }
                        if keep {
                            bytes.extend_from_slice(&buffer[..count]);
                        }
                    }
                    Err(e)
                        if matches!(
                            e.kind(),
                            std::io::ErrorKind::WouldBlock | std::io::ErrorKind::Interrupted
                        ) => {}
                    Err(_) => return Err(Failure::Pipe),
                }
            }
            if let Some(status) = child.try_wait().map_err(|_| Failure::Wait)?
                && out_done
                && err_done
            {
                return if status.success() {
                    Ok(bytes)
                } else {
                    Err(Failure::QueryFailed)
                };
            }
            thread::sleep(Duration::from_millis(1));
        }
    })();
    // Kill remaining descendants on success too; an inspection never owns a background job.
    if let Some(pid) = rustix::process::Pid::from_raw(child.id() as i32) {
        let _ = rustix::process::kill_process_group(pid, rustix::process::Signal::KILL);
    }
    let _ = child.wait();
    result
}

#[cfg(test)]
mod tests;