workpen 0.9.0

Workpen dest-deny and a per-child process jail (Landlock, Seatbelt, Windows).
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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
//! Workspace PathGuard. Separate from dest-deny. Does not classify secrets.

use std::io;
use std::path::{Component, Path, PathBuf};

/// Policy for absolute dests. Extra roots apply to absolute inputs only.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AbsolutePathPolicy {
    /// Reject every absolute path (builder default).
    Reject,
    /// Allow absolute paths that stay inside the primary workspace.
    AllowIfContained,
    /// Allow absolute paths inside the workspace or these extra roots.
    AllowAdditionalRoots(Vec<PathBuf>),
}

/// Allowed roots plus an absolute-path policy.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PathGuard {
    root: PathBuf,
    workspace: PathBuf,
    roots: Vec<PathBuf>,
    policy: AbsolutePathPolicy,
}

/// Why PathGuard rejected a path. Hosts branch on this; do not parse messages.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PathGuardKind {
    /// Resolved path is outside every allowed root (`..` or absolute escape).
    Escape,
    /// A symlink in the chain resolved outside the allowed roots.
    SymlinkVault,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PathGuardDeny {
    pub kind: PathGuardKind,
    pub path: PathBuf,
    pub display: String,
}

impl PathGuardDeny {
    pub fn message(&self) -> String {
        match self.kind {
            PathGuardKind::Escape => {
                format!("path escapes workspace: {}", self.display)
            }
            PathGuardKind::SymlinkVault => {
                format!(
                    "path is a symlink that leaves the workspace: {}",
                    self.display
                )
            }
        }
    }
}

impl std::fmt::Display for PathGuardDeny {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.message())
    }
}

#[derive(Debug, thiserror::Error)]
pub enum PathGuardError {
    #[error("path must not be empty")]
    EmptyPath,
    #[error("absolute paths are not allowed: {0}")]
    AbsolutePath(String),
    #[error("{0}")]
    Denied(PathGuardDeny),
    #[error("path guard root is not usable: {0}")]
    Root(String),
    #[error("workspace root is the home directory {0}; use a project subdirectory, not $HOME")]
    Home(PathBuf),
    #[error("failed to canonicalize path: {path}: {source}")]
    Canonicalize {
        path: String,
        #[source]
        source: io::Error,
    },
}

/// Extra-root resolution. Separate from PathGuardError so hosts can match variants.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum ExtraRootError {
    #[error("extra write dir must not be empty")]
    Empty,
    #[error("extra write dir does not exist: {path}")]
    Missing { path: String },
    #[error("extra write dir is not a directory: {path}")]
    NotDirectory { path: String },
    #[error("failed to canonicalize extra write dir {path}: {detail}")]
    Canonicalize { path: String, detail: String },
    #[error(
        "extra write dir {requested} escaped after canonicalize to {resolved} (not an explicit extra)"
    )]
    EscapedToRoot { requested: String, resolved: String },
    #[error("extra write dir is the home directory {0}; use a project subdirectory, not $HOME")]
    Home(PathBuf),
}

/// Builder default policy is [`AbsolutePathPolicy::Reject`].
pub struct PathGuardBuilder {
    root: PathBuf,
    policy: AbsolutePathPolicy,
}

impl PathGuard {
    pub fn new(
        workspace: impl AsRef<Path>,
        policy: AbsolutePathPolicy,
    ) -> Result<Self, PathGuardError> {
        let root = workspace.as_ref().to_path_buf();
        let workspace = canonicalize_root(&root)?;
        let extra = match &policy {
            AbsolutePathPolicy::AllowAdditionalRoots(extra) => extra.as_slice(),
            AbsolutePathPolicy::Reject | AbsolutePathPolicy::AllowIfContained => &[],
        };
        let mut roots = vec![workspace.clone()];
        for extra in extra {
            let extra = canonicalize_root(extra)?;
            if is_user_home_dir(&extra) {
                return Err(PathGuardError::Home(extra));
            }
            if !roots.iter().any(|r| r == &extra) {
                roots.push(extra);
            }
        }
        Ok(Self {
            root,
            workspace,
            roots,
            policy,
        })
    }

    pub fn builder(root: impl Into<PathBuf>) -> PathGuardBuilder {
        PathGuardBuilder {
            root: root.into(),
            policy: AbsolutePathPolicy::Reject,
        }
    }

    pub fn with_extra_roots(
        workspace: impl AsRef<Path>,
        extra: impl IntoIterator<Item = impl AsRef<Path>>,
    ) -> Result<Self, PathGuardError> {
        let extra = extra
            .into_iter()
            .map(|p| p.as_ref().to_path_buf())
            .collect::<Vec<_>>();
        Self::new(workspace, AbsolutePathPolicy::AllowAdditionalRoots(extra))
    }

    pub fn workspace(&self) -> &Path {
        &self.workspace
    }

    pub fn root(&self) -> &Path {
        &self.root
    }

    pub fn canon_root(&self) -> &Path {
        &self.workspace
    }

    pub fn roots(&self) -> &[PathBuf] {
        &self.roots
    }

    /// Classify one dest. Escape vs symlink vault only. Does not dest-deny.
    pub fn classify(&self, path: &Path) -> Option<PathGuardKind> {
        match self.check(path) {
            Ok(_) => None,
            Err(PathGuardError::Denied(d)) => Some(d.kind),
            Err(_) => Some(PathGuardKind::Escape),
        }
    }

    /// Resolve one dest. A path that is not valid UTF-8 is
    /// [`PathGuardKind::Escape`]. The lossy name is not scanned.
    pub fn check(&self, path: &Path) -> Result<PathBuf, PathGuardError> {
        let Some(raw) = path.to_str() else {
            return Err(PathGuardError::Denied(PathGuardDeny {
                kind: PathGuardKind::Escape,
                path: path.to_path_buf(),
                display: path.to_string_lossy().into_owned(),
            }));
        };
        self.check_path(raw)
    }

    /// Content ops. Follows the final component.
    pub fn check_path(&self, path: &str) -> Result<PathBuf, PathGuardError> {
        self.check_inner(path, Follow::Final)
    }

    /// Unlink / rename. Follows the parent only; appends the leaf.
    pub fn check_path_entry(&self, path: &str) -> Result<PathBuf, PathGuardError> {
        self.check_inner(path, Follow::Parent)
    }

    fn check_inner(&self, path: &str, follow: Follow) -> Result<PathBuf, PathGuardError> {
        if is_blank_path(path) {
            return Err(PathGuardError::EmptyPath);
        }
        let raw = Path::new(path);
        if raw.is_absolute() {
            let roots = self.absolute_roots(path)?;
            return self.resolve(path, raw, &roots, follow);
        }
        if relative_escapes_primary(raw) {
            return Err(self.denied(path, PathGuardKind::Escape));
        }
        let joined = self.workspace.join(raw);
        self.resolve(path, &joined, std::slice::from_ref(&self.workspace), follow)
    }

    fn absolute_roots(&self, path: &str) -> Result<Vec<PathBuf>, PathGuardError> {
        match &self.policy {
            AbsolutePathPolicy::Reject => Err(PathGuardError::AbsolutePath(path.to_owned())),
            AbsolutePathPolicy::AllowIfContained => Ok(vec![self.workspace.clone()]),
            AbsolutePathPolicy::AllowAdditionalRoots(_) => Ok(self.roots.clone()),
        }
    }

    fn resolve(
        &self,
        display: &str,
        start: &Path,
        roots: &[PathBuf],
        follow: Follow,
    ) -> Result<PathBuf, PathGuardError> {
        match follow {
            Follow::Final => walk_guarded(start, roots).map_err(|kind| self.denied(display, kind)),
            Follow::Parent => {
                let leaf = start.file_name().map(PathBuf::from);
                let parent = start.parent().unwrap_or(Path::new("."));
                let parent = if parent.as_os_str().is_empty() {
                    self.workspace.clone()
                } else {
                    walk_guarded(parent, roots).map_err(|kind| self.denied(display, kind))?
                };
                Ok(match leaf {
                    Some(name) => parent.join(name),
                    None => parent,
                })
            }
        }
    }

    fn denied(&self, display: &str, kind: PathGuardKind) -> PathGuardError {
        PathGuardError::Denied(PathGuardDeny {
            kind,
            path: PathBuf::from(display),
            display: display.to_owned(),
        })
    }
}

impl PathGuardBuilder {
    pub fn allow_root(mut self, extra: impl Into<PathBuf>) -> Self {
        let extra = extra.into();
        self.policy = match self.policy {
            AbsolutePathPolicy::AllowAdditionalRoots(mut roots) => {
                if !roots.iter().any(|r| r == &extra) {
                    roots.push(extra);
                }
                AbsolutePathPolicy::AllowAdditionalRoots(roots)
            }
            AbsolutePathPolicy::Reject | AbsolutePathPolicy::AllowIfContained => {
                AbsolutePathPolicy::AllowAdditionalRoots(vec![extra])
            }
        };
        self
    }

    pub fn absolute_policy(mut self, policy: AbsolutePathPolicy) -> Self {
        self.policy = policy;
        self
    }

    pub fn build(self) -> Result<PathGuard, PathGuardError> {
        PathGuard::new(self.root, self.policy)
    }
}

/// Refuse if any host-extracted dest leaves the workspace.
pub fn check_dests(guard: &PathGuard, dests: &[impl AsRef<Path>]) -> Result<(), PathGuardError> {
    for dest in dests {
        guard.check(dest.as_ref())?;
    }
    Ok(())
}

/// Resolve `--root` against `cwd`. Must exist and be a directory.
/// A relative `../ws` becomes the absolute workspace, not a PathGuard escape.
/// Implicit canonicalize to `/` or the host temp root is refused unless asked.
pub fn resolve_workspace_root(cwd: &Path, root: &str) -> Result<PathBuf, PathGuardError> {
    let requested = root;
    // Whitespace-only is empty. Do not trim a real name: "trail " is another directory.
    if requested.trim().is_empty() {
        return Err(PathGuardError::Root(
            "workspace root must not be empty".into(),
        ));
    }
    let raw = PathBuf::from(requested);
    let abs = if raw.is_absolute() {
        raw
    } else {
        cwd.join(raw)
    };
    if !abs.exists() {
        return Err(PathGuardError::Root(format!(
            "workspace root does not exist: {}",
            abs.display()
        )));
    }
    if !abs.is_dir() {
        return Err(PathGuardError::Root(format!(
            "workspace root is not a directory: {}",
            abs.display()
        )));
    }
    let canon = canonicalize_root(&abs)?;
    if is_filesystem_root(&canon) && !requested_is_explicit_root(requested) {
        return Err(PathGuardError::Root(format!(
            "workspace root {requested} escaped after canonicalize to {}",
            canon.display()
        )));
    }
    if is_host_temp_root(&canon) && !requested_is_explicit_temp(requested) {
        return Err(PathGuardError::Root(format!(
            "workspace root {requested} escaped after canonicalize to {}",
            canon.display()
        )));
    }
    if is_user_home_dir(&canon) {
        return Err(PathGuardError::Home(canon));
    }
    Ok(canon)
}

/// Resolve one extra write dir against `cwd`. Fail closed on missing,
/// not-a-dir, canonicalize failure, the current user's home directory,
/// or implicit escape to `/` or host temp unless the caller named that
/// root explicitly. A subdirectory of home (for example `~/.cache`) is
/// still allowed.
pub fn resolve_extra_root(cwd: &Path, extra: &str) -> Result<PathBuf, ExtraRootError> {
    resolve_extra_root_pair(cwd, extra).map(|(_, canon)| canon)
}

/// Same as [`resolve_extra_root`], plus the absolute path before canonicalize.
///
/// `presented` is `cwd` joined with the trimmed extra when relative. Hosts
/// grant that path so a symlink extra such as `/tmp` stays writable on macOS.
pub fn resolve_extra_root_pair(
    cwd: &Path,
    extra: &str,
) -> Result<(PathBuf, PathBuf), ExtraRootError> {
    let extra = extra.trim();
    if extra.is_empty() {
        return Err(ExtraRootError::Empty);
    }
    let raw = PathBuf::from(extra);
    let presented = if raw.is_absolute() {
        raw
    } else {
        cwd.join(raw)
    };
    if !presented.exists() {
        return Err(ExtraRootError::Missing {
            path: presented.display().to_string(),
        });
    }
    if !presented.is_dir() {
        return Err(ExtraRootError::NotDirectory {
            path: presented.display().to_string(),
        });
    }
    let canon = dunce::canonicalize(&presented).map_err(|e| ExtraRootError::Canonicalize {
        path: presented.display().to_string(),
        detail: e.to_string(),
    })?;
    if is_filesystem_root(&canon) && !requested_is_explicit_root(extra) {
        return Err(ExtraRootError::EscapedToRoot {
            requested: extra.to_owned(),
            resolved: canon.display().to_string(),
        });
    }
    if is_host_temp_root(&canon) && !requested_is_explicit_temp(extra) {
        return Err(ExtraRootError::EscapedToRoot {
            requested: extra.to_owned(),
            resolved: canon.display().to_string(),
        });
    }
    if is_user_home_dir(&canon) {
        return Err(ExtraRootError::Home(canon));
    }
    Ok((presented, canon))
}

#[derive(Clone, Copy)]
enum Follow {
    Final,
    Parent,
}

fn is_blank_path(s: &str) -> bool {
    s.chars().all(|c| {
        c.is_whitespace() || matches!(c, '\u{200B}' | '\u{200C}' | '\u{200D}' | '\u{FEFF}')
    })
}

fn relative_escapes_primary(path: &Path) -> bool {
    let mut depth: i32 = 0;
    for component in path.components() {
        match component {
            Component::Prefix(_) | Component::RootDir | Component::CurDir => {}
            Component::Normal(_) => depth += 1,
            Component::ParentDir => {
                if depth == 0 {
                    return true;
                }
                depth -= 1;
            }
        }
    }
    false
}

fn canonicalize_root(path: &Path) -> Result<PathBuf, PathGuardError> {
    dunce::canonicalize(path).map_err(|e| PathGuardError::Root(format!("{} ({e})", path.display())))
}

/// True when `path` is the current user's home directory.
///
/// Compares `HOME` (Unix) or `USERPROFILE` (Windows) after
/// `dunce::canonicalize`. Missing or unreadable home is not a match.
/// `/tmp` and `/private/tmp` are not home.
pub(crate) fn is_user_home_dir(path: &Path) -> bool {
    let Some(raw) = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")) else {
        return false;
    };
    if raw.is_empty() {
        return false;
    }
    let Ok(home) = dunce::canonicalize(&raw) else {
        return false;
    };
    let path = dunce::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
    path == home
}

fn walk_guarded(start: &Path, roots: &[PathBuf]) -> Result<PathBuf, PathGuardKind> {
    let lexical = normalize_lexical(start);
    if let Ok(canon) = dunce::canonicalize(&lexical) {
        if inside_any_root(&canon, roots) {
            return Ok(canon);
        }
        if inside_any_root(&lexical, roots) {
            return Err(PathGuardKind::SymlinkVault);
        }
        return Err(PathGuardKind::Escape);
    }

    let prefix = longest_existing_prefix(&lexical);
    if prefix.as_os_str().is_empty() {
        return if inside_any_root(&lexical, roots) {
            Ok(lexical)
        } else {
            Err(PathGuardKind::Escape)
        };
    }
    let prefix_canon = match dunce::canonicalize(&prefix) {
        Ok(canon) => canon,
        Err(_) => {
            let rest = lexical.strip_prefix(&prefix).unwrap_or(Path::new(""));
            if let Some(target) = lexical_symlink_target(&prefix, rest) {
                if inside_with_firmlink(&target, roots) {
                    // The link text stays in the workspace. The final
                    // file is missing, same as a path that was never created.
                    return Ok(target);
                }
                if chain_has_symlink(&prefix) {
                    return Err(PathGuardKind::SymlinkVault);
                }
            }
            if chain_has_symlink(&prefix) && inside_with_firmlink(&prefix, roots) {
                return Err(PathGuardKind::SymlinkVault);
            }
            return Err(PathGuardKind::Escape);
        }
    };
    let rest = lexical.strip_prefix(&prefix).unwrap_or(Path::new(""));
    let resolved = prefix_canon.join(rest);
    if inside_any_root(&resolved, roots) {
        return Ok(resolved);
    }
    if chain_has_symlink(&prefix) && inside_any_root(&prefix, roots) {
        return Err(PathGuardKind::SymlinkVault);
    }
    Err(PathGuardKind::Escape)
}

fn root_component_len(path: &Path) -> usize {
    path.components()
        .take_while(|component| matches!(component, Component::Prefix(_) | Component::RootDir))
        .count()
}

fn normalize_lexical(path: &Path) -> PathBuf {
    let mut out = PathBuf::new();
    for component in path.components() {
        match component {
            Component::Prefix(prefix) => out.push(prefix.as_os_str()),
            Component::RootDir => out.push(component.as_os_str()),
            Component::CurDir => {}
            Component::ParentDir => {
                // `/..` stays `/`. Popping the root makes the rest relative.
                if out.has_root() && out.components().count() <= root_component_len(&out) {
                    continue;
                }
                let _ = out.pop();
            }
            Component::Normal(name) => out.push(name),
        }
    }
    out
}

fn longest_existing_prefix(path: &Path) -> PathBuf {
    let mut last = PathBuf::new();
    let mut cur = PathBuf::new();
    for component in path.components() {
        cur.push(component);
        // `exists` follows the last component. A broken symlink is a dirent
        // and must count as present so walk_guarded can classify it.
        if std::fs::symlink_metadata(&cur).is_ok() {
            last.clone_from(&cur);
        } else {
            break;
        }
    }
    last
}

fn chain_has_symlink(path: &Path) -> bool {
    let mut cur = PathBuf::new();
    for component in path.components() {
        cur.push(component);
        if let Ok(meta) = std::fs::symlink_metadata(&cur)
            && meta.file_type().is_symlink()
        {
            return true;
        }
    }
    false
}

fn inside_any_root(path: &Path, roots: &[PathBuf]) -> bool {
    let path = strip_verbatim_disk(path);
    roots.iter().any(|root| {
        let root = strip_verbatim_disk(root);
        path == root || path.starts_with(&root)
    })
}

/// `dunce` keeps the `\\?\` prefix when the final name is reserved
/// (`CON`, `NUL`). The workspace root does not have that prefix, so
/// the literal file would look like an escape.
fn strip_verbatim_disk(path: &Path) -> PathBuf {
    #[cfg(windows)]
    {
        let text = path.to_string_lossy();
        if let Some(rest) = text.strip_prefix(r"\\?\") {
            if let Some(unc) = rest.strip_prefix(r"UNC\") {
                return PathBuf::from(format!(r"\\{unc}"));
            }
            if rest.as_bytes().get(1) == Some(&b':') {
                return PathBuf::from(rest);
            }
        }
    }
    path.to_path_buf()
}

/// One `read_link` hop, then the remaining components. Absolute link
/// text replaces the prefix. Relative link text is joined to its parent.
fn lexical_symlink_target(prefix: &Path, rest: &Path) -> Option<PathBuf> {
    let raw = std::fs::read_link(prefix).ok()?;
    let base = if raw.is_absolute() {
        raw
    } else {
        prefix.parent()?.join(raw)
    };
    Some(normalize_lexical(&base.join(rest)))
}

/// `/tmp` and `/private/tmp` are the same directory on macOS. Compare
/// both spellings so a dangling link written with the public path is
/// not an escape from a canonical root.
fn inside_with_firmlink(path: &Path, roots: &[PathBuf]) -> bool {
    let path = firmlink_private(path);
    roots.iter().any(|root| {
        let root = firmlink_private(root);
        path == root || path.starts_with(&root)
    })
}

fn firmlink_private(path: &Path) -> PathBuf {
    let Some(raw) = path.to_str() else {
        return path.to_path_buf();
    };
    for (public, private) in [
        ("/tmp", "/private/tmp"),
        ("/var", "/private/var"),
        ("/etc", "/private/etc"),
    ] {
        if raw == public || raw.starts_with(&format!("{public}/")) {
            return PathBuf::from(format!("{private}{}", &raw[public.len()..]));
        }
    }
    path.to_path_buf()
}

fn is_filesystem_root(path: &Path) -> bool {
    path.parent().is_none_or(|p| p.as_os_str().is_empty())
}

fn requested_is_explicit_root(requested: &str) -> bool {
    let t = requested.trim();
    t == "/" || t == "\\" || (t.len() == 3 && t.as_bytes()[1] == b':' && t.ends_with(['\\', '/']))
}

fn is_host_temp_root(path: &Path) -> bool {
    if is_well_known_temp_name(path) {
        return true;
    }
    let tmp = std::env::temp_dir();
    if path == tmp {
        return true;
    }
    dunce::canonicalize(&tmp).is_ok_and(|canon| path == canon)
}

fn is_well_known_temp_name(path: &Path) -> bool {
    let s = path.to_string_lossy();
    let s = s.trim_end_matches(['/', '\\']);
    s.eq_ignore_ascii_case("/tmp")
        || s.eq_ignore_ascii_case("/private/tmp")
        || s.eq_ignore_ascii_case("/var/tmp")
        || s.eq_ignore_ascii_case("/private/var/tmp")
}

fn requested_is_explicit_temp(requested: &str) -> bool {
    let t = requested.trim().trim_end_matches(['/', '\\']);
    if t.is_empty() {
        return false;
    }
    let p = Path::new(t);
    p.is_absolute() && (is_well_known_temp_name(p) || is_host_temp_root(p))
}