interplane.Get Omega
Read in your language

aien-sovereign-core-mv

AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.

Brought by drakestapleton

branch main Branches Tags History

aien-sovereign-core-mv / crates / aien-cli / src / fs_bind_linux.rs

2047 lines · 74712 bytes Raw Blame History
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16use std::ffi::{CString, OsStr, OsString};
17use std::fs::File;
18use std::io::{Read, Seek, SeekFrom, Write};
19use std::os::fd::{AsRawFd, FromRawFd, IntoRawFd, OwnedFd};
20use std::os::unix::ffi::OsStrExt;
21use std::path::{Component, Path, PathBuf};
22use std::process::{Command, Stdio};
23use std::sync::Mutex;
24
25use crate::safety::validate_workspace_path;
26
27#[repr(C)]
28struct OpenHow {
29 flags: u64,
30 mode: u64,
31 resolve: u64,
32}
33
34#[derive(Debug)]
35pub enum BindError {
36 /// The path is not the authorized workspace object, or it cannot be bound.
37 Denied(String),
38 NotFound(String),
39 Exists(String),
40 Failed(String),
41}
42
43impl BindError {
44 pub fn message(&self) -> &str {
45 match self {
46 Self::Denied(m) | Self::NotFound(m) | Self::Exists(m) | Self::Failed(m) => m,
47 }
48 }
49}
50
51struct Authorized {
52 /// Workspace that contains the path the caller named.
53 workspace: PathBuf,
54 /// That path, relative to `workspace`, exactly as named. `..` is kept:
55 /// the kernel resolves it under `RESOLVE_BENEATH | RESOLVE_NO_SYMLINKS`,
56 /// so a `..` reaches the same parent the allow-list resolved, and a
57 /// symlink before it is refused instead of being dropped as text.
58 rel: PathBuf,
59 /// Workspace that contains the allow-listed canonical object.
60 canon_workspace: PathBuf,
61 /// Canonical object relative to `canon_workspace`. Plain components.
62 /// Used only when the caller's final component is a symlink to it.
63 canon_rel: PathBuf,
64 canonical: PathBuf,
65 display: String,
66}
67
68/// Workspace roots the CLI file tools may authorize. Same set the tool
69/// allow-list already used: platform defaults plus `/tmp`.
70pub fn permitted_workspaces() -> Vec<PathBuf> {
71 #[cfg(test)]
72 if let Some(roots) = test_hooks::workspaces() {
73 return roots;
74 }
75 let mut allowed = crate::platform::PlatformContext::detect().default_workspaces;
76 allowed.push(PathBuf::from("/tmp"));
77 allowed
78}
79
80fn authorize(user_path: &str) -> Result<Authorized, BindError> {
81 let workspaces = permitted_workspaces();
82 let canonical = validate_workspace_path(user_path, &workspaces).map_err(|_| {
83 BindError::Denied(format!(
84 "refusing {}: it is outside the workspace allow-list",
85 safe_label(Path::new(user_path))
86 ))
87 })?;
88 let named = absolute_named(user_path)?;
89 // Open the path the caller named. Opening `canonical` instead would
90 // follow a directory symlink into another allowed directory.
91 let Some((workspace, rel)) = longest_workspace(&named, &workspaces) else {
92 return Err(BindError::Denied(format!(
93 "refusing {}: it resolves outside permitted workspace roots",
94 safe_label(Path::new(user_path))
95 )));
96 };
97 let Some((canon_workspace, canon_rel)) = longest_workspace(&canonical, &workspaces) else {
98 return Err(BindError::Denied(format!(
99 "refusing {}: it resolves outside permitted workspace roots",
100 safe_label(Path::new(user_path))
101 )));
102 };
103 plain_rel(&canon_rel, user_path)?;
104 Ok(Authorized {
105 workspace,
106 rel,
107 canon_workspace,
108 canon_rel,
109 canonical,
110 display: user_path.to_string(),
111 })
112}
113
114fn plain_rel(rel: &Path, user_path: &str) -> Result<(), BindError> {
115 if rel.components().any(|c| !matches!(c, Component::Normal(_))) {
116 return Err(BindError::Denied(format!(
117 "refusing {}: the authorized path is not a plain path under the workspace",
118 safe_label(Path::new(user_path))
119 )));
120 }
121 Ok(())
122}
123
124/// True when `rel` holds only names and `..`, and no `..` climbs above the
125/// directory it starts from. `RESOLVE_BENEATH` enforces the same bound.
126fn stays_beneath(rel: &Path) -> bool {
127 let mut depth = 0usize;
128 for c in rel.components() {
129 match c {
130 Component::Normal(_) => depth += 1,
131 Component::ParentDir if depth > 0 => depth -= 1,
132 _ => return false,
133 }
134 }
135 true
136}
137
138/// Deepest workspace that `path` names lexically and never climbs out of,
139/// returned as (canonical root, path relative to it). A root configured
140/// through a symlink also matches by its configured name; it is opened at
141/// its canonical place, since `open_workspace` trusts the root and its
142/// ancestors.
143fn longest_workspace(path: &Path, workspaces: &[PathBuf]) -> Option<(PathBuf, PathBuf)> {
144 let mut best: Option<(usize, PathBuf, PathBuf)> = None;
145 for ws in workspaces {
146 let Ok(ws_canon) = ws.canonicalize() else {
147 continue;
148 };
149 let Some((prefix, rel)) = [ws_canon.as_path(), ws.as_path()]
150 .into_iter()
151 .find_map(|prefix| path.strip_prefix(prefix).ok().map(|rel| (prefix, rel)))
152 else {
153 continue;
154 };
155 if !stays_beneath(rel) {
156 continue;
157 }
158 let depth = prefix.components().count();
159 if best.as_ref().is_none_or(|(cur, _, _)| depth > *cur) {
160 best = Some((depth, ws_canon.clone(), rel.to_path_buf()));
161 }
162 }
163 best.map(|(_, ws, rel)| (ws, rel))
164}
165
166/// `user_path` made absolute against the current directory. `.` and repeated
167/// separators go; `..` stays. Collapsing `link/..` as text names a different
168/// object from the one the OS (and `validate_workspace_path`) resolves when
169/// `link` is a symlink.
170fn absolute_named(user_path: &str) -> Result<PathBuf, BindError> {
171 let raw = Path::new(user_path);
172 let abs = if raw.is_absolute() {
173 raw.to_path_buf()
174 } else {
175 std::env::current_dir()
176 .map_err(|e| BindError::Failed(e.to_string()))?
177 .join(raw)
178 };
179 Ok(abs.components().collect())
180}
181
182fn symlink_component(err: &std::io::Error) -> bool {
183 matches!(err.raw_os_error(), Some(libc::ELOOP) | Some(libc::ENOTDIR))
184}
185
186fn name_is_symlink(dirfd: libc::c_int, name: &OsStr) -> bool {
187 let Ok(c) = c_string(name.as_bytes()) else {
188 return false;
189 };
190 let mut st = std::mem::MaybeUninit::<libc::stat>::uninit();
191 // SAFETY: `dirfd` is a directory we hold and `c` is one component.
192 let rc = unsafe {
193 libc::fstatat(
194 dirfd,
195 c.as_ptr(),
196 st.as_mut_ptr(),
197 libc::AT_SYMLINK_NOFOLLOW,
198 )
199 };
200 if rc != 0 {
201 return false;
202 }
203 let st = unsafe { st.assume_init() };
204 st.st_mode & libc::S_IFMT == libc::S_IFLNK
205}
206
207/// True only when every component except the last opened, and the last is a
208/// symlink. An intermediate symlink makes the parent open fail, so a swapped
209/// directory is not treated as a final-component link.
210fn final_component_is_symlink(ws: &OwnedFd, rel: &Path) -> bool {
211 let Some(name) = rel.file_name() else {
212 return false;
213 };
214 let parent = rel.parent().unwrap_or(Path::new(""));
215 let parent_fd = if parent.as_os_str().is_empty() {
216 dup_fd(ws.as_raw_fd()).ok()
217 } else {
218 open_beneath(
219 ws.as_raw_fd(),
220 parent,
221 libc::O_RDONLY | libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC,
222 0,
223 )
224 .ok()
225 };
226 let Some(parent_fd) = parent_fd else {
227 return false;
228 };
229 name_is_symlink(parent_fd.as_raw_fd(), name)
230}
231
232/// Workspace-relative text, or a generic label when `path` is absolute.
233/// Error strings must not carry a host absolute path.
234fn safe_label(path: &Path) -> String {
235 if path.as_os_str().is_empty() {
236 "the workspace root".to_string()
237 } else if path.is_absolute() {
238 "the requested path".to_string()
239 } else {
240 path.display().to_string()
241 }
242}
243
244fn map_io(path: &Path, err: std::io::Error) -> BindError {
245 let label = safe_label(path);
246 match err.raw_os_error() {
247 Some(libc::ELOOP) => BindError::Denied(format!(
248 "refusing '{label}': a symlink is on the authorized path"
249 )),
250 Some(libc::EXDEV) => BindError::Denied(format!(
251 "refusing '{label}': the path resolves outside the workspace root"
252 )),
253 Some(libc::ENOSYS) => BindError::Denied(format!(
254 "refusing '{label}': openat2 is unavailable, so the open cannot be bound to the authorized target"
255 )),
256 // EPERM and EINVAL are confinement failures, not a generic I/O miss.
257 // A kernel that rejects the resolve flags must not fall through to a
258 // pathname open.
259 Some(libc::EPERM) | Some(libc::EINVAL) => BindError::Denied(format!(
260 "refusing '{label}': the open cannot be bound to the authorized target"
261 )),
262 // A symlink opened with O_DIRECTORY and RESOLVE_NO_SYMLINKS is reported
263 // as ENOTDIR (the link itself is not a directory). Do not follow it.
264 Some(libc::ENOTDIR) => BindError::Denied(format!(
265 "refusing '{label}': a path component is not a directory"
266 )),
267 Some(libc::ENOENT) => BindError::NotFound(err.to_string()),
268 Some(libc::EEXIST) => BindError::Exists(err.to_string()),
269 _ => BindError::Failed(err.to_string()),
270 }
271}
272
273fn c_string(bytes: &[u8]) -> std::io::Result<CString> {
274 CString::new(bytes).map_err(|_| std::io::Error::from_raw_os_error(libc::EINVAL))
275}
276
277/// Open `rel` beneath `dirfd` in one `openat2` step. `rel` empty duplicates
278/// `dirfd` (the workspace root itself).
279fn open_beneath(
280 dirfd: libc::c_int,
281 rel: &Path,
282 flags: libc::c_int,
283 mode: u64,
284) -> std::io::Result<OwnedFd> {
285 if rel.as_os_str().is_empty() {
286 return dup_fd(dirfd);
287 }
288 #[cfg(test)]
289 if let Some(code) = test_hooks::take_openat2_error() {
290 return Err(std::io::Error::from_raw_os_error(code));
291 }
292 let c = c_string(rel.as_os_str().as_bytes())?;
293 let how = OpenHow {
294 flags: (flags | libc::O_CLOEXEC) as u64,
295 mode,
296 resolve: libc::RESOLVE_BENEATH | libc::RESOLVE_NO_SYMLINKS | libc::RESOLVE_NO_MAGICLINKS,
297 };
298 // With RESOLVE_BENEATH the kernel returns EAGAIN when a rename or mount
299 // anywhere raced a `..` step, since it cannot then prove the walk stayed
300 // beneath. Retry a bounded number of times; it stays a failure after.
301 let mut attempts = 0;
302 loop {
303 // SAFETY: `c` is a valid C string, `how` matches the kernel `open_how`
304 // layout, and a non-negative fd is owned by this function alone.
305 let fd = unsafe {
306 libc::syscall(
307 libc::SYS_openat2,
308 dirfd,
309 c.as_ptr(),
310 &how as *const OpenHow,
311 std::mem::size_of::<OpenHow>(),
312 )
313 };
314 if fd >= 0 {
315 return Ok(unsafe { OwnedFd::from_raw_fd(fd as libc::c_int) });
316 }
317 let err = std::io::Error::last_os_error();
318 attempts += 1;
319 if err.raw_os_error() != Some(libc::EAGAIN) || attempts == 32 {
320 return Err(err);
321 }
322 }
323}
324
325fn dup_fd(fd: libc::c_int) -> std::io::Result<OwnedFd> {
326 // SAFETY: `fd` is an open descriptor; a non-negative result is a new fd.
327 let n = unsafe { libc::fcntl(fd, libc::F_DUPFD_CLOEXEC, 0) };
328 if n < 0 {
329 return Err(std::io::Error::last_os_error());
330 }
331 Ok(unsafe { OwnedFd::from_raw_fd(n) })
332}
333
334fn open_workspace(path: &Path) -> Result<OwnedFd, BindError> {
335 let c = c_string(path.as_os_str().as_bytes()).map_err(|e| map_io(path, e))?;
336 // SAFETY: `c` is a valid C string. `O_NOFOLLOW` applies to the final
337 // component. Ancestors of the workspace root are the trust boundary, the
338 // same rule as runtime `open_confined`. A non-negative fd is ours.
339 let fd = unsafe {
340 libc::open(
341 c.as_ptr(),
342 libc::O_RDONLY | libc::O_DIRECTORY | libc::O_CLOEXEC | libc::O_NOFOLLOW,
343 )
344 };
345 if fd < 0 {
346 return Err(map_io(path, std::io::Error::last_os_error()));
347 }
348 Ok(unsafe { OwnedFd::from_raw_fd(fd) })
349}
350
351fn mkdir_at(dirfd: libc::c_int, name: &OsStr) -> std::io::Result<()> {
352 let c = c_string(name.as_bytes())?;
353 // SAFETY: `dirfd` is a directory and `c` is one component, not a path.
354 let rc = unsafe { libc::mkdirat(dirfd, c.as_ptr(), 0o755) };
355 if rc == 0 {
356 return Ok(());
357 }
358 let err = std::io::Error::last_os_error();
359 if err.raw_os_error() == Some(libc::EEXIST) {
360 Ok(())
361 } else {
362 Err(err)
363 }
364}
365
366/// Stop a single file from being pulled into the grep pipe without a bound.
367const READ_LIMIT: u64 = 8 * 1024 * 1024;
368
369fn read_all(file: &mut File) -> Result<Vec<u8>, BindError> {
370 file.seek(SeekFrom::Start(0))
371 .map_err(|e| BindError::Failed(e.to_string()))?;
372 read_capped(file, READ_LIMIT)
373}
374
375/// Read at most `limit + 1` bytes from `src` and refuse the read if that
376/// extra byte arrives, so a large or growing file is never buffered whole.
377fn read_capped(src: &mut impl Read, limit: u64) -> Result<Vec<u8>, BindError> {
378 let mut buf = Vec::new();
379 src.take(limit + 1)
380 .read_to_end(&mut buf)
381 .map_err(|e| BindError::Failed(e.to_string()))?;
382 if buf.len() as u64 > limit {
383 return Err(BindError::Denied(
384 "refusing the file: it is larger than the read limit".into(),
385 ));
386 }
387 Ok(buf)
388}
389
390fn write_all_trunc(file: &mut File, content: &[u8]) -> Result<(), BindError> {
391 file.set_len(0)
392 .map_err(|e| BindError::Failed(e.to_string()))?;
393 file.seek(SeekFrom::Start(0))
394 .map_err(|e| BindError::Failed(e.to_string()))?;
395 file.write_all(content)
396 .map_err(|e| BindError::Failed(e.to_string()))?;
397 Ok(())
398}
399
400fn reject_special(path: &Path, file: &File) -> Result<(), BindError> {
401 let meta = file
402 .metadata()
403 .map_err(|e| BindError::Failed(e.to_string()))?;
404 if meta.file_type().is_file() {
405 return Ok(());
406 }
407 if meta.is_dir() {
408 return Err(BindError::Failed("Is a directory (os error 21)".into()));
409 }
410 Err(BindError::Denied(format!(
411 "refusing '{}': authorized target is not a regular file",
412 safe_label(path)
413 )))
414}
415
416/// A file authorized under a workspace, pinned by the descriptor in `cached`
417/// once it has been opened. Later reads and writes use that descriptor.
418#[derive(Debug)]
419pub struct HeldFile {
420 workspace: OwnedFd,
421 rel: PathBuf,
422 authorized: PathBuf,
423 display: String,
424 cached: Mutex<Option<File>>,
425 writable: bool,
426}
427
428impl HeldFile {
429 pub fn authorized(&self) -> &Path {
430 &self.authorized
431 }
432
433 pub fn display(&self) -> &str {
434 &self.display
435 }
436
437 fn cache_lock(&self) -> std::sync::MutexGuard<'_, Option<File>> {
438 self.cached.lock().unwrap_or_else(|e| e.into_inner())
439 }
440
441 fn open_rel(&self, flags: libc::c_int, mode: u64) -> Result<OwnedFd, BindError> {
442 open_beneath(self.workspace.as_raw_fd(), &self.rel, flags, mode)
443 .map_err(|e| map_io(&self.authorized, e))
444 }
445
446 /// Bytes of the pinned file, or `None` when the authorized name is absent.
447 /// A symlink occupying that name is a denial, not a read of its target.
448 pub fn read_checkpoint(&self) -> Result<Option<Vec<u8>>, String> {
449 self.read_bytes().map_err(|e| e.message().to_string())
450 }
451
452 fn read_bytes(&self) -> Result<Option<Vec<u8>>, BindError> {
453 let mut guard = self.cache_lock();
454 if let Some(file) = guard.as_mut() {
455 return read_all(file).map(Some);
456 }
457 match self.open_rel(
458 libc::O_RDONLY | libc::O_NONBLOCK | libc::O_NOFOLLOW | libc::O_CLOEXEC,
459 0,
460 ) {
461 Ok(fd) => {
462 let mut file = File::from(fd);
463 reject_special(&self.authorized, &file)?;
464 let bytes = read_all(&mut file)?;
465 *guard = Some(file);
466 Ok(Some(bytes))
467 }
468 Err(BindError::NotFound(_)) => Ok(None),
469 Err(e) => Err(e),
470 }
471 }
472
473 /// Create missing parent directories beneath the workspace, then write
474 /// `content`. Returns whether any parent directory was created.
475 /// `overwrite` false refuses an existing file without truncating it.
476 pub fn write_bytes(&self, content: &[u8], overwrite: bool) -> Result<bool, BindError> {
477 {
478 let mut guard = self.cache_lock();
479 if let Some(file) = guard.as_mut() {
480 if !self.writable {
481 return Err(BindError::Failed(format!(
482 "Permission denied writing {}",
483 safe_label(&self.rel)
484 )));
485 }
486 if !overwrite {
487 return Err(BindError::Failed(format!(
488 "File already exists: {}. Pass overwrite: true to replace.",
489 safe_label(&self.rel)
490 )));
491 }
492 write_all_trunc(file, content)?;
493 return Ok(false);
494 }
495 }
496 let parent_rel = self.rel.parent().unwrap_or(Path::new(""));
497 let created = self.ensure_dirs(parent_rel)?;
498 let create_flags =
499 libc::O_RDWR | libc::O_CREAT | libc::O_EXCL | libc::O_CLOEXEC | libc::O_NOFOLLOW;
500 match self.open_rel(create_flags, 0o666) {
501 Ok(fd) => {
502 let mut file = File::from(fd);
503 write_all_trunc(&mut file, content)?;
504 *self.cache_lock() = Some(file);
505 Ok(created)
506 }
507 Err(BindError::Exists(_)) if overwrite => {
508 let fd = self.open_rel(
509 libc::O_RDWR | libc::O_NONBLOCK | libc::O_NOFOLLOW | libc::O_CLOEXEC,
510 0,
511 )?;
512 let mut file = File::from(fd);
513 reject_special(&self.authorized, &file)?;
514 write_all_trunc(&mut file, content)?;
515 *self.cache_lock() = Some(file);
516 Ok(created)
517 }
518 Err(BindError::Exists(_)) => Err(BindError::Failed(format!(
519 "File already exists: {}. Pass overwrite: true to replace.",
520 safe_label(&self.rel)
521 ))),
522 Err(e) => Err(e),
523 }
524 }
525
526 /// Replace the bytes of a file that was already pinned. Does not create.
527 pub fn overwrite_existing(&self, content: &[u8]) -> Result<(), BindError> {
528 let mut guard = self.cache_lock();
529 let Some(file) = guard.as_mut() else {
530 return Err(BindError::NotFound(
531 "No such file or directory (os error 2)".into(),
532 ));
533 };
534 if !self.writable {
535 return Err(BindError::Failed(format!(
536 "Permission denied writing {}",
537 safe_label(&self.rel)
538 )));
539 }
540 write_all_trunc(file, content)
541 }
542
543 /// Create every missing directory in `dir_rel` beneath the workspace fd.
544 /// Each new directory is re-opened from the workspace root, so a rename
545 /// out of the workspace fails closed instead of continuing the walk.
546 /// Names up to the last `..` were resolved by the allow-list; they are
547 /// opened as they stand and never created.
548 fn ensure_dirs(&self, dir_rel: &Path) -> Result<bool, BindError> {
549 if dir_rel.as_os_str().is_empty() {
550 return Ok(false);
551 }
552 let mut created = false;
553 let names: Vec<OsString> = dir_rel
554 .components()
555 .map(|c| c.as_os_str().to_os_string())
556 .collect();
557 let fixed = names.iter().rposition(|n| n == "..").map_or(0, |i| i + 1);
558 let mut acc: PathBuf = names[..fixed].iter().collect();
559 for name in &names[fixed..] {
560 let parent_fd = if acc.as_os_str().is_empty() {
561 dup_fd(self.workspace.as_raw_fd()).map_err(|e| map_io(&self.authorized, e))?
562 } else {
563 open_beneath(
564 self.workspace.as_raw_fd(),
565 &acc,
566 libc::O_RDONLY | libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC,
567 0,
568 )
569 .map_err(|e| map_io(&self.authorized, e))?
570 };
571 acc.push(name);
572 match open_beneath(
573 self.workspace.as_raw_fd(),
574 &acc,
575 libc::O_RDONLY | libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC,
576 0,
577 ) {
578 Ok(_) => {}
579 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
580 mkdir_at(parent_fd.as_raw_fd(), name)
581 .map_err(|err| map_io(&self.authorized, err))?;
582 created = true;
583 open_beneath(
584 self.workspace.as_raw_fd(),
585 &acc,
586 libc::O_RDONLY | libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC,
587 0,
588 )
589 .map_err(|err| map_io(&self.authorized, err))?;
590 }
591 Err(e) => return Err(map_io(&self.authorized, e)),
592 }
593 }
594 Ok(created)
595 }
596}
597
598struct PinnedOpen {
599 workspace: OwnedFd,
600 rel: PathBuf,
601 cached: Option<File>,
602}
603
604fn open_pinned(
605 auth: &Authorized,
606 flags: libc::c_int,
607 regular_only: bool,
608) -> Result<PinnedOpen, BindError> {
609 let workspace = open_workspace(&auth.workspace)?;
610 run_before();
611 match open_beneath(workspace.as_raw_fd(), &auth.rel, flags, 0) {
612 Ok(fd) => {
613 let file = File::from(fd);
614 if regular_only {
615 reject_special(&auth.canonical, &file)?;
616 }
617 Ok(PinnedOpen {
618 workspace,
619 rel: auth.rel.clone(),
620 cached: Some(file),
621 })
622 }
623 Err(e) if e.kind() == std::io::ErrorKind::NotFound && !regular_only => {
624 Err(map_io(&auth.canonical, e))
625 }
626 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(PinnedOpen {
627 workspace,
628 rel: auth.rel.clone(),
629 cached: None,
630 }),
631 Err(e) if symlink_component(&e) && final_component_is_symlink(&workspace, &auth.rel) => {
632 let canon_ws = open_workspace(&auth.canon_workspace)?;
633 let fd = open_beneath(canon_ws.as_raw_fd(), &auth.canon_rel, flags, 0)
634 .map_err(|err| map_io(&auth.canonical, err))?;
635 let file = File::from(fd);
636 if regular_only {
637 reject_special(&auth.canonical, &file)?;
638 }
639 Ok(PinnedOpen {
640 workspace: canon_ws,
641 rel: auth.canon_rel.clone(),
642 cached: Some(file),
643 })
644 }
645 Err(e) => Err(map_io(&auth.canonical, e)),
646 }
647}
648
649fn hold(path: &str, write: bool) -> Result<HeldFile, BindError> {
650 let auth = authorize(path)?;
651 // `Path` drops a trailing `/` or `/.`; POSIX does not. Such a name is a
652 // directory, so a write must not create a regular file under it.
653 if auth.rel.as_os_str().is_empty() || (write && (path.ends_with('/') || path.ends_with("/.")))
654 {
655 return Err(BindError::Failed("Is a directory (os error 21)".into()));
656 }
657 let flags = if write {
658 libc::O_RDWR | libc::O_NONBLOCK | libc::O_NOFOLLOW | libc::O_CLOEXEC
659 } else {
660 libc::O_RDONLY | libc::O_NONBLOCK | libc::O_NOFOLLOW | libc::O_CLOEXEC
661 };
662 let pinned = open_pinned(&auth, flags, true)?;
663 run_after();
664 Ok(HeldFile {
665 workspace: pinned.workspace,
666 rel: pinned.rel,
667 authorized: auth.canonical,
668 display: auth.display,
669 cached: Mutex::new(pinned.cached),
670 writable: write,
671 })
672}
673
674pub fn hold_for_write(path: &str) -> Result<HeldFile, BindError> {
675 hold(path, true)
676}
677
678pub fn read_text(path: &str) -> Result<(PathBuf, String), BindError> {
679 let held = hold(path, false)?;
680 let Some(bytes) = held.read_bytes()? else {
681 return Err(BindError::NotFound(
682 "No such file or directory (os error 2)".into(),
683 ));
684 };
685 let text = String::from_utf8(bytes)
686 .map_err(|_| BindError::Failed("stream did not contain valid UTF-8".into()))?;
687 Ok((held.authorized, text))
688}
689
690#[derive(Debug)]
691enum NodeKind {
692 File,
693 Dir,
694 Link,
695 Other,
696}
697
698fn kind_of(mode: u32) -> NodeKind {
699 match mode & libc::S_IFMT {
700 libc::S_IFREG => NodeKind::File,
701 libc::S_IFDIR => NodeKind::Dir,
702 libc::S_IFLNK => NodeKind::Link,
703 _ => NodeKind::Other,
704 }
705}
706
707struct DirEnt {
708 name: OsString,
709 kind: NodeKind,
710 len: u64,
711}
712
713fn list_dirfd(dirfd: libc::c_int) -> std::io::Result<Vec<DirEnt>> {
714 let raw = dup_fd(dirfd)?.into_raw_fd();
715 // SAFETY: `raw` is a live fd. On success fdopendir owns it; on failure
716 // we close it below.
717 let dir = unsafe { libc::fdopendir(raw) };
718 if dir.is_null() {
719 let err = std::io::Error::last_os_error();
720 unsafe { libc::close(raw) };
721 return Err(err);
722 }
723 let mut out = Vec::new();
724 let walked = loop {
725 // SAFETY: `dir` is a live DIR. A null readdir is EOF when errno is 0.
726 unsafe { *libc::__errno_location() = 0 };
727 let ent = unsafe { libc::readdir(dir) };
728 if ent.is_null() {
729 let errno = unsafe { *libc::__errno_location() };
730 break if errno == 0 {
731 Ok(())
732 } else {
733 Err(std::io::Error::from_raw_os_error(errno))
734 };
735 }
736 let name_c = unsafe { std::ffi::CStr::from_ptr((*ent).d_name.as_ptr()) };
737 let name = OsStr::from_bytes(name_c.to_bytes()).to_os_string();
738 if name == "." || name == ".." {
739 continue;
740 }
741 let Ok(c_name) = c_string(name.as_bytes()) else {
742 continue;
743 };
744 let mut st = std::mem::MaybeUninit::<libc::stat>::uninit();
745 // SAFETY: `dirfd` is still the caller's directory (fdopendir consumed
746 // only the duplicate). `c_name` is one entry name. On success `st`
747 // is initialized.
748 let rc = unsafe {
749 libc::fstatat(
750 dirfd,
751 c_name.as_ptr(),
752 st.as_mut_ptr(),
753 libc::AT_SYMLINK_NOFOLLOW,
754 )
755 };
756 if rc != 0 {
757 continue;
758 }
759 let st = unsafe { st.assume_init() };
760 let len = if st.st_size < 0 { 0 } else { st.st_size as u64 };
761 out.push(DirEnt {
762 name,
763 kind: kind_of(st.st_mode),
764 len,
765 });
766 };
767 // SAFETY: `dir` came from fdopendir and has not been closed.
768 unsafe { libc::closedir(dir) };
769 walked?;
770 out.sort_by(|a, b| a.name.cmp(&b.name));
771 Ok(out)
772}
773
774fn open_node(path: &str, directory: bool) -> Result<(Authorized, OwnedFd), BindError> {
775 let auth = authorize(path)?;
776 let flags = if directory {
777 libc::O_RDONLY | libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC
778 } else {
779 libc::O_RDONLY | libc::O_NONBLOCK | libc::O_NOFOLLOW | libc::O_CLOEXEC
780 };
781 let pinned = open_pinned(&auth, flags, false)?;
782 run_after();
783 let Some(file) = pinned.cached else {
784 return Err(BindError::NotFound(
785 "No such file or directory (os error 2)".into(),
786 ));
787 };
788 Ok((auth, OwnedFd::from(file)))
789}
790
791#[derive(Debug, Clone)]
792pub struct ListedEntry {
793 pub name: String,
794 pub is_dir: bool,
795 pub size_bytes: u64,
796}
797
798pub fn list_dir(path: &str) -> Result<(PathBuf, Vec<ListedEntry>), BindError> {
799 let (auth, fd) = open_node(path, true)?;
800 let ents = list_dirfd(fd.as_raw_fd()).map_err(|e| map_io(&auth.canonical, e))?;
801 let rows = ents
802 .into_iter()
803 .map(|e| ListedEntry {
804 name: e.name.to_string_lossy().into_owned(),
805 is_dir: matches!(e.kind, NodeKind::Dir),
806 size_bytes: e.len,
807 })
808 .collect();
809 Ok((auth.canonical, rows))
810}
811
812pub fn make_dir(path: &str) -> Result<PathBuf, BindError> {
813 let auth = authorize(path)?;
814 // An existing directory, or a final-component symlink to one, is opened
815 // the way `list_dir` opens it. Only a missing name goes on to be created.
816 match open_pinned(
817 &auth,
818 libc::O_RDONLY | libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC,
819 false,
820 ) {
821 Ok(_) => {
822 run_after();
823 return Ok(auth.canonical);
824 }
825 Err(BindError::NotFound(_)) => {}
826 Err(e) => return Err(e),
827 }
828 let held = HeldFile {
829 workspace: open_workspace(&auth.workspace)?,
830 rel: auth.rel.clone(),
831 authorized: auth.canonical.clone(),
832 display: auth.display.clone(),
833 cached: Mutex::new(None),
834 writable: true,
835 };
836 held.ensure_dirs(&auth.rel)?;
837 // Confirm the final directory is still the one beneath the workspace.
838 open_beneath(
839 held.workspace.as_raw_fd(),
840 &auth.rel,
841 libc::O_RDONLY | libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC,
842 0,
843 )
844 .map_err(|e| map_io(&auth.canonical, e))?;
845 run_after();
846 Ok(auth.canonical)
847}
848
849fn grep_bytes(query: &str, bytes: &[u8]) -> Result<Vec<String>, BindError> {
850 let mut child = Command::new("grep")
851 .args(["-nI", "-e", query])
852 .stdin(Stdio::piped())
853 .stdout(Stdio::piped())
854 .stderr(Stdio::piped())
855 .spawn()
856 .map_err(|e| BindError::Failed(format!("failed to run grep: {e}")))?;
857 let mut stdin = child
858 .stdin
859 .take()
860 .ok_or_else(|| BindError::Failed("grep stdin is unavailable".into()))?;
861 let mut stdout = child
862 .stdout
863 .take()
864 .ok_or_else(|| BindError::Failed("grep stdout is unavailable".into()))?;
865 let mut stderr = child
866 .stderr
867 .take()
868 .ok_or_else(|| BindError::Failed("grep stderr is unavailable".into()))?;
869 // Write stdin on another thread. Reading stdout only after the write
870 // fills both pipes once the match output exceeds the kernel buffer.
871 let payload = bytes.to_vec();
872 let writer = std::thread::spawn(move || {
873 let _ = stdin.write_all(&payload);
874 });
875 let err_reader = std::thread::spawn(move || {
876 let mut buf = Vec::new();
877 let _ = stderr.read_to_end(&mut buf);
878 buf
879 });
880 let mut out = Vec::new();
881 let read_result = stdout.read_to_end(&mut out);
882 let status = child.wait();
883 let _ = writer.join();
884 let err_buf = err_reader.join().unwrap_or_default();
885 read_result.map_err(|e| BindError::Failed(format!("grep failed: {e}")))?;
886 let status = status.map_err(|e| BindError::Failed(format!("grep failed: {e}")))?;
887 if status.code() == Some(2) {
888 let err = String::from_utf8_lossy(&err_buf);
889 return Err(BindError::Failed(format!(
890 "grep refused the pattern: {}",
891 err.trim()
892 )));
893 }
894 let text = String::from_utf8_lossy(&out);
895 Ok(text.lines().map(|s| s.to_string()).collect())
896}
897
898fn display_of(display_root: &str, root: &Path, child: &Path) -> String {
899 match child.strip_prefix(root) {
900 Ok(rel) if !rel.as_os_str().is_empty() => {
901 Path::new(display_root).join(rel).display().to_string()
902 }
903 _ => display_root.to_string(),
904 }
905}
906
907fn name_matches(pattern: &str, name: &str) -> bool {
908 let Ok(pat) = CString::new(pattern) else {
909 return false;
910 };
911 let Ok(nm) = CString::new(name) else {
912 return false;
913 };
914 // SAFETY: both pointers are valid C strings. fnmatch does not retain them.
915 unsafe { libc::fnmatch(pat.as_ptr(), nm.as_ptr(), 0) == 0 }
916}
917
918fn open_child(dirfd: libc::c_int, name: &OsStr, flags: libc::c_int) -> std::io::Result<OwnedFd> {
919 let c = c_string(name.as_bytes())?;
920 // SAFETY: `dirfd` is a directory we hold and `c` is a single component.
921 let fd = unsafe { libc::openat(dirfd, c.as_ptr(), flags) };
922 if fd < 0 {
923 return Err(std::io::Error::last_os_error());
924 }
925 Ok(unsafe { OwnedFd::from_raw_fd(fd) })
926}
927
928/// Directory descriptors held by one walk: the root plus the ancestors of
929/// the directory currently being listed. Sibling directories stay as names
930/// until their turn, so a wide tree does not open one fd per child.
931const MAX_WALK_DEPTH: usize = 64;
932
933#[cfg(test)]
934thread_local! {
935 static WALK_FD_MAX: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
936}
937
938#[cfg(test)]
939fn note_walk_fds(n: usize) {
940 WALK_FD_MAX.with(|c| {
941 if n > c.get() {
942 c.set(n);
943 }
944 });
945}
946
947#[cfg(test)]
948fn take_walk_fd_max() -> usize {
949 WALK_FD_MAX.with(|c| c.replace(0))
950}
951
952#[cfg(not(test))]
953fn note_walk_fds(_n: usize) {}
954
955struct WalkFrame {
956 dir: OwnedFd,
957 path: PathBuf,
958 listed: bool,
959 subdirs: Vec<OsString>,
960}
961
962/// Walk `root`, never following symlinks. `visit` returns false to stop.
963fn walk_nofollow(
964 root: &Path,
965 dirfd: libc::c_int,
966 limit_hit: &mut bool,
967 mut visit: impl FnMut(&Path, &DirEnt, Option<File>) -> Result<bool, BindError>,
968) -> Result<(), BindError> {
969 let mut stack = vec![WalkFrame {
970 dir: dup_fd(dirfd).map_err(|e| map_io(root, e))?,
971 path: root.to_path_buf(),
972 listed: false,
973 subdirs: Vec::new(),
974 }];
975 note_walk_fds(stack.len());
976 while !stack.is_empty() {
977 if *limit_hit {
978 break;
979 }
980 if !stack.last().is_some_and(|f| f.listed) {
981 let fd = stack.last().unwrap().dir.as_raw_fd();
982 let dir_path = stack.last().unwrap().path.clone();
983 let ents = list_dirfd(fd).map_err(|e| map_io(&dir_path, e))?;
984 let mut subdirs = Vec::new();
985 for ent in ents {
986 let child_path = dir_path.join(&ent.name);
987 match ent.kind {
988 NodeKind::Dir => {
989 let cont = visit(&child_path, &ent, None)?;
990 if !cont {
991 *limit_hit = true;
992 break;
993 }
994 subdirs.push(ent.name);
995 }
996 NodeKind::File => {
997 match open_child(
998 fd,
999 &ent.name,
1000 libc::O_RDONLY | libc::O_NONBLOCK | libc::O_NOFOLLOW | libc::O_CLOEXEC,
1001 ) {
1002 Ok(raw) => {
1003 let file = File::from(raw);
1004 let cont = visit(&child_path, &ent, Some(file))?;
1005 if !cont {
1006 *limit_hit = true;
1007 break;
1008 }
1009 }
1010 Err(e) if e.raw_os_error() == Some(libc::ELOOP) => {}
1011 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
1012 Err(_) => {}
1013 }
1014 }
1015 NodeKind::Link | NodeKind::Other => {
1016 let cont = visit(&child_path, &ent, None)?;
1017 if !cont {
1018 *limit_hit = true;
1019 break;
1020 }
1021 }
1022 }
1023 }
1024 let frame = stack.last_mut().unwrap();
1025 frame.subdirs = subdirs;
1026 frame.listed = true;
1027 continue;
1028 }
1029 let name = stack.last_mut().unwrap().subdirs.pop();
1030 let Some(name) = name else {
1031 stack.pop();
1032 continue;
1033 };
1034 if stack.len() >= MAX_WALK_DEPTH {
1035 return Err(BindError::Denied(
1036 "refusing the directory walk: the tree is too deep".into(),
1037 ));
1038 }
1039 let parent = stack.last().unwrap().dir.as_raw_fd();
1040 let child_path = stack.last().unwrap().path.join(&name);
1041 match open_child(
1042 parent,
1043 &name,
1044 libc::O_RDONLY | libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC,
1045 ) {
1046 Ok(child) => {
1047 stack.push(WalkFrame {
1048 dir: child,
1049 path: child_path,
1050 listed: false,
1051 subdirs: Vec::new(),
1052 });
1053 note_walk_fds(stack.len());
1054 }
1055 Err(e) if e.raw_os_error() == Some(libc::ELOOP) => {}
1056 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
1057 Err(e) => return Err(map_io(&child_path, e)),
1058 }
1059 }
1060 Ok(())
1061}
1062
1063pub fn grep_search(path: &str, query: &str, limit: usize) -> Result<Vec<String>, BindError> {
1064 // One open. A second lookup after this returns would authorize whatever
1065 // the name points at now, which is a different request.
1066 let (auth, fd) = open_node(path, false)?;
1067 let mut file = File::from(fd);
1068 let meta = file
1069 .metadata()
1070 .map_err(|e| BindError::Failed(e.to_string()))?;
1071 let mut matches = Vec::new();
1072 if meta.is_file() {
1073 let bytes = read_all(&mut file)?;
1074 for line in grep_bytes(query, &bytes)? {
1075 matches.push(format!("{}:{line}", auth.display));
1076 if matches.len() >= limit {
1077 break;
1078 }
1079 }
1080 return Ok(matches);
1081 }
1082 if !meta.is_dir() {
1083 return Err(BindError::Denied(format!(
1084 "refusing '{}': authorized target is not a file or directory",
1085 safe_label(&auth.rel)
1086 )));
1087 }
1088 let root = auth.canonical.clone();
1089 let shown = auth.display.clone();
1090 let mut stop = false;
1091 walk_nofollow(&root, file.as_raw_fd(), &mut stop, |child, ent, file| {
1092 if !matches!(ent.kind, NodeKind::File) {
1093 return Ok(true);
1094 }
1095 let Some(mut file) = file else {
1096 return Ok(true);
1097 };
1098 let bytes = read_all(&mut file)?;
1099 for line in grep_bytes(query, &bytes)? {
1100 matches.push(format!("{}:{line}", display_of(&shown, &root, child)));
1101 if matches.len() >= limit {
1102 return Ok(false);
1103 }
1104 }
1105 Ok(true)
1106 })?;
1107 Ok(matches)
1108}
1109
1110pub fn find_names(path: &str, pattern: &str, limit: usize) -> Result<Vec<String>, BindError> {
1111 let (auth, fd) = open_node(path, false)?;
1112 let file = File::from(fd);
1113 let meta = file
1114 .metadata()
1115 .map_err(|e| BindError::Failed(e.to_string()))?;
1116 let mut matches = Vec::new();
1117 // Match the root by the name the caller gave, as find(1) does: a
1118 // symlinked root keeps its own name. `..` or `.` has no name to match.
1119 let root_name = Path::new(&auth.display)
1120 .file_name()
1121 .or_else(|| auth.canonical.file_name())
1122 .map(|n| n.to_string_lossy().into_owned())
1123 .unwrap_or_default();
1124 if meta.is_file() {
1125 if name_matches(pattern, &root_name) {
1126 matches.push(auth.display.clone());
1127 }
1128 return Ok(matches);
1129 }
1130 if !meta.is_dir() {
1131 return Err(BindError::Denied(format!(
1132 "refusing '{}': authorized target is not a file or directory",
1133 safe_label(&auth.rel)
1134 )));
1135 }
1136 if name_matches(pattern, &root_name) {
1137 matches.push(auth.display.clone());
1138 }
1139 let root = auth.canonical.clone();
1140 let shown = auth.display.clone();
1141 let mut stop = matches.len() >= limit;
1142 walk_nofollow(&root, file.as_raw_fd(), &mut stop, |child, ent, _| {
1143 let name = ent.name.to_string_lossy();
1144 if name_matches(pattern, &name) {
1145 matches.push(display_of(&shown, &root, child));
1146 if matches.len() >= limit {
1147 return Ok(false);
1148 }
1149 }
1150 Ok(true)
1151 })?;
1152 Ok(matches)
1153}
1154
1155#[cfg(test)]
1156pub mod test_hooks {
1157 use std::cell::RefCell;
1158
1159 thread_local! {
1160 static BEFORE: RefCell<Option<Box<dyn FnOnce()>>> = const { RefCell::new(None) };
1161 static AFTER: RefCell<Option<Box<dyn FnOnce()>>> = const { RefCell::new(None) };
1162 static OPENAT2_ERR: std::cell::Cell<Option<i32>> = const { std::cell::Cell::new(None) };
1163 static WORKSPACES: RefCell<Option<Vec<std::path::PathBuf>>> = const { RefCell::new(None) };
1164 }
1165
1166 /// `permitted_workspaces` returns exactly `roots` on this thread, so a
1167 /// test can hold two permitted roots without touching real user dirs.
1168 pub fn set_workspaces(roots: Vec<std::path::PathBuf>) {
1169 WORKSPACES.with(|c| *c.borrow_mut() = Some(roots));
1170 }
1171
1172 pub(super) fn workspaces() -> Option<Vec<std::path::PathBuf>> {
1173 WORKSPACES.with(|c| c.borrow().clone())
1174 }
1175
1176 /// Next `openat2` returns this errno instead of calling the kernel.
1177 /// One shot, so a later open in the same call is real.
1178 pub fn set_openat2_error(code: i32) {
1179 OPENAT2_ERR.with(|c| c.set(Some(code)));
1180 }
1181
1182 pub(super) fn take_openat2_error() -> Option<i32> {
1183 OPENAT2_ERR.with(|c| c.take())
1184 }
1185
1186 pub fn set_before_open(f: impl FnOnce() + 'static) {
1187 BEFORE.with(|c| *c.borrow_mut() = Some(Box::new(f)));
1188 }
1189
1190 pub fn set_after_open(f: impl FnOnce() + 'static) {
1191 AFTER.with(|c| *c.borrow_mut() = Some(Box::new(f)));
1192 }
1193
1194 pub fn clear() {
1195 BEFORE.with(|c| *c.borrow_mut() = None);
1196 AFTER.with(|c| *c.borrow_mut() = None);
1197 OPENAT2_ERR.with(|c| c.set(None));
1198 WORKSPACES.with(|c| *c.borrow_mut() = None);
1199 }
1200
1201 pub(super) fn run_before() {
1202 if let Some(f) = BEFORE.with(|c| c.borrow_mut().take()) {
1203 f();
1204 }
1205 }
1206
1207 pub(super) fn run_after() {
1208 if let Some(f) = AFTER.with(|c| c.borrow_mut().take()) {
1209 f();
1210 }
1211 }
1212}
1213
1214#[cfg(not(test))]
1215fn run_before() {}
1216
1217#[cfg(not(test))]
1218fn run_after() {}
1219
1220#[cfg(test)]
1221fn run_before() {
1222 test_hooks::run_before();
1223}
1224
1225#[cfg(test)]
1226fn run_after() {
1227 test_hooks::run_after();
1228}
1229
1230#[cfg(test)]
1231mod tests {
1232 use super::*;
1233 use std::os::unix::fs::symlink;
1234 use std::sync::atomic::{AtomicBool, Ordering};
1235 use std::time::{Duration, Instant};
1236
1237 const INSIDE: &str = "INSIDE_MARKER";
1238 const OTHER: &str = "OTHER_MARKER";
1239 const OUTSIDE: &str = "OUTSIDE_MARKER";
1240
1241 struct ClearHooks;
1242 impl Drop for ClearHooks {
1243 fn drop(&mut self) {
1244 test_hooks::clear();
1245 }
1246 }
1247
1248 struct Scratch {
1249 _root: tempfile::TempDir,
1250 ws: PathBuf,
1251 other: PathBuf,
1252 }
1253
1254 fn scratch() -> Scratch {
1255 let root = tempfile::tempdir_in("/tmp").unwrap();
1256 let root_path = root.path().canonicalize().unwrap();
1257 let ws = root_path.join("ws");
1258 let other = root_path.join("other");
1259 std::fs::create_dir_all(ws.join("d")).unwrap();
1260 std::fs::create_dir_all(&other).unwrap();
1261 std::fs::write(ws.join("d/f"), INSIDE).unwrap();
1262 std::fs::write(other.join("f"), OTHER).unwrap();
1263 Scratch {
1264 _root: root,
1265 ws,
1266 other,
1267 }
1268 }
1269
1270 fn outside_scratch() -> tempfile::TempDir {
1271 let base = PathBuf::from("/dev/shm");
1272 assert!(
1273 base.is_dir(),
1274 "/dev/shm is required for an unpermitted scratch dir"
1275 );
1276 let dir = tempfile::tempdir_in(&base).unwrap();
1277 let marker = dir.path().join("secret");
1278 std::fs::write(&marker, OUTSIDE).unwrap();
1279 assert!(
1280 validate_workspace_path(&marker, &permitted_workspaces()).is_err(),
1281 "unpermitted scratch resolved inside a workspace; the check would not prove confinement"
1282 );
1283 dir
1284 }
1285
1286 /// A fresh open during a directory swap may see the original file or a
1287 /// denial. The other workspace file and the unpermitted file are rejected.
1288 /// Accepting either of those is the broken implementation.
1289 fn fresh_swap_read_is_inside(text: &str) -> bool {
1290 text == INSIDE
1291 }
1292
1293 #[test]
1294 fn fresh_swap_read_rejects_the_other_and_outside_markers() {
1295 assert!(fresh_swap_read_is_inside(INSIDE));
1296 assert!(!fresh_swap_read_is_inside(OTHER));
1297 assert!(!fresh_swap_read_is_inside(OUTSIDE));
1298 }
1299
1300 #[test]
1301 fn read_all_accepts_the_limit_and_refuses_one_byte_more() {
1302 let dir = tempfile::tempdir_in("/tmp").unwrap();
1303 let path = dir.path().join("f");
1304 let at_limit = vec![b'a'; READ_LIMIT as usize];
1305 std::fs::write(&path, &at_limit).unwrap();
1306 let mut f = File::open(&path).unwrap();
1307 let got = read_all(&mut f).expect("a file of exactly READ_LIMIT bytes is read");
1308 assert_eq!(got.len() as u64, READ_LIMIT);
1309
1310 std::fs::OpenOptions::new()
1311 .append(true)
1312 .open(&path)
1313 .unwrap()
1314 .write_all(b"a")
1315 .unwrap();
1316 let mut f = File::open(&path).unwrap();
1317 assert!(
1318 matches!(read_all(&mut f), Err(BindError::Denied(_))),
1319 "a file of READ_LIMIT + 1 bytes must be refused"
1320 );
1321 }
1322
1323 /// An endless source that panics once a caller pulls more than
1324 /// `budget` bytes from it. An unbounded read trips the panic.
1325 struct Endless {
1326 served: u64,
1327 budget: u64,
1328 }
1329
1330 impl Read for Endless {
1331 fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
1332 buf.fill(b'z');
1333 self.served += buf.len() as u64;
1334 assert!(
1335 self.served <= self.budget,
1336 "read past the cap: {} bytes pulled, budget {}",
1337 self.served,
1338 self.budget
1339 );
1340 Ok(buf.len())
1341 }
1342 }
1343
1344 #[test]
1345 fn read_capped_stops_one_byte_past_the_limit_on_an_endless_source() {
1346 let limit = 4096;
1347 let mut src = Endless {
1348 served: 0,
1349 budget: limit + 1,
1350 };
1351 assert!(matches!(
1352 read_capped(&mut src, limit),
1353 Err(BindError::Denied(_))
1354 ));
1355 assert_eq!(src.served, limit + 1, "exactly limit + 1 bytes are pulled");
1356 }
1357
1358 fn swap_dir(dir: &Path, elsewhere: &Path) {
1359 let parked = dir.with_file_name("d.held");
1360 std::fs::rename(dir, &parked).unwrap();
1361 symlink(elsewhere, dir).unwrap();
1362 }
1363
1364 #[test]
1365 fn ordinary_read_write_list_create_search_round_trip() {
1366 let root = tempfile::tempdir_in("/tmp").unwrap();
1367 let root = root.path().canonicalize().unwrap();
1368 let file = root.join("note.txt");
1369 let held = hold_for_write(file.to_str().unwrap()).unwrap();
1370 held.write_bytes(b"alpha beta", true).unwrap();
1371 let (path, text) = read_text(file.to_str().unwrap()).unwrap();
1372 assert_eq!(path, file);
1373 assert_eq!(text, "alpha beta");
1374 held.overwrite_existing(b"alpha gamma").unwrap();
1375 let (_, text) = read_text(file.to_str().unwrap()).unwrap();
1376 assert_eq!(text, "alpha gamma");
1377
1378 let nested = root.join("sub/leaf");
1379 let created = make_dir(nested.to_str().unwrap()).unwrap();
1380 assert!(created.is_dir());
1381 let (listed_at, rows) = list_dir(root.to_str().unwrap()).unwrap();
1382 assert_eq!(listed_at, root);
1383 assert!(rows.iter().any(|r| r.name == "note.txt" && !r.is_dir));
1384 assert!(rows.iter().any(|r| r.name == "sub" && r.is_dir));
1385
1386 let hits = grep_search(root.to_str().unwrap(), "gamma", 50).unwrap();
1387 assert!(hits
1388 .iter()
1389 .any(|h| h.contains("note.txt") && h.contains("gamma")));
1390 let found = find_names(root.to_str().unwrap(), "note.txt", 50).unwrap();
1391 assert_eq!(found, vec![file.display().to_string()]);
1392 }
1393
1394 #[test]
1395 fn in_workspace_symlink_reads_the_canonical_file() {
1396 let s = scratch();
1397 let link = s.ws.join("alias");
1398 symlink(s.ws.join("d/f"), &link).unwrap();
1399 let (_, text) = read_text(link.to_str().unwrap()).unwrap();
1400 assert_eq!(text, INSIDE);
1401 }
1402
1403 #[test]
1404 fn symlink_to_unpermitted_target_is_denied() {
1405 let s = scratch();
1406 let outside = outside_scratch();
1407 let link = s.ws.join("leak");
1408 symlink(outside.path().join("secret"), &link).unwrap();
1409 let err = read_text(link.to_str().unwrap()).unwrap_err();
1410 assert!(matches!(err, BindError::Denied(_)), "{err:?}");
1411 assert!(!err.message().contains(OUTSIDE));
1412 assert_eq!(
1413 std::fs::read_to_string(outside.path().join("secret")).unwrap(),
1414 OUTSIDE
1415 );
1416 }
1417
1418 #[test]
1419 fn parent_dotdot_through_symlink_is_denied() {
1420 let s = scratch();
1421 let outside = outside_scratch();
1422 std::fs::create_dir(outside.path().join("child")).unwrap();
1423 symlink(outside.path().join("child"), s.ws.join("link")).unwrap();
1424 let probe = s.ws.join("link/../secret");
1425 let err = read_text(probe.to_str().unwrap()).unwrap_err();
1426 assert!(matches!(err, BindError::Denied(_)), "{err:?}");
1427 assert!(!err.message().contains(OUTSIDE));
1428 }
1429
1430 const DECOY: &str = "DECOY_MARKER";
1431 const REAL: &str = "REAL_MARKER";
1432
1433 /// `ws/link -> ws/a/b`. `ws/a/x` holds REAL when `real` is set and `ws/x`
1434 /// holds DECOY when `decoy` is set. The OS and the allow-list resolve
1435 /// `ws/link/../x` to `ws/a/x`; dropping `link/..` as text names `ws/x`.
1436 fn dotdot_layout(real: bool, decoy: bool) -> Scratch {
1437 let s = scratch();
1438 std::fs::create_dir_all(s.ws.join("a/b")).unwrap();
1439 symlink(s.ws.join("a/b"), s.ws.join("link")).unwrap();
1440 if real {
1441 std::fs::write(s.ws.join("a/x"), REAL).unwrap();
1442 }
1443 if decoy {
1444 std::fs::write(s.ws.join("x"), DECOY).unwrap();
1445 }
1446 s
1447 }
1448
1449 /// The call either acted on the authorized object (`ok`) or was denied.
1450 fn authorized_or_denied<T: std::fmt::Debug>(r: Result<T, BindError>, ok: impl FnOnce(T)) {
1451 match r {
1452 Ok(v) => ok(v),
1453 Err(BindError::Denied(m)) => {
1454 assert!(!m.contains(DECOY) && !m.contains(REAL), "{m}")
1455 }
1456 Err(e) => panic!("expected the authorized object or a denial, got {e:?}"),
1457 }
1458 }
1459
1460 fn write_through(path: &Path, content: &[u8]) -> Result<bool, BindError> {
1461 hold_for_write(path.to_str().unwrap())?.write_bytes(content, true)
1462 }
1463
1464 #[test]
1465 fn dotdot_after_a_symlink_never_reads_the_lexical_decoy() {
1466 let s = dotdot_layout(true, true);
1467 let probe = s.ws.join("link/../x");
1468 assert_eq!(
1469 validate_workspace_path(&probe, &permitted_workspaces()).unwrap(),
1470 s.ws.join("a/x")
1471 );
1472 assert_eq!(std::fs::read_to_string(&probe).unwrap(), REAL);
1473 authorized_or_denied(read_text(probe.to_str().unwrap()), |(path, text)| {
1474 assert_eq!(text, REAL, "opened a different file from the authorized one");
1475 assert_eq!(path, s.ws.join("a/x"));
1476 });
1477 authorized_or_denied(
1478 grep_search(probe.to_str().unwrap(), "MARKER", 50),
1479 |hits| assert!(hits.iter().all(|h| !h.contains(DECOY)), "{hits:?}"),
1480 );
1481 }
1482
1483 #[test]
1484 fn dotdot_after_a_symlink_never_overwrites_the_lexical_decoy() {
1485 let s = dotdot_layout(true, true);
1486 let probe = s.ws.join("link/../x");
1487 authorized_or_denied(write_through(&probe, b"NEW"), |_| {
1488 assert_eq!(std::fs::read_to_string(s.ws.join("a/x")).unwrap(), "NEW")
1489 });
1490 assert_eq!(std::fs::read_to_string(s.ws.join("x")).unwrap(), DECOY);
1491 }
1492
1493 #[test]
1494 fn dotdot_after_a_symlink_never_creates_the_lexical_decoy() {
1495 for real in [true, false] {
1496 let s = dotdot_layout(real, false);
1497 let probe = s.ws.join("link/../x");
1498 authorized_or_denied(write_through(&probe, b"NEW"), |_| {
1499 assert!(real, "created a file the allow-list never authorized");
1500 assert_eq!(std::fs::read_to_string(s.ws.join("a/x")).unwrap(), "NEW")
1501 });
1502 assert!(
1503 s.ws.join("x").symlink_metadata().is_err(),
1504 "write through link/.. created ws/x (real={real})"
1505 );
1506 }
1507 }
1508
1509 #[test]
1510 fn dotdot_after_a_symlink_never_lists_or_makes_the_lexical_parent() {
1511 let s = dotdot_layout(true, true);
1512 authorized_or_denied(
1513 list_dir(s.ws.join("link/..").to_str().unwrap()),
1514 |(path, rows)| {
1515 assert_eq!(path, s.ws.join("a"));
1516 let names: Vec<_> = rows.iter().map(|r| r.name.as_str()).collect();
1517 assert_eq!(names, ["b", "x"], "listed a different directory");
1518 },
1519 );
1520 authorized_or_denied(
1521 make_dir(s.ws.join("link/../made").to_str().unwrap()),
1522 |path| {
1523 assert_eq!(path, s.ws.join("a/made"));
1524 assert!(path.is_dir());
1525 },
1526 );
1527 assert!(s.ws.join("made").symlink_metadata().is_err());
1528 }
1529
1530 #[test]
1531 fn dotdot_after_a_symlink_never_crosses_into_the_lexical_workspace() {
1532 let _clear = ClearHooks;
1533 let root = tempfile::tempdir_in("/tmp").unwrap();
1534 let base = root.path().canonicalize().unwrap();
1535 let (ws_a, ws_b) = (base.join("A"), base.join("B"));
1536 std::fs::create_dir_all(ws_b.join("sub")).unwrap();
1537 std::fs::create_dir_all(&ws_a).unwrap();
1538 std::fs::write(ws_a.join("x"), DECOY).unwrap();
1539 std::fs::write(ws_b.join("x"), REAL).unwrap();
1540 symlink(ws_b.join("sub"), ws_a.join("link")).unwrap();
1541 test_hooks::set_workspaces(vec![ws_a.clone(), ws_b.clone()]);
1542 let probe = ws_a.join("link/../x");
1543 // Both files are permitted; the allow-list picked the one in B.
1544 assert_eq!(
1545 validate_workspace_path(&probe, &permitted_workspaces()).unwrap(),
1546 ws_b.join("x")
1547 );
1548 assert!(validate_workspace_path(ws_a.join("x"), &permitted_workspaces()).is_ok());
1549 authorized_or_denied(read_text(probe.to_str().unwrap()), |(_, text)| {
1550 assert_eq!(text, REAL, "read workspace A for a path authorized in B")
1551 });
1552 authorized_or_denied(write_through(&probe, b"NEW"), |_| {
1553 assert_eq!(std::fs::read_to_string(ws_b.join("x")).unwrap(), "NEW")
1554 });
1555 assert_eq!(std::fs::read_to_string(ws_a.join("x")).unwrap(), DECOY);
1556 }
1557
1558 #[test]
1559 fn dotdot_through_real_directories_still_opens_the_resolved_path() {
1560 let s = scratch();
1561 let (_, text) = read_text(s.ws.join("d/../d/f").to_str().unwrap()).unwrap();
1562 assert_eq!(text, INSIDE);
1563 symlink(s.ws.join("d/f"), s.ws.join("alias")).unwrap();
1564 let (_, text) = read_text(s.ws.join("d/../alias").to_str().unwrap()).unwrap();
1565 assert_eq!(text, INSIDE);
1566 write_through(&s.ws.join("d/../d/g"), b"G").unwrap();
1567 assert_eq!(std::fs::read_to_string(s.ws.join("d/g")).unwrap(), "G");
1568 let made = make_dir(s.ws.join("d/../d/sub/leaf").to_str().unwrap()).unwrap();
1569 assert_eq!(made, s.ws.join("d/sub/leaf"));
1570 assert!(made.is_dir());
1571 }
1572
1573 #[test]
1574 fn dotdot_open_survives_concurrent_renames() {
1575 let s = scratch();
1576 let stop = std::sync::Arc::new(AtomicBool::new(false));
1577 let (flag, other) = (stop.clone(), s.other.clone());
1578 let renamer = std::thread::spawn(move || {
1579 while !flag.load(Ordering::Relaxed) {
1580 std::fs::rename(other.join("f"), other.join("g")).unwrap();
1581 std::fs::rename(other.join("g"), other.join("f")).unwrap();
1582 }
1583 });
1584 let probe = s.ws.join("d/../d/f");
1585 let failures = (0..5000)
1586 .filter(|_| read_text(probe.to_str().unwrap()).is_err())
1587 .count();
1588 stop.store(true, Ordering::Relaxed);
1589 renamer.join().unwrap();
1590 assert_eq!(failures, 0, "a rename elsewhere failed a `..` open");
1591 }
1592
1593 #[test]
1594 fn dotdot_above_the_deepest_workspace_uses_the_enclosing_one() {
1595 let _clear = ClearHooks;
1596 let s = scratch();
1597 test_hooks::set_workspaces(vec![s.ws.parent().unwrap().to_path_buf(), s.ws.clone()]);
1598 let (_, text) = read_text(s.ws.join("../other/f").to_str().unwrap()).unwrap();
1599 assert_eq!(text, OTHER);
1600 }
1601
1602 #[test]
1603 fn write_to_a_trailing_slash_name_never_creates_a_file() {
1604 let s = scratch();
1605 let named = |rest: &str| format!("{}/{rest}", s.ws.display());
1606 for name in ["d/new/", "d/new/."] {
1607 let err = hold_for_write(&named(name))
1608 .and_then(|h| h.write_bytes(b"x", false))
1609 .unwrap_err();
1610 assert!(err.message().contains("Is a directory"), "{name}: {err:?}");
1611 assert!(
1612 s.ws.join("d/new").symlink_metadata().is_err(),
1613 "{name} created d/new"
1614 );
1615 }
1616 // Directory-shaped names keep working where a directory is meant.
1617 assert!(matches!(
1618 read_text(&named("d/new/")),
1619 Err(BindError::NotFound(_))
1620 ));
1621 make_dir(&named("d/new/")).unwrap();
1622 assert!(s.ws.join("d/new").is_dir());
1623 let (_, rows) = list_dir(&named("d/")).unwrap();
1624 assert!(rows.iter().any(|r| r.name == "new" && r.is_dir));
1625 }
1626
1627 /// `real` is configured as `alias -> real`, alone or under an enclosing
1628 /// root that also matches the named path.
1629 fn symlinked_root_is_usable(nested: bool) {
1630 let _clear = ClearHooks;
1631 let s = scratch();
1632 let base = s.ws.parent().unwrap().to_path_buf();
1633 let real = s.ws.clone();
1634 let alias = base.join("alias");
1635 symlink(&real, &alias).unwrap();
1636 let at = |rest: &str| alias.join(rest).to_str().unwrap().to_string();
1637 let roots = if nested {
1638 vec![base.clone(), alias.clone()]
1639 } else {
1640 vec![alias.clone()]
1641 };
1642 test_hooks::set_workspaces(roots);
1643 assert_eq!(
1644 validate_workspace_path(alias.join("d/f"), &permitted_workspaces()).unwrap(),
1645 real.join("d/f")
1646 );
1647 let (path, text) = read_text(&at("d/f")).unwrap();
1648 assert_eq!((path, text.as_str()), (real.join("d/f"), INSIDE));
1649 hold_for_write(&at("g"))
1650 .and_then(|h| h.write_bytes(b"G", false))
1651 .unwrap();
1652 assert_eq!(std::fs::read_to_string(real.join("g")).unwrap(), "G");
1653 assert_eq!(make_dir(&at("n")).unwrap(), real.join("n"));
1654 assert!(real.join("n").is_dir());
1655 let (listed, _) = list_dir(&at("d")).unwrap();
1656 assert_eq!(listed, real.join("d"));
1657 }
1658
1659 #[test]
1660 fn a_workspace_root_configured_through_a_symlink_is_usable() {
1661 symlinked_root_is_usable(false);
1662 }
1663
1664 #[test]
1665 fn a_symlinked_root_nested_under_another_root_is_usable() {
1666 symlinked_root_is_usable(true);
1667 }
1668
1669 #[test]
1670 fn make_dir_accepts_an_existing_directory_symlink_like_list_dir() {
1671 let s = scratch();
1672 let dl = s.ws.join("dl");
1673 symlink(s.ws.join("d"), &dl).unwrap();
1674 assert_eq!(list_dir(dl.to_str().unwrap()).unwrap().0, s.ws.join("d"));
1675 assert_eq!(make_dir(dl.to_str().unwrap()).unwrap(), s.ws.join("d"));
1676 assert!(dl.symlink_metadata().unwrap().file_type().is_symlink());
1677 // A symlink to a file is not a directory.
1678 let fl = s.ws.join("fl");
1679 symlink(s.ws.join("d/f"), &fl).unwrap();
1680 assert!(make_dir(fl.to_str().unwrap()).is_err());
1681 assert_eq!(std::fs::read_to_string(s.ws.join("d/f")).unwrap(), INSIDE);
1682 // A symlink before the last component stays refused.
1683 assert!(matches!(
1684 make_dir(dl.join("new").to_str().unwrap()),
1685 Err(BindError::Denied(_))
1686 ));
1687 assert!(!s.ws.join("d/new").exists());
1688 }
1689
1690 #[test]
1691 fn find_names_matches_a_symlinked_root_by_the_name_given() {
1692 let s = scratch();
1693 std::fs::write(s.ws.join("d/hit.txt"), "HIT\n").unwrap();
1694 let dl = s.ws.join("dl");
1695 let fl = s.ws.join("fl");
1696 symlink(s.ws.join("d"), &dl).unwrap();
1697 symlink(s.ws.join("d/hit.txt"), &fl).unwrap();
1698 let find = |p: &Path, pat: &str| find_names(p.to_str().unwrap(), pat, 50).unwrap();
1699 let (dl_s, fl_s) = (dl.display().to_string(), fl.display().to_string());
1700 // find(1) semantics: the root is named by the caller's last component.
1701 assert_eq!(find(&dl, "dl"), vec![dl_s.clone()]);
1702 assert!(!find(&dl, "d").contains(&dl_s));
1703 assert_eq!(find(&fl, "fl"), vec![fl_s.clone()]);
1704 assert!(find(&fl, "hit.txt").is_empty());
1705 // No name to match (`..`): the resolved directory's name is used.
1706 let up = s.ws.join("d/..");
1707 assert_eq!(find(&up, "ws"), vec![up.display().to_string()]);
1708 }
1709
1710 fn assert_no_host_path(msg: &str, hidden: &[&Path]) {
1711 for prefix in ["/tmp", "/dev", "/etc", "/home", "/workspace", "/usr"] {
1712 assert!(!msg.contains(prefix), "{msg}");
1713 }
1714 for path in hidden {
1715 let text = path.display().to_string();
1716 if !text.is_empty() {
1717 assert!(!msg.contains(&text), "{msg} contains {text}");
1718 }
1719 }
1720 }
1721
1722 #[test]
1723 fn error_text_omits_host_absolute_paths() {
1724 let s = scratch();
1725 let outside = outside_scratch();
1726 let link = s.ws.join("leak");
1727 symlink(outside.path().join("secret"), &link).unwrap();
1728 let err = read_text(link.to_str().unwrap()).unwrap_err();
1729 assert_no_host_path(err.message(), &[outside.path(), &s.ws, &link]);
1730
1731 swap_dir(&s.ws.join("d"), &s.other);
1732 let err = read_text(s.ws.join("d/f").to_str().unwrap()).unwrap_err();
1733 assert_no_host_path(err.message(), &[&s.ws, &s.other, &s.ws.join("d/f")]);
1734
1735 let err = read_text("/etc/passwd").unwrap_err();
1736 assert_no_host_path(
1737 err.message(),
1738 &[Path::new("/etc/passwd"), Path::new("/etc")],
1739 );
1740 }
1741
1742 #[test]
1743 fn directory_symlink_does_not_read_the_other_file() {
1744 let s = scratch();
1745 let target = s.ws.join("d/f");
1746 swap_dir(&s.ws.join("d"), &s.other);
1747 let err = read_text(target.to_str().unwrap()).unwrap_err();
1748 assert!(
1749 matches!(err, BindError::Denied(_)),
1750 "a directory symlink must not open the other file, got {err:?}"
1751 );
1752 assert!(!err.message().contains(OTHER));
1753 assert_eq!(std::fs::read_to_string(s.other.join("f")).unwrap(), OTHER);
1754 assert_eq!(
1755 std::fs::read_to_string(s.ws.join("d.held/f")).unwrap(),
1756 INSIDE
1757 );
1758 }
1759
1760 #[test]
1761 fn allowlist_would_permit_the_other_file_but_a_swap_before_open_does_not_read_it() {
1762 let _clear = ClearHooks;
1763 let s = scratch();
1764 let target = s.ws.join("d/f");
1765 let other_file = s.other.join("f");
1766 // Both paths sit under /tmp, so a pathname allow-list admits either.
1767 assert!(validate_workspace_path(&target, &permitted_workspaces()).is_ok());
1768 assert!(validate_workspace_path(&other_file, &permitted_workspaces()).is_ok());
1769 let other = s.other.clone();
1770 let dir = s.ws.join("d");
1771 test_hooks::set_before_open(move || swap_dir(&dir, &other));
1772 let err = read_text(target.to_str().unwrap()).unwrap_err();
1773 assert!(matches!(err, BindError::Denied(_)), "{err:?}");
1774 assert!(!err.message().contains(OTHER));
1775 assert_eq!(std::fs::read_to_string(&other_file).unwrap(), OTHER);
1776 assert_eq!(
1777 std::fs::read_to_string(s.ws.join("d.held/f")).unwrap(),
1778 INSIDE
1779 );
1780 }
1781
1782 #[test]
1783 fn held_descriptor_ignores_a_parent_swap() {
1784 let _clear = ClearHooks;
1785 let s = scratch();
1786 let target = s.ws.join("d/f");
1787 let other = s.other.clone();
1788 let dir = s.ws.join("d");
1789 test_hooks::set_after_open(move || swap_dir(&dir, &other));
1790 let (_, text) = read_text(target.to_str().unwrap()).unwrap();
1791 assert_eq!(text, INSIDE);
1792 // By path the name now resolves at the other file.
1793 assert_eq!(std::fs::read_to_string(&target).unwrap(), OTHER);
1794 assert_eq!(
1795 std::fs::read_to_string(s.ws.join("d.held/f")).unwrap(),
1796 INSIDE
1797 );
1798 }
1799
1800 #[test]
1801 fn swap_before_open_does_not_write_the_other_file() {
1802 let _clear = ClearHooks;
1803 let s = scratch();
1804 let target = s.ws.join("d/f");
1805 let other_file = s.other.join("f");
1806 let other = s.other.clone();
1807 let dir = s.ws.join("d");
1808 test_hooks::set_before_open(move || swap_dir(&dir, &other));
1809 let err = hold_for_write(target.to_str().unwrap()).unwrap_err();
1810 assert!(matches!(err, BindError::Denied(_)), "{err:?}");
1811 assert_eq!(std::fs::read_to_string(&other_file).unwrap(), OTHER);
1812 assert_eq!(
1813 std::fs::read_to_string(s.ws.join("d.held/f")).unwrap(),
1814 INSIDE
1815 );
1816 }
1817
1818 #[test]
1819 fn held_descriptor_write_stays_on_the_authorized_inode() {
1820 let _clear = ClearHooks;
1821 let s = scratch();
1822 let target = s.ws.join("d/f");
1823 let other = s.other.clone();
1824 let dir = s.ws.join("d");
1825 test_hooks::set_after_open(move || swap_dir(&dir, &other));
1826 let held = hold_for_write(target.to_str().unwrap()).unwrap();
1827 held.write_bytes(b"UPDATED", true).unwrap();
1828 assert_eq!(std::fs::read_to_string(s.other.join("f")).unwrap(), OTHER);
1829 assert_eq!(
1830 std::fs::read_to_string(s.ws.join("d.held/f")).unwrap(),
1831 "UPDATED"
1832 );
1833 assert_eq!(held.read_checkpoint().unwrap().unwrap(), b"UPDATED");
1834 }
1835
1836 #[test]
1837 fn create_does_not_land_in_a_swapped_parent() {
1838 let _clear = ClearHooks;
1839 let s = scratch();
1840 let target = s.ws.join("d/newfile");
1841 let other = s.other.clone();
1842 let dir = s.ws.join("d");
1843 test_hooks::set_after_open(move || swap_dir(&dir, &other));
1844 let held = hold_for_write(target.to_str().unwrap()).unwrap();
1845 let err = held.write_bytes(b"nope", true).unwrap_err();
1846 assert!(matches!(err, BindError::Denied(_)), "{err:?}");
1847 assert!(!s.other.join("newfile").exists());
1848 assert!(!s.ws.join("d.held/newfile").exists());
1849 }
1850
1851 #[test]
1852 fn make_dir_refuses_a_swapped_parent() {
1853 let _clear = ClearHooks;
1854 let s = scratch();
1855 let target = s.ws.join("d/created");
1856 let other = s.other.clone();
1857 let dir = s.ws.join("d");
1858 test_hooks::set_before_open(move || swap_dir(&dir, &other));
1859 let err = make_dir(target.to_str().unwrap()).unwrap_err();
1860 assert!(matches!(err, BindError::Denied(_)), "{err:?}");
1861 assert!(!s.other.join("created").exists());
1862 }
1863
1864 #[test]
1865 fn search_does_not_descend_a_symlink() {
1866 let s = scratch();
1867 let outside = outside_scratch();
1868 std::fs::write(s.ws.join("d/hit.txt"), "HIT_MARKER").unwrap();
1869 symlink(outside.path(), s.ws.join("d/leak")).unwrap();
1870 let hits = grep_search(s.ws.join("d").to_str().unwrap(), OUTSIDE, 50).unwrap();
1871 assert!(hits.is_empty(), "{hits:?}");
1872 let found = find_names(s.ws.join("d").to_str().unwrap(), "secret", 50).unwrap();
1873 assert!(found.is_empty(), "{found:?}");
1874 let leak = find_names(s.ws.join("d").to_str().unwrap(), "leak", 50).unwrap();
1875 assert_eq!(leak.len(), 1);
1876 assert!(leak[0].ends_with("/leak"));
1877 }
1878
1879 #[test]
1880 fn search_keeps_the_opened_directory_after_a_swap() {
1881 let _clear = ClearHooks;
1882 let s = scratch();
1883 std::fs::write(s.ws.join("d/hit.txt"), "HIT_MARKER").unwrap();
1884 std::fs::write(s.other.join("secret"), OUTSIDE).unwrap();
1885 let other = s.other.clone();
1886 let dir = s.ws.join("d");
1887 let search = dir.clone();
1888 test_hooks::set_after_open(move || swap_dir(&dir, &other));
1889 let hits = grep_search(search.to_str().unwrap(), "HIT_MARKER", 50).unwrap();
1890 assert!(hits.iter().any(|h| h.contains("HIT_MARKER")), "{hits:?}");
1891 assert!(hits.iter().all(|h| !h.contains(OUTSIDE)));
1892 }
1893
1894 #[test]
1895 fn concurrent_swap_keeps_a_pinned_file_and_refuses_an_unpermitted_target() {
1896 let s = scratch();
1897 let outside = outside_scratch();
1898 std::fs::write(outside.path().join("f"), OUTSIDE).unwrap();
1899 let target = s.ws.join("d/f");
1900 let held = hold_for_write(target.to_str().unwrap()).unwrap();
1901 let dir = s.ws.join("d");
1902 let other = s.other.clone();
1903 let outside_dir = outside.path().to_path_buf();
1904 let stop = std::sync::Arc::new(AtomicBool::new(false));
1905 let swapper = {
1906 let (stop, dir, other, outside_dir) = (
1907 std::sync::Arc::clone(&stop),
1908 dir.clone(),
1909 other.clone(),
1910 outside_dir.clone(),
1911 );
1912 std::thread::spawn(move || {
1913 let parked = dir.with_file_name("d.held");
1914 let mut flip = false;
1915 while !stop.load(Ordering::Relaxed) {
1916 let dest = if flip { &other } else { &outside_dir };
1917 flip = !flip;
1918 if dir
1919 .symlink_metadata()
1920 .map(|m| m.file_type().is_symlink())
1921 .unwrap_or(false)
1922 {
1923 let _ = std::fs::remove_file(&dir);
1924 let _ = std::fs::rename(&parked, &dir);
1925 } else {
1926 let _ = std::fs::rename(&dir, &parked);
1927 let _ = symlink(dest, &dir);
1928 }
1929 }
1930 if dir
1931 .symlink_metadata()
1932 .map(|m| m.file_type().is_symlink())
1933 .unwrap_or(false)
1934 {
1935 let _ = std::fs::remove_file(&dir);
1936 let _ = std::fs::rename(&parked, &dir);
1937 }
1938 })
1939 };
1940 let end = Instant::now() + Duration::from_millis(400);
1941 let mut reads = 0u32;
1942 while Instant::now() < end {
1943 let pinned = held
1944 .read_checkpoint()
1945 .unwrap()
1946 .expect("pinned file missing");
1947 assert_eq!(pinned, INSIDE.as_bytes());
1948 match read_text(target.to_str().unwrap()) {
1949 Ok((_, text)) => {
1950 assert!(
1951 fresh_swap_read_is_inside(&text),
1952 "fresh open followed a swapped directory: {text}"
1953 );
1954 }
1955 Err(BindError::Denied(_)) | Err(BindError::NotFound(_)) => {}
1956 Err(BindError::Failed(msg))
1957 if msg.contains("No such file") || msg.contains("Not a directory") => {}
1958 Err(e) => panic!("unexpected bind failure: {e:?}"),
1959 }
1960 reads += 1;
1961 }
1962 stop.store(true, Ordering::Relaxed);
1963 swapper.join().unwrap();
1964 assert!(reads > 0);
1965 assert_eq!(
1966 std::fs::read_to_string(outside.path().join("f")).unwrap(),
1967 OUTSIDE
1968 );
1969 let (_, text) = read_text(target.to_str().unwrap()).unwrap();
1970 assert_eq!(text, INSIDE);
1971 }
1972
1973 fn openat2_errno_is_denied(code: i32) {
1974 let _clear = ClearHooks;
1975 let root = tempfile::tempdir_in("/tmp").unwrap();
1976 let file = root.path().join("f");
1977 std::fs::write(&file, b"kept").unwrap();
1978 test_hooks::set_openat2_error(code);
1979 let err = read_text(file.to_str().unwrap()).unwrap_err();
1980 assert!(
1981 matches!(err, BindError::Denied(_)),
1982 "errno {code} must be a confinement denial, got {err:?}"
1983 );
1984 assert_eq!(std::fs::read(&file).unwrap(), b"kept");
1985 }
1986
1987 #[test]
1988 fn wide_tree_walk_holds_one_fd_per_depth_not_per_sibling() {
1989 let root = tempfile::tempdir_in("/tmp").unwrap();
1990 let root = root.path().canonicalize().unwrap();
1991 let n = 80;
1992 for i in 0..n {
1993 let dir = root.join(format!("dir{i:03}"));
1994 std::fs::create_dir(&dir).unwrap();
1995 std::fs::write(dir.join("f.txt"), b"x").unwrap();
1996 }
1997 let _ = take_walk_fd_max();
1998 let found = find_names(root.to_str().unwrap(), "f.txt", 200).unwrap();
1999 assert_eq!(found.len(), n);
2000 let max_fds = take_walk_fd_max();
2001 assert!(
2002 max_fds <= 3,
2003 "wide tree held {max_fds} directory fds; one per sibling would be about {n}"
2004 );
2005 }
2006
2007 #[test]
2008 fn openat2_enosys_fails_closed() {
2009 openat2_errno_is_denied(libc::ENOSYS);
2010 }
2011
2012 #[test]
2013 fn openat2_eperm_is_denied() {
2014 openat2_errno_is_denied(libc::EPERM);
2015 }
2016
2017 #[test]
2018 fn openat2_einval_is_denied() {
2019 openat2_errno_is_denied(libc::EINVAL);
2020 }
2021
2022 #[test]
2023 fn grep_bytes_makes_progress_on_large_input_and_output() {
2024 let line = "match-token\n";
2025 let copies = (1024 * 1024) / line.len();
2026 let bytes = line.repeat(copies).into_bytes();
2027 let (tx, rx) = std::sync::mpsc::channel();
2028 std::thread::spawn(move || {
2029 let _ = tx.send(grep_bytes("match-token", &bytes));
2030 });
2031 let result = match rx.recv_timeout(Duration::from_secs(8)) {
2032 Ok(result) => result,
2033 Err(_) => {
2034 let _ = Command::new("pkill")
2035 .args(["-P", &std::process::id().to_string(), "grep"])
2036 .status();
2037 panic!("grep_bytes stalled; stdout was not read while stdin was written");
2038 }
2039 };
2040 let lines = result.expect("grep");
2041 assert!(
2042 lines.len() > 1000,
2043 "expected a large match set, got {}",
2044 lines.len()
2045 );
2046 }
2047}