返回 CodeWhale
private_directory.rs
根目录 / crates / config / src / private_directory.rs
1 //! Private directory/file mechanism extracted from xai_credentials.
2 //! Retained handles, no-follow component traversal, owner/type/link checks,
3 //! atomic publication and Windows owner-only security preserve existing policy.
4
5 #[cfg(windows)]
6 use crate::windows_identity::{CurrentWindowsUser, WindowsLocalAllocation};
7 use anyhow::{Context, Result, bail};
8 #[cfg(unix)]
9 use codewhale_paths::resolve_root_owned_ancestors as resolve_ancestors;
10 #[cfg(unix)]
11 use std::ffi::CString;
12 use std::fs::{self, File};
13 use std::io::Write as _;
14 use std::path::{Component, Path, PathBuf};
15 #[cfg(all(windows, test))]
16 use std::sync::Mutex;
17 #[cfg(not(windows))]
18 use std::time::{SystemTime, UNIX_EPOCH};
19
20 pub fn error_is_filesystem_loop(error: &std::io::Error) -> bool {
21 #[cfg(unix)]
22 {
23 error.raw_os_error() == Some(libc::ELOOP)
24 }
25 #[cfg(windows)]
26 {
27 error.raw_os_error() == Some(1921)
28 }
29 #[cfg(not(any(unix, windows)))]
30 {
31 let _ = error;
32 false
33 }
34 }
35
36 /// Anchored current-user-owned directory and file mechanism. Credential and
37 /// Runtime policies remain with their callers; this type owns no authority.
38 #[derive(Debug)]
39 pub struct PrivateDirectory {
40 pub(crate) directory: PathBuf,
41 #[cfg(unix)]
42 pub(crate) directory_handle: File,
43 /// Whether ownership and mode were actually verifiable on this mount.
44 #[cfg(unix)]
45 pub(crate) guard: PrivateGuard,
46 #[cfg(windows)]
47 pub(crate) _component_handles: Vec<File>,
48 }
49
50 /// A retained file was retired before it could be validated. This is still a
51 /// refusal; an owner observer may re-observe, but must never accept this file.
52 #[cfg(unix)]
53 #[derive(Debug)]
54 pub struct UnlinkedPrivateFile;
55
56 #[cfg(unix)]
57 impl std::fmt::Display for UnlinkedPrivateFile {
58 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
59 formatter.write_str("private file was unlinked before validation")
60 }
61 }
62
63 #[cfg(unix)]
64 impl std::error::Error for UnlinkedPrivateFile {}
65
66 impl PrivateDirectory {
67 pub fn open(directory: &Path) -> Result<Self> {
68 open_owned_directory(directory, true, true, PrivateGuard::Required)
69 }
70 /// Read-only admission of an existing private directory, without repair.
71 pub fn inspect(directory: &Path) -> Result<Self> {
72 open_owned_directory(directory, false, false, PrivateGuard::Required)
73 }
74
75 /// Create missing owned directories; refuse existing non-private permissions.
76 pub fn admit(directory: &Path) -> Result<Self> {
77 open_owned_directory(directory, false, true, PrivateGuard::Required)
78 }
79
80 /// Create and admit, accepting a mount that cannot express ownership.
81 ///
82 /// On a filesystem that stores ownership and mode this is exactly
83 /// [`Self::open`]. On one that synthesises them — HarmonyOS hmdfs reports
84 /// the logged-in user's uid and a group-writable mode for every object an
85 /// app creates and reports that user as the owner of every object, so a
86 /// process is never the owner of what it creates and `chmod` answers
87 /// `EPERM` — the strict proof can never hold, so
88 /// refusing here would make the feature unusable on that platform for
89 /// everyone. The object is admitted with [`PrivateGuard::Unverifiable`],
90 /// which relaxes *only* the ownership proof; the no-follow walk, the
91 /// single-link check and atomic publication still apply, and a warning
92 /// names the values the mount reported.
93 ///
94 /// A directory this process may not enter is still an error: the probe must
95 /// be able to create an object of its own before a mount is blamed.
96 #[cfg(unix)]
97 pub fn open_trusting_mount(directory: &Path) -> Result<Self> {
98 Self::with_mount_tolerance(directory, true, true)
99 }
100
101 /// [`Self::admit`], accepting a mount that cannot express ownership.
102 #[cfg(unix)]
103 pub fn admit_trusting_mount(directory: &Path) -> Result<Self> {
104 Self::with_mount_tolerance(directory, false, true)
105 }
106
107 /// [`Self::inspect`], accepting a mount that cannot express ownership.
108 #[cfg(unix)]
109 pub fn inspect_trusting_mount(directory: &Path) -> Result<Self> {
110 Self::with_mount_tolerance(directory, false, false)
111 }
112
113 /// Not applicable outside Unix: the ownership guard is the Windows security
114 /// descriptor, which every local filesystem stores.
115 #[cfg(not(unix))]
116 pub fn open_trusting_mount(directory: &Path) -> Result<Self> {
117 Self::open(directory)
118 }
119
120 #[cfg(not(unix))]
121 pub fn admit_trusting_mount(directory: &Path) -> Result<Self> {
122 Self::admit(directory)
123 }
124
125 #[cfg(not(unix))]
126 pub fn inspect_trusting_mount(directory: &Path) -> Result<Self> {
127 Self::inspect(directory)
128 }
129
130 #[cfg(unix)]
131 fn with_mount_tolerance(directory: &Path, protect: bool, create: bool) -> Result<Self> {
132 match open_owned_directory(directory, protect, create, PrivateGuard::Required) {
133 Ok(private) => Ok(private),
134 Err(strict_error) => {
135 // `mount_footing` answers once per directory and reports the
136 // values it saw; a probe that could not run answers `Native`,
137 // which keeps the strict error below.
138 let PrivateFooting::Synthesised {
139 observed_uid,
140 observed_mode,
141 } = mount_footing(directory)
142 else {
143 return Err(strict_error);
144 };
145 let private = open_owned_directory(
146 directory,
147 protect,
148 create,
149 PrivateGuard::Unverifiable {
150 observed_uid,
151 observed_mode,
152 },
153 )?;
154 tracing::warn!(
155 directory = %private.directory.display(),
156 "{} reports uid {observed_uid} and mode {observed_mode:o} for objects created on \
157 it, so the ownership guard cannot be verified; relying on the mount's own \
158 access control for this private directory",
159 private.directory.display()
160 );
161 Ok(private)
162 }
163 }
164 }
165
166 /// Check the retained directory against the lexical selection without
167 /// following links, creating directories, or changing permissions.
168 #[cfg(unix)]
169 pub fn is_at_selected_path(&self) -> Result<bool> {
170 use std::os::unix::fs::MetadataExt as _;
171 // What this compares is identity — device and inode of the retained
172 // handle against the freshly opened one — so repeating the ownership
173 // proof adds nothing here, and a directory admitted as `Unverifiable`
174 // would fail that proof on exactly the mount that made it necessary.
175 let current = match self.guard {
176 PrivateGuard::Required => Self::inspect(&self.directory)?,
177 PrivateGuard::Unverifiable { .. } => Self::inspect_trusting_mount(&self.directory)?,
178 };
179 let held = self.directory_handle.metadata()?;
180 let now = current.directory_handle.metadata()?;
181 Ok(held.dev() == now.dev() && held.ino() == now.ino())
182 }
183
184 /// The guard this directory was admitted with, for validating files under
185 /// it. A file on a mount that cannot express ownership is exactly as
186 /// unverifiable as its directory.
187 #[cfg(unix)]
188 pub fn guard(&self) -> PrivateGuard {
189 self.guard
190 }
191
192 #[cfg(not(unix))]
193 pub fn guard(&self) -> PrivateGuard {
194 PrivateGuard::Required
195 }
196
197 #[cfg(unix)]
198 pub fn current_user_id() -> u32 {
199 // SAFETY: geteuid has no pointer arguments.
200 unsafe { libc::geteuid() }
201 }
202 }
203
204 /// Narrow `path` to `mode`, tolerating a filesystem that cannot store modes.
205 ///
206 /// Every ownership story in this crate ends in a `chmod`: a lock file is
207 /// narrowed to `0600`, a session directory to `0700`. On HarmonyOS hmdfs the
208 /// call fails with `EPERM` for every object, including objects the caller just
209 /// created, because the mount assigns the mode itself. Treating that as fatal
210 /// turns an ordinary write into "permission denied" on a platform where the
211 /// write itself succeeded — and the mode the caller asked for was never going
212 /// to be applied.
213 ///
214 /// This narrows when the mount stores modes and, only where a probe proves the
215 /// mount synthesises them, continues. A mount that stores modes keeps the
216 /// error, so a real permission problem is still reported; the probe's own
217 /// warning names the values the mount reported, once per directory.
218 #[cfg(unix)]
219 pub fn tighten_mode(path: &Path, mode: u32) -> Result<()> {
220 use std::os::unix::fs::PermissionsExt as _;
221
222 match fs::set_permissions(path, fs::Permissions::from_mode(mode)) {
223 Ok(()) => Ok(()),
224 Err(error) => {
225 // A mount that assigns modes itself refuses this for every object
226 // it holds, including one it has just accepted a write to. Only
227 // that mount is excused, and `mount_footing` answers once per
228 // directory, so a write path does not pay for a probe each time.
229 let parent = path.parent().filter(|p| !p.as_os_str().is_empty());
230 if parent.is_some_and(|parent| {
231 matches!(mount_footing(parent), PrivateFooting::Synthesised { .. })
232 }) {
233 return Ok(());
234 }
235 Err(error)
236 .with_context(|| format!("narrowing {} to {mode:o}", crate::quote_os_path(path)))
237 }
238 }
239 }
240
241 /// [`tighten_mode`] for an object this process already holds open.
242 ///
243 /// Preferred wherever a handle exists: the mode is applied to the object the
244 /// caller validated, so narrowing cannot be redirected to a substituted path.
245 /// Only the *question* about the filesystem is answered by path, and only after
246 /// the call has already failed.
247 #[cfg(unix)]
248 pub fn tighten_mode_of(file: &File, path: &Path, mode: u32) -> Result<()> {
249 use std::os::unix::fs::PermissionsExt as _;
250
251 let error = match file.set_permissions(fs::Permissions::from_mode(mode)) {
252 Ok(()) => return Ok(()),
253 Err(error) => error,
254 };
255 let parent = path.parent().filter(|p| !p.as_os_str().is_empty());
256 if parent
257 .is_some_and(|parent| matches!(mount_footing(parent), PrivateFooting::Synthesised { .. }))
258 {
259 return Ok(());
260 }
261 Err(error).with_context(|| format!("narrowing {} to {mode:o}", crate::quote_os_path(path)))
262 }
263
264 #[cfg(not(unix))]
265 pub fn tighten_mode_of(_file: &File, _path: &Path, _mode: u32) -> Result<()> {
266 Ok(())
267 }
268
269 #[cfg(not(unix))]
270 pub fn tighten_mode(_path: &Path, _mode: u32) -> Result<()> {
271 Ok(())
272 }
273
274 /// How much of the private-directory guard this object could establish.
275 ///
276 /// Everything that makes an object unreachable by another local user — the
277 /// no-follow component walk, the single-link check, atomic publication, the
278 /// retained handle — holds in both cases. Only the proof of *ownership* is what
279 /// a mount can fail to express, and that is what [`Self::Unverifiable`] records.
280 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
281 pub enum PrivateGuard {
282 /// Ownership and mode prove the directory is current-user-only.
283 Required,
284 /// The mount reports ownership and mode of its own, so they prove nothing.
285 /// The caller asked for this explicitly and has said so to the user; the
286 /// mount's own access control is what governs the object.
287 Unverifiable {
288 observed_uid: u32,
289 observed_mode: u32,
290 },
291 }
292
293 /// What a filesystem does with the owner and mode of a directory created on it.
294 ///
295 /// A private directory is admitted by proving it is current-user-owned and
296 /// inaccessible to group or other. Some mounts synthesise those attributes
297 /// instead of storing them, so no object there can ever satisfy that proof —
298 /// and refusing the feature outright turns a filesystem limitation into a
299 /// failed startup. Callers use this to tell "you are not allowed" (fatal) from
300 /// "this mount cannot express the guard" (a capability the caller must
301 /// degrade around, loudly).
302 #[cfg(unix)]
303 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
304 pub enum PrivateFooting {
305 /// The mount stored the owner and mode the probe directory was created with.
306 Native,
307 /// The mount reported values of its own for the probe directory, with the
308 /// observed values, so a refusal can name what it saw.
309 Synthesised {
310 observed_uid: u32,
311 observed_mode: u32,
312 },
313 }
314
315 /// Probe the filesystem that would hold `directory`.
316 ///
317 /// Creates one directory at `0o700` under the deepest existing ancestor of
318 /// `directory`, reads back what the mount made of it, and removes it. A mount
319 /// that keeps the owner and mode it was given answers
320 /// [`PrivateFooting::Native`]; a mount that invents them (HarmonyOS hmdfs
321 /// reports the logged-in user's uid and a group-writable mode for every object,
322 /// and reports another owner, so `chmod` answers `EPERM`) answers
323 /// [`PrivateFooting::Synthesised`].
324 ///
325 /// An unexpected mode alone is *not* enough to blame the mount: a default ACL
326 /// or a setgid parent can widen a new directory on a filesystem that stores
327 /// modes perfectly well. The probe therefore asks the mount to apply `0o700`
328 /// and looks again, and only a mount that will not honour that is called
329 /// synthesising. Reclassifying a mount that does store modes would relax a real
330 /// ownership guard, so the question is asked in the direction that keeps it.
331 ///
332 /// Any failure to run the probe is an error rather than an answer, so a
333 /// directory this process cannot write to keeps the strict refusal instead of
334 /// being reclassified as a mount limitation.
335 #[cfg(unix)]
336 pub fn private_footing(directory: &Path) -> Result<PrivateFooting> {
337 anyhow::ensure!(
338 directory.is_absolute(),
339 "private footing probe needs an absolute path"
340 );
341 let Some(parent) = deepest_existing_ancestor(directory) else {
342 // Nothing exists to create in; the real admission reports the cause.
343 return Ok(PrivateFooting::Native);
344 };
345 let handle = File::open(parent).with_context(|| {
346 format!(
347 "opening {} to probe its filesystem",
348 crate::quote_os_path(parent)
349 )
350 })?;
351 probe_footing_in(&handle).with_context(|| {
352 format!(
353 "probing private-directory footing under {}",
354 crate::quote_os_path(parent)
355 )
356 })
357 }
358
359 /// The footing of the filesystem behind an already-open directory.
360 ///
361 /// The probe runs inside `directory` through its descriptor, so no path is
362 /// involved and nothing outside it can be reached. Used both by
363 /// [`private_footing`] and by callers that already hold the directory — a
364 /// delivery writer, an anchored report directory — and want the answer for the
365 /// object they are actually writing into.
366 #[cfg(unix)]
367 fn probe_footing_in(directory: &File) -> Result<PrivateFooting> {
368 use std::os::fd::AsRawFd as _;
369
370 static PROBE_COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
371 let directory_fd = directory.as_raw_fd();
372 let nanos = SystemTime::now()
373 .duration_since(UNIX_EPOCH)
374 .map_or(0, |elapsed| elapsed.as_nanos());
375 let mut reserved = None;
376 for _ in 0..8 {
377 let name = CString::new(format!(
378 ".codewhale-owner-probe-{}-{nanos}-{}",
379 std::process::id(),
380 PROBE_COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
381 ))?;
382 // SAFETY: a retained directory descriptor and a single component that
383 // contains no path separator and no interior NUL.
384 if unsafe { libc::mkdirat(directory_fd, name.as_ptr(), 0o700) } == 0 {
385 reserved = Some(name);
386 break;
387 }
388 let error = std::io::Error::last_os_error();
389 if error.kind() == std::io::ErrorKind::AlreadyExists {
390 continue;
391 }
392 return Err(error).context("creating private footing probe");
393 }
394 let name = reserved.context("private footing probe could not reserve a name")?;
395 let observed = (|| {
396 let first = probe_stat(directory_fd, &name)?;
397 if matches!(
398 classify_probe_footing(first.0, first.1, PrivateDirectory::current_user_id()),
399 PrivateFooting::Native
400 ) {
401 return Ok(PrivateFooting::Native);
402 }
403 // Ask the mount for the mode the probe actually wants, and look again.
404 // SAFETY: the same retained descriptor and the same single component.
405 let narrowed = (unsafe { libc::fchmodat(directory_fd, name.as_ptr(), 0o700, 0) } == 0)
406 .then(|| probe_stat(directory_fd, &name))
407 .transpose()?;
408 Ok(footing_from_observations(
409 first,
410 narrowed,
411 PrivateDirectory::current_user_id(),
412 ))
413 })();
414 // Best effort: a probe that cannot be removed must not change the answer.
415 // SAFETY: the same retained descriptor and the same single component.
416 unsafe { libc::unlinkat(directory_fd, name.as_ptr(), libc::AT_REMOVEDIR) };
417 observed
418 }
419
420 #[cfg(unix)]
421 fn probe_stat(directory_fd: libc::c_int, name: &CString) -> Result<(u32, u32)> {
422 let mut metadata = std::mem::MaybeUninit::<libc::stat>::uninit();
423 // SAFETY: one component below a retained descriptor, no follow, writable
424 // output.
425 if unsafe {
426 libc::fstatat(
427 directory_fd,
428 name.as_ptr(),
429 metadata.as_mut_ptr(),
430 libc::AT_SYMLINK_NOFOLLOW,
431 )
432 } != 0
433 {
434 return Err(std::io::Error::last_os_error()).context("inspecting private footing probe");
435 }
436 // SAFETY: a successful `fstatat` initialized the whole object.
437 let metadata = unsafe { metadata.assume_init() };
438 // The field types differ per platform (Darwin's `mode_t` is narrower than
439 // Linux's), so both are read through one pair of accessors.
440 let mode = libc_mode(&metadata);
441 Ok((libc_uid(&metadata), mode & 0o777))
442 }
443
444 /// The rule [`private_footing`] applies, separated so every branch is testable
445 /// on a filesystem that only ever produces the native one.
446 #[cfg(unix)]
447 fn classify_probe_footing(
448 observed_uid: u32,
449 observed_mode: u32,
450 current_uid: u32,
451 ) -> PrivateFooting {
452 if observed_uid == current_uid && observed_mode & 0o077 == 0 {
453 PrivateFooting::Native
454 } else {
455 PrivateFooting::Synthesised {
456 observed_uid,
457 observed_mode,
458 }
459 }
460 }
461
462 /// The whole rule: the first observation, and what the mount did when it was
463 /// asked to apply `0o700` (`None` when it refused the request).
464 ///
465 /// A second observation that finally shows the private values means the mount
466 /// stores modes and simply applied something of its own at creation — a default
467 /// ACL, a setgid parent. Such a filesystem can hold the guard (the strict
468 /// admission narrows it), so calling it synthesising would relax a real check.
469 /// Only a mount that refuses, or that reports values of its own after being
470 /// asked, is synthesising.
471 #[cfg(unix)]
472 fn footing_from_observations(
473 first: (u32, u32),
474 narrowed: Option<(u32, u32)>,
475 current_uid: u32,
476 ) -> PrivateFooting {
477 match narrowed {
478 Some((uid, mode)) => classify_probe_footing(uid, mode, current_uid),
479 None => classify_probe_footing(first.0, first.1, current_uid),
480 }
481 }
482
483 #[cfg(unix)]
484 fn libc_uid(metadata: &libc::stat) -> u32 {
485 metadata.st_uid
486 }
487
488 #[cfg(unix)]
489 fn libc_mode(metadata: &libc::stat) -> u32 {
490 #[allow(clippy::unnecessary_cast)]
491 // `mode_t` is `u16` on Apple and `u32` on Linux; no single conversion is
492 // lint-clean on both, and this is the widening that keeps the value exact.
493 let mode = metadata.st_mode as u32;
494 mode
495 }
496
497 /// Answers already obtained from a filesystem, keyed by the identity of the
498 /// directory that was probed.
499 ///
500 /// A probe is a create, a stat, a `chmod` and an unlink, and the sites that ask
501 /// sit under ordinary file writes. The answer is a property of the mount and
502 /// cannot change for one directory, so each directory is asked once per process
503 /// and the one warning is emitted with that first answer. A probe that could
504 /// not run is not an answer and is never cached.
505 #[cfg(unix)]
506 fn footing_answers()
507 -> &'static std::sync::Mutex<std::collections::HashMap<(u64, u64), PrivateFooting>> {
508 static ANSWERS: std::sync::OnceLock<
509 std::sync::Mutex<std::collections::HashMap<(u64, u64), PrivateFooting>>,
510 > = std::sync::OnceLock::new();
511 ANSWERS.get_or_init(std::sync::Mutex::default)
512 }
513
514 /// [`private_footing`] for a directory handle, answered at most once.
515 #[cfg(unix)]
516 pub fn mount_footing_of(directory: &File) -> PrivateFooting {
517 use std::os::unix::fs::MetadataExt as _;
518
519 let key = directory
520 .metadata()
521 .ok()
522 .map(|metadata| (metadata.dev(), metadata.ino()));
523 if let Some(key) = key
524 && let Some(answer) = footing_answers()
525 .lock()
526 .unwrap_or_else(|poisoned| poisoned.into_inner())
527 .get(&key)
528 .copied()
529 {
530 return answer;
531 }
532 let Ok(answer) = probe_footing_in(directory) else {
533 // The probe could not run: that is a problem to report, not a mount
534 // limitation, so the caller keeps its strict check.
535 return PrivateFooting::Native;
536 };
537 if let PrivateFooting::Synthesised {
538 observed_uid,
539 observed_mode,
540 } = answer
541 {
542 tracing::warn!(
543 "a directory on this filesystem was created at 0o700 and reports uid \
544 {observed_uid} and mode {observed_mode:o}, and the mount will not narrow it; \
545 ownership cannot be verified for private files here, so relying on the mount's \
546 own access control"
547 );
548 }
549 if let Some(key) = key {
550 footing_answers()
551 .lock()
552 .unwrap_or_else(|poisoned| poisoned.into_inner())
553 .insert(key, answer);
554 }
555 answer
556 }
557
558 /// [`private_footing`] for a path, answered at most once per directory.
559 #[cfg(unix)]
560 pub fn mount_footing(directory: &Path) -> PrivateFooting {
561 let Some(existing) = deepest_existing_ancestor(directory) else {
562 return PrivateFooting::Native;
563 };
564 let Ok(handle) = File::open(existing) else {
565 return PrivateFooting::Native;
566 };
567 mount_footing_of(&handle)
568 }
569
570 #[cfg(unix)]
571 fn deepest_existing_ancestor(directory: &Path) -> Option<&Path> {
572 let mut candidate = Some(directory);
573 while let Some(path) = candidate {
574 if fs::symlink_metadata(path).is_ok() {
575 return Some(path);
576 }
577 candidate = path.parent();
578 }
579 None
580 }
581
582 fn validate_private_basename(name: &str) -> Result<()> {
583 let path = Path::new(name);
584 anyhow::ensure!(
585 path.components().count() == 1
586 && matches!(path.components().next(), Some(Component::Normal(_)))
587 && path.file_name().and_then(|value| value.to_str()) == Some(name),
588 "xAI OAuth private basename must be one UTF-8 path component"
589 );
590 Ok(())
591 }
592
593 #[cfg(unix)]
594 fn open_owned_directory(
595 directory: &Path,
596 protect: bool,
597 create: bool,
598 guard: PrivateGuard,
599 ) -> Result<PrivateDirectory> {
600 use std::os::fd::FromRawFd as _;
601 use std::os::unix::fs::{MetadataExt as _, PermissionsExt as _};
602
603 anyhow::ensure!(
604 directory.is_absolute(),
605 "xAI OAuth credentials directory must be absolute"
606 );
607 let resolved = resolve_ancestors(directory);
608 let directory = resolved.as_path();
609 let directory_flags = libc::O_DIRECTORY | libc::O_CLOEXEC | libc::O_NOFOLLOW;
610 #[cfg(target_os = "linux")]
611 let ancestor_flags = directory_flags | libc::O_PATH;
612 #[cfg(not(target_os = "linux"))]
613 let ancestor_flags = directory_flags | libc::O_RDONLY;
614 // SAFETY: the literal root path contains no interior NUL and the returned
615 // descriptor is immediately owned by `File`.
616 let root_fd = unsafe {
617 libc::open(
618 c"/".as_ptr(),
619 if directory == Path::new("/") {
620 directory_flags | libc::O_RDONLY
621 } else {
622 ancestor_flags
623 },
624 )
625 };
626 if root_fd < 0 {
627 let error = std::io::Error::last_os_error();
628 let context = format!("opening filesystem root: {error}");
629 return Err(error).context(context);
630 }
631 // SAFETY: `root_fd` is a newly owned descriptor on the success path above.
632 let mut current = unsafe { File::from_raw_fd(root_fd) };
633 let mut components = directory.components().peekable();
634 while let Some(component) = components.next() {
635 let Component::Normal(name) = component else {
636 if matches!(component, Component::RootDir) {
637 continue;
638 }
639 bail!(
640 "Codewhale credentials directory has an unsupported component: {}",
641 crate::quote_os_path(directory)
642 );
643 };
644 let name = cstring_from_os_str(name)?;
645 let flags = if components.peek().is_none() {
646 directory_flags | libc::O_RDONLY
647 } else {
648 ancestor_flags
649 };
650 // SAFETY: parent borrowed from live `current`; `name` outlives the call.
651 let mut fd = unsafe {
652 libc::openat(
653 std::os::fd::AsRawFd::as_raw_fd(&current),
654 name.as_ptr(),
655 flags,
656 )
657 };
658 if create
659 && fd < 0
660 && std::io::Error::last_os_error().kind() == std::io::ErrorKind::NotFound
661 {
662 // SAFETY: both the parent descriptor and component pointer remain
663 // valid for this call. `mkdirat` cannot follow the missing leaf.
664 let created = unsafe {
665 libc::mkdirat(
666 std::os::fd::AsRawFd::as_raw_fd(&current),
667 name.as_ptr(),
668 0o700,
669 )
670 };
671 if created != 0 {
672 let error = std::io::Error::last_os_error();
673 if error.kind() != std::io::ErrorKind::AlreadyExists {
674 return Err(error).with_context(|| {
675 format!(
676 "creating a component of Codewhale credentials directory {}",
677 crate::quote_os_path(directory)
678 )
679 });
680 }
681 }
682 // SAFETY: same stable parent/component arguments as above.
683 fd = unsafe {
684 libc::openat(
685 std::os::fd::AsRawFd::as_raw_fd(&current),
686 name.as_ptr(),
687 flags,
688 )
689 };
690 }
691 if fd < 0 {
692 let error = std::io::Error::last_os_error();
693 let situation = if error_is_filesystem_loop(&error) {
694 "is a symlink loop"
695 } else if error.kind() == std::io::ErrorKind::NotFound {
696 "does not exist"
697 } else {
698 "could not be opened without following links"
699 };
700 return Err(error).with_context(|| {
701 format!(
702 "Codewhale credentials directory {}: {}",
703 situation,
704 crate::quote_os_path(directory)
705 )
706 });
707 }
708 // SAFETY: `fd` is a newly owned descriptor on the success path above.
709 current = unsafe { File::from_raw_fd(fd) };
710 }
711 let metadata = current.metadata().with_context(|| {
712 format!(
713 "inspecting Codewhale credentials directory {}",
714 crate::quote_os_path(directory)
715 )
716 })?;
717 anyhow::ensure!(
718 metadata.is_dir(),
719 "Codewhale credentials path must be a directory"
720 );
721 match guard {
722 PrivateGuard::Required => {
723 // The message names the directory and both uids. It used to say
724 // only "credentials directory must be owned by the current user",
725 // which was wrong twice over: the directory is not necessarily a
726 // credential store (the workspace lease and the control socket use
727 // the same mechanism), and without the values there was no way to
728 // tell a real ownership problem from a mount that reports an owner
729 // of its own.
730 // SAFETY: geteuid(2) dereferences no pointers.
731 let current_uid = unsafe { libc::geteuid() };
732 anyhow::ensure!(
733 metadata.uid() == current_uid,
734 "private directory {} is owned by uid {} but this process runs as uid {}",
735 crate::quote_os_path(directory),
736 metadata.uid(),
737 current_uid
738 );
739 if protect {
740 current.set_permissions(fs::Permissions::from_mode(0o700))?;
741 } else {
742 anyhow::ensure!(
743 metadata.mode() & 0o077 == 0,
744 "private endpoint directory must already be current-user-only"
745 );
746 }
747 }
748 PrivateGuard::Unverifiable { .. } => {
749 // The mount owns the attributes, so neither the owner nor the mode
750 // can be made to prove anything. Narrowing is still attempted and
751 // its failure is expected rather than fatal: hmdfs answers EPERM to
752 // `chmod` for every object.
753 if protect {
754 let _ = current.set_permissions(fs::Permissions::from_mode(0o700));
755 }
756 }
757 }
758 Ok(PrivateDirectory {
759 directory: directory.to_path_buf(),
760 directory_handle: current,
761 guard,
762 })
763 }
764
765 #[cfg(unix)]
766 fn cstring_from_os_str(value: &std::ffi::OsStr) -> Result<CString> {
767 use std::os::unix::ffi::OsStrExt as _;
768 CString::new(value.as_bytes()).context("owned xAI OAuth path contains an interior NUL")
769 }
770
771 #[cfg(unix)]
772 impl PrivateDirectory {
773 fn open_at(&self, name: &str, flags: i32, mode: libc::mode_t) -> Result<Option<File>> {
774 use std::os::fd::AsRawFd as _;
775 use std::os::fd::FromRawFd as _;
776
777 validate_private_basename(name)?;
778 let name = CString::new(name).context("xAI OAuth basename contains an interior NUL")?;
779 // SAFETY: the stable directory descriptor and component pointer remain
780 // valid for the call; a successful descriptor is transferred to File.
781 let fd = unsafe {
782 libc::openat(
783 self.directory_handle.as_raw_fd(),
784 name.as_ptr(),
785 flags | libc::O_CLOEXEC | libc::O_NOFOLLOW,
786 libc::c_uint::from(mode),
787 )
788 };
789 if fd < 0 {
790 let error = std::io::Error::last_os_error();
791 if error.kind() == std::io::ErrorKind::NotFound {
792 return Ok(None);
793 }
794 return Err(error).with_context(|| {
795 format!(
796 "opening Codewhale-owned xAI OAuth path {}",
797 crate::quote_os_path(&self.directory.join(name.to_string_lossy().as_ref()))
798 )
799 });
800 }
801 // SAFETY: `fd` is newly owned on the success path above.
802 Ok(Some(unsafe { File::from_raw_fd(fd) }))
803 }
804
805 pub fn open_owned_file_for_read(&self, name: &str) -> Result<Option<File>> {
806 self.open_at(name, libc::O_RDONLY, 0)
807 }
808
809 pub fn open_internal_file(&self, name: &str) -> Result<File> {
810 use std::os::unix::fs::PermissionsExt as _;
811 let file = self
812 .open_at(name, libc::O_RDWR | libc::O_CREAT, 0o600)?
813 .context("xAI OAuth lifecycle lock disappeared while opening")?;
814 validate_owned_file_handle(&file, &self.directory.join(name), self.guard)?;
815 // Narrowing is a no-op where the mount stores the mode it was given,
816 // and is expected to fail where the mount invents one (hmdfs answers
817 // EPERM to `chmod` for every object). Refusing there would make the
818 // store unwritable on that platform for a mode it never applied anyway.
819 match self.guard {
820 PrivateGuard::Required => {
821 file.set_permissions(fs::Permissions::from_mode(0o600))?;
822 }
823 PrivateGuard::Unverifiable { .. } => {
824 let _ = file.set_permissions(fs::Permissions::from_mode(0o600));
825 }
826 }
827 Ok(file)
828 }
829
830 pub fn write_owned_file(&self, name: &str, bytes: &[u8], allow_replace: bool) -> Result<()> {
831 use std::os::fd::AsRawFd as _;
832 use std::os::unix::fs::PermissionsExt as _;
833
834 let temp_name = format!(
835 ".xai-oauth-write-{}-{}.tmp",
836 std::process::id(),
837 SystemTime::now()
838 .duration_since(UNIX_EPOCH)
839 .unwrap_or_default()
840 .as_nanos()
841 );
842 let mut temp = self
843 .open_at(
844 &temp_name,
845 libc::O_WRONLY | libc::O_CREAT | libc::O_EXCL,
846 0o600,
847 )?
848 .context("creating private xAI OAuth temporary file")?;
849 let result = (|| -> Result<()> {
850 temp.write_all(bytes)
851 .context("writing xAI OAuth temporary file")?;
852 temp.flush().context("flushing xAI OAuth temporary file")?;
853 match self.guard {
854 PrivateGuard::Required => {
855 temp.set_permissions(fs::Permissions::from_mode(0o600))?;
856 }
857 PrivateGuard::Unverifiable { .. } => {
858 let _ = temp.set_permissions(fs::Permissions::from_mode(0o600));
859 }
860 }
861 temp.sync_all()
862 .context("syncing xAI OAuth temporary file")?;
863
864 let target =
865 CString::new(name).context("xAI OAuth basename contains an interior NUL")?;
866 let temporary =
867 CString::new(temp_name.as_str()).context("temporary basename contains NUL")?;
868 if allow_replace {
869 if let Some(existing) = self.open_owned_file_for_read(name)? {
870 validate_owned_file_handle(&existing, &self.directory.join(name), self.guard)?;
871 }
872 // SAFETY: both names are relative to the same stable directory
873 // handle; rename is atomic and cannot escape that directory.
874 if unsafe {
875 libc::renameat(
876 self.directory_handle.as_raw_fd(),
877 temporary.as_ptr(),
878 self.directory_handle.as_raw_fd(),
879 target.as_ptr(),
880 )
881 } != 0
882 {
883 return Err(std::io::Error::last_os_error())
884 .context("atomically replacing xAI OAuth credentials");
885 }
886 } else {
887 #[cfg(any(target_os = "macos", target_os = "linux", target_os = "android"))]
888 // Exclusive rename publishes one link atomically. A hard-link
889 // publication briefly exposes two links to concurrent readers.
890 self.move_no_replace(&temp_name, name)?;
891 #[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "android")))]
892 {
893 // `linkat` installs the unique generation without clobbering an
894 // existing path. The temporary link is removed immediately.
895 // SAFETY: all descriptors/names remain valid for both calls.
896 if unsafe {
897 libc::linkat(
898 self.directory_handle.as_raw_fd(),
899 temporary.as_ptr(),
900 self.directory_handle.as_raw_fd(),
901 target.as_ptr(),
902 0,
903 )
904 } != 0
905 {
906 return Err(std::io::Error::last_os_error())
907 .context("installing a new xAI OAuth generation without replacement");
908 }
909 // SAFETY: same descriptor and staging name as the `linkat` above.
910 if unsafe {
911 libc::unlinkat(self.directory_handle.as_raw_fd(), temporary.as_ptr(), 0)
912 } != 0
913 {
914 let error = std::io::Error::last_os_error();
915 // The target and staging name still reference the same
916 // inode. Remove the just-installed target so the generic
917 // error cleanup can safely retire the single remaining
918 // staging link instead of leaving an inert secret with
919 // link count two.
920 // SAFETY: same descriptor; `target` was just installed above.
921 unsafe {
922 libc::unlinkat(self.directory_handle.as_raw_fd(), target.as_ptr(), 0)
923 };
924 return Err(error).context("removing xAI OAuth generation staging link");
925 }
926 }
927 }
928 self.directory_handle
929 .sync_all()
930 .context("syncing Codewhale credentials directory")?;
931 Ok(())
932 })();
933 drop(temp);
934 if result.is_err() {
935 let _ = self.remove_raw(&temp_name);
936 }
937 result
938 }
939
940 pub fn remove_raw(&self, name: &str) -> Result<bool> {
941 use std::os::fd::AsRawFd as _;
942 validate_private_basename(name)?;
943 let Some(file) = self.open_owned_file_for_read(name)? else {
944 return Ok(false);
945 };
946 validate_owned_file_handle(&file, &self.directory.join(name), self.guard)?;
947 drop(file);
948 let name = CString::new(name).context("xAI OAuth basename contains an interior NUL")?;
949 // SAFETY: the name is one component relative to the stable credentials
950 // directory descriptor and was validated immediately above.
951 if unsafe { libc::unlinkat(self.directory_handle.as_raw_fd(), name.as_ptr(), 0) } != 0 {
952 let error = std::io::Error::last_os_error();
953 if error.kind() == std::io::ErrorKind::NotFound {
954 return Ok(false);
955 }
956 return Err(error).context("removing Codewhale-owned xAI OAuth file");
957 }
958 Ok(true)
959 }
960
961 pub fn rename_raw(&self, from: &str, to: &str) -> Result<()> {
962 use std::os::fd::AsRawFd as _;
963 validate_private_basename(from)?;
964 validate_private_basename(to)?;
965 let source = self
966 .open_owned_file_for_read(from)?
967 .context("xAI OAuth source disappeared before retirement")?;
968 validate_owned_file_handle(&source, &self.directory.join(from), self.guard)?;
969 anyhow::ensure!(
970 self.open_owned_file_for_read(to)?.is_none(),
971 "refusing to replace an existing xAI OAuth retirement path"
972 );
973 drop(source);
974 let from = CString::new(from).context("xAI OAuth basename contains an interior NUL")?;
975 let to = CString::new(to).context("xAI OAuth basename contains an interior NUL")?;
976 // SAFETY: both names are one component relative to the same pinned
977 // directory descriptor.
978 if unsafe {
979 libc::renameat(
980 self.directory_handle.as_raw_fd(),
981 from.as_ptr(),
982 self.directory_handle.as_raw_fd(),
983 to.as_ptr(),
984 )
985 } != 0
986 {
987 return Err(std::io::Error::last_os_error()).context("retiring xAI OAuth file");
988 }
989 Ok(())
990 }
991 }
992
993 #[cfg(unix)]
994 pub(crate) fn validate_owned_file_handle(
995 file: &File,
996 path: &Path,
997 guard: PrivateGuard,
998 ) -> Result<fs::Metadata> {
999 use std::os::unix::fs::MetadataExt as _;
1000 let metadata = file.metadata().with_context(|| {
1001 format!(
1002 "inspecting Codewhale-owned xAI OAuth file {}",
1003 crate::quote_os_path(path)
1004 )
1005 })?;
1006 anyhow::ensure!(metadata.is_file(), "xAI OAuth path must be a regular file");
1007 // A file on a mount that reports ownership of its own carries the same
1008 // evidence as its directory: none. The link count still has to be exact,
1009 // because that is a real property the mount stores.
1010 if matches!(guard, PrivateGuard::Required) {
1011 // SAFETY: geteuid(2) dereferences no pointers.
1012 anyhow::ensure!(
1013 metadata.uid() == unsafe { libc::geteuid() },
1014 "xAI OAuth file must be owned by the current user"
1015 );
1016 }
1017 anyhow::ensure!(metadata.nlink() != 0, UnlinkedPrivateFile);
1018 anyhow::ensure!(
1019 metadata.nlink() == 1,
1020 "xAI OAuth file must not have multiple filesystem links"
1021 );
1022 Ok(metadata)
1023 }
1024
1025 #[cfg(windows)]
1026 fn open_owned_directory(
1027 directory: &Path,
1028 protect: bool,
1029 create: bool,
1030 _guard: PrivateGuard,
1031 ) -> Result<PrivateDirectory> {
1032 use std::os::windows::fs::OpenOptionsExt as _;
1033 use windows_sys::Win32::Storage::FileSystem::{
1034 FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OPEN_REPARSE_POINT, FILE_GENERIC_READ,
1035 FILE_SHARE_READ, FILE_SHARE_WRITE, WRITE_DAC, WRITE_OWNER,
1036 };
1037
1038 anyhow::ensure!(
1039 directory.is_absolute(),
1040 "xAI OAuth credentials directory must be absolute"
1041 );
1042 let mut current = PathBuf::new();
1043 let mut handles = Vec::new();
1044 let mut created_final = false;
1045 for component in directory.components() {
1046 match component {
1047 Component::Prefix(prefix) => current.push(prefix.as_os_str()),
1048 Component::RootDir => current.push(Path::new(r"\")),
1049 Component::Normal(name) => {
1050 current.push(name);
1051 created_final = false;
1052 if create {
1053 match fs::create_dir(&current) {
1054 Ok(()) => {
1055 created_final = true;
1056 }
1057 Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {}
1058 Err(error) => {
1059 return Err(error).with_context(|| {
1060 format!(
1061 "creating a component of Codewhale credentials directory {}",
1062 crate::quote_os_path(directory)
1063 )
1064 });
1065 }
1066 }
1067 }
1068 let mut options = fs::OpenOptions::new();
1069 options
1070 .read(true)
1071 .share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE)
1072 .custom_flags(FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT);
1073 let handle = options.open(&current).with_context(|| {
1074 format!(
1075 "opening Codewhale credentials directory component {}",
1076 crate::quote_os_path(&current)
1077 )
1078 })?;
1079 validate_windows_handle_path(&handle, &current, true)?;
1080 handles.push(handle);
1081 }
1082 Component::CurDir | Component::ParentDir => bail!(
1083 "Codewhale credentials directory must be lexically normalized: {}",
1084 crate::quote_os_path(directory)
1085 ),
1086 }
1087 }
1088 anyhow::ensure!(
1089 !handles.is_empty(),
1090 "Codewhale credentials directory cannot be a volume root"
1091 );
1092 let open_final = |access: u32| {
1093 let mut secure_options = fs::OpenOptions::new();
1094 secure_options
1095 .access_mode(access)
1096 .share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE)
1097 .custom_flags(FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT);
1098 secure_options.open(directory)
1099 };
1100 let not_owned_hint = || {
1101 format!(
1102 "Codewhale cannot make {} private: your account neither owns it nor has Full control \
1103 of it. Take ownership of the folder, or grant your account Full control, and retry",
1104 crate::quote_os_path(directory)
1105 )
1106 };
1107 let (final_directory, holds_write_owner) =
1108 match open_final(FILE_GENERIC_READ | WRITE_DAC | WRITE_OWNER) {
1109 Ok(handle) => (handle, true),
1110 Err(error) if error.raw_os_error() == Some(5) => {
1111 let handle = open_final(FILE_GENERIC_READ | WRITE_DAC)
1112 .with_context(|| {
1113 format!(
1114 "opening Codewhale credentials directory for owner-only security: {}",
1115 crate::quote_os_path(directory)
1116 )
1117 })
1118 .with_context(not_owned_hint)?;
1119 (handle, false)
1120 }
1121 Err(error) => {
1122 return Err(error).with_context(|| {
1123 format!(
1124 "opening Codewhale credentials directory for owner-only security: {}",
1125 crate::quote_os_path(directory)
1126 )
1127 });
1128 }
1129 };
1130 validate_windows_handle_path(&final_directory, directory, true)?;
1131 if protect || created_final {
1132 let secured = if holds_write_owner {
1133 secure_windows_owner_only_handle(&final_directory, true, true)
1134 } else {
1135 secure_windows_owner_only_handle(&final_directory, true, false)
1136 .with_context(not_owned_hint)
1137 };
1138 secured.context("securing the current-user private directory")?;
1139 }
1140 verify_windows_owner_only_handle(&final_directory)
1141 .context("verifying Codewhale credentials directory ownership")?;
1142 handles.push(final_directory);
1143 Ok(PrivateDirectory {
1144 directory: directory.to_path_buf(),
1145 _component_handles: handles,
1146 })
1147 }
1148
1149 #[cfg(windows)]
1150 impl PrivateDirectory {
1151 fn open_windows_file(&self, name: &str, read: bool, write: bool) -> Result<Option<File>> {
1152 use std::os::windows::fs::OpenOptionsExt as _;
1153 use windows_sys::Win32::Storage::FileSystem::{
1154 FILE_FLAG_OPEN_REPARSE_POINT, FILE_SHARE_READ, FILE_SHARE_WRITE,
1155 };
1156
1157 validate_private_basename(name)?;
1158 let path = self.directory.join(name);
1159 let mut options = fs::OpenOptions::new();
1160 options
1161 .read(read)
1162 .write(write)
1163 .share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE)
1164 .custom_flags(FILE_FLAG_OPEN_REPARSE_POINT);
1165 match options.open(&path) {
1166 Ok(file) => {
1167 validate_windows_owned_file_handle(&file, &path)?;
1168 Ok(Some(file))
1169 }
1170 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
1171 Err(error) => Err(error).with_context(|| {
1172 format!(
1173 "opening Codewhale-owned xAI OAuth path {}",
1174 crate::quote_os_path(&path)
1175 )
1176 }),
1177 }
1178 }
1179
1180 pub fn open_owned_file_for_read(&self, name: &str) -> Result<Option<File>> {
1181 self.open_windows_file(name, true, false)
1182 }
1183
1184 pub fn open_internal_file(&self, name: &str) -> Result<File> {
1185 use std::os::windows::fs::OpenOptionsExt as _;
1186 use windows_sys::Win32::Storage::FileSystem::{
1187 DELETE, FILE_FLAG_OPEN_REPARSE_POINT, FILE_GENERIC_READ, FILE_GENERIC_WRITE,
1188 FILE_SHARE_READ, FILE_SHARE_WRITE, WRITE_DAC, WRITE_OWNER,
1189 };
1190
1191 validate_private_basename(name)?;
1192 let path = self.directory.join(name);
1193 for _ in 0..8 {
1194 if let Some(existing) = self.open_windows_file(name, true, true)? {
1195 return Ok(existing);
1196 }
1197
1198 let mut options = fs::OpenOptions::new();
1199 options
1200 // `access_mode` supplies the exact Win32 access mask below,
1201 // while Rust still requires the portable write intent to be
1202 // set before it permits `create_new`.
1203 .write(true)
1204 .access_mode(
1205 FILE_GENERIC_READ | FILE_GENERIC_WRITE | WRITE_DAC | WRITE_OWNER | DELETE,
1206 )
1207 .create_new(true)
1208 .share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE)
1209 .custom_flags(FILE_FLAG_OPEN_REPARSE_POINT);
1210 let file = match options.open(&path) {
1211 Ok(file) => file,
1212 Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
1213 Err(error) => {
1214 return Err(error).with_context(|| {
1215 format!(
1216 "creating Codewhale-owned xAI OAuth lifecycle lock {}",
1217 crate::quote_os_path(&path)
1218 )
1219 });
1220 }
1221 };
1222 let secured = (|| -> Result<()> {
1223 validate_windows_file_shape(&file, &path)?;
1224 secure_windows_owner_only_handle(&file, false, true)
1225 .context("securing a new xAI OAuth lifecycle lock")?;
1226 validate_windows_owned_file_handle(&file, &path)?;
1227 Ok(())
1228 })();
1229 if let Err(error) = secured {
1230 let cleanup = mark_windows_file_handle_for_deletion(&file);
1231 return match cleanup {
1232 Ok(()) => Err(error),
1233 Err(cleanup) => Err(error).context(format!(
1234 "also failed to delete the empty lifecycle lock: {cleanup:#}"
1235 )),
1236 };
1237 }
1238 let identity = windows_file_identity(&file)?;
1239 drop(file);
1240 let file = self
1241 .open_windows_file(name, true, true)?
1242 .context("new xAI OAuth lifecycle lock disappeared after securing")?;
1243 anyhow::ensure!(
1244 windows_file_identity(&file)? == identity,
1245 "new xAI OAuth lifecycle lock identity changed after securing"
1246 );
1247 return Ok(file);
1248 }
1249 bail!("xAI OAuth lifecycle lock changed repeatedly while opening")
1250 }
1251
1252 pub fn write_owned_file(&self, name: &str, bytes: &[u8], allow_replace: bool) -> Result<()> {
1253 let path = self.directory.join(name);
1254 if let Some(existing) = self.open_owned_file_for_read(name)? {
1255 anyhow::ensure!(
1256 allow_replace,
1257 "refusing to replace an existing xAI OAuth generation"
1258 );
1259 drop(existing);
1260 }
1261 let mut temporary = tempfile::NamedTempFile::new_in(&self.directory)
1262 .context("creating private xAI OAuth temporary file")?;
1263 let temporary_path = temporary.path().to_path_buf();
1264 let security_handle =
1265 reopen_windows_file_for_owner_security(temporary.as_file(), &temporary_path)?;
1266 secure_windows_owner_only_handle(&security_handle, false, true)
1267 .context("securing a new xAI OAuth temporary file before writing credentials")?;
1268 validate_windows_owned_file_handle(&security_handle, &temporary_path)
1269 .context("verifying a new xAI OAuth temporary file before writing credentials")?;
1270 let write_result = (|| -> Result<()> {
1271 temporary
1272 .write_all(bytes)
1273 .context("writing xAI OAuth temporary file")?;
1274 temporary
1275 .flush()
1276 .context("flushing xAI OAuth temporary file")?;
1277 temporary
1278 .as_file()
1279 .sync_all()
1280 .context("syncing xAI OAuth temporary file")?;
1281 Ok(())
1282 })();
1283 if let Err(error) = write_result {
1284 return Err(cleanup_windows_secret_after_error(
1285 &security_handle,
1286 error,
1287 "temporary file",
1288 ));
1289 }
1290 let persisted = if allow_replace {
1291 match temporary.persist(&path) {
1292 Ok(file) => file,
1293 Err(error) => {
1294 let tempfile::PersistError { error, file } = error;
1295 let persistence_error = anyhow::Error::new(error)
1296 .context("atomically replacing xAI OAuth credentials");
1297 let error = cleanup_windows_secret_after_error(
1298 &security_handle,
1299 persistence_error,
1300 "temporary file",
1301 );
1302 drop(file);
1303 return Err(error);
1304 }
1305 }
1306 } else {
1307 match temporary.persist_noclobber(&path) {
1308 Ok(file) => file,
1309 Err(error) => {
1310 let tempfile::PersistError { error, file } = error;
1311 let persistence_error = anyhow::Error::new(error)
1312 .context("installing a new xAI OAuth generation without replacement");
1313 let error = cleanup_windows_secret_after_error(
1314 &security_handle,
1315 persistence_error,
1316 "temporary file",
1317 );
1318 drop(file);
1319 return Err(error);
1320 }
1321 }
1322 };
1323 if let Err(error) = validate_persisted_windows_owned_file(&persisted, &path) {
1324 // MoveFileEx has already published this exact object. Delete it by
1325 // handle rather than trusting the pathname again. For a refresh
1326 // replacement this can leave the unchanged config pointer missing;
1327 // that fail-closed availability outcome is safer than retaining a
1328 // generation that failed the post-publication invariant check.
1329 return Err(cleanup_windows_secret_after_error(
1330 &security_handle,
1331 error,
1332 "rejected generation",
1333 ));
1334 }
1335 Ok(())
1336 }
1337
1338 pub fn remove_raw(&self, name: &str) -> Result<bool> {
1339 use std::os::windows::fs::OpenOptionsExt as _;
1340 use windows_sys::Win32::Storage::FileSystem::{
1341 DELETE, FILE_FLAG_OPEN_REPARSE_POINT, FILE_GENERIC_READ, FILE_SHARE_DELETE,
1342 FILE_SHARE_READ, FILE_SHARE_WRITE,
1343 };
1344
1345 validate_private_basename(name)?;
1346 let path = self.directory.join(name);
1347 let mut options = fs::OpenOptions::new();
1348 options
1349 .access_mode(FILE_GENERIC_READ | DELETE)
1350 .share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE)
1351 .custom_flags(FILE_FLAG_OPEN_REPARSE_POINT);
1352 let file = match options.open(&path) {
1353 Ok(file) => file,
1354 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(false),
1355 Err(error) => return Err(error).context("opening xAI OAuth file for exact deletion"),
1356 };
1357 validate_windows_owned_file_handle(&file, &path)?;
1358 mark_windows_file_handle_for_deletion(&file)?;
1359 drop(file);
1360 Ok(true)
1361 }
1362 }
1363
1364 #[cfg(windows)]
1365 fn reopen_windows_file_for_owner_security(file: &File, path: &Path) -> Result<File> {
1366 use std::os::windows::io::{AsRawHandle as _, FromRawHandle as _};
1367 use windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE;
1368 use windows_sys::Win32::Storage::FileSystem::{
1369 DELETE, FILE_FLAG_OPEN_REPARSE_POINT, FILE_GENERIC_READ, FILE_GENERIC_WRITE,
1370 FILE_SHARE_DELETE, FILE_SHARE_READ, FILE_SHARE_WRITE, ReOpenFile, WRITE_DAC, WRITE_OWNER,
1371 };
1372
1373 // ReOpenFile derives a new handle from the already-created temporary file,
1374 // so no pathname can be substituted between creation and hardening.
1375 // SAFETY: `file` is live; no output pointers passed.
1376 let handle = unsafe {
1377 ReOpenFile(
1378 file.as_raw_handle(),
1379 FILE_GENERIC_READ | FILE_GENERIC_WRITE | WRITE_DAC | WRITE_OWNER | DELETE,
1380 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
1381 FILE_FLAG_OPEN_REPARSE_POINT,
1382 )
1383 };
1384 if handle == INVALID_HANDLE_VALUE {
1385 return Err(std::io::Error::last_os_error())
1386 .context("reopening a new xAI OAuth temporary file for owner-only security");
1387 }
1388 // SAFETY: ReOpenFile returned a newly owned handle on the success path.
1389 let reopened = unsafe { File::from_raw_handle(handle) };
1390 validate_windows_file_shape(&reopened, path)?;
1391 Ok(reopened)
1392 }
1393
1394 #[cfg(windows)]
1395 pub fn mark_windows_file_handle_for_deletion(file: &File) -> Result<()> {
1396 use std::os::windows::io::AsRawHandle as _;
1397 use windows_sys::Win32::Foundation::{
1398 ERROR_INVALID_FUNCTION, ERROR_INVALID_PARAMETER, ERROR_NOT_SUPPORTED,
1399 };
1400 use windows_sys::Win32::Storage::FileSystem::{
1401 FILE_DISPOSITION_FLAG_DELETE, FILE_DISPOSITION_FLAG_POSIX_SEMANTICS, FILE_DISPOSITION_INFO,
1402 FILE_DISPOSITION_INFO_EX, FileDispositionInfo, FileDispositionInfoEx,
1403 SetFileInformationByHandle,
1404 };
1405
1406 let posix = FILE_DISPOSITION_INFO_EX {
1407 Flags: FILE_DISPOSITION_FLAG_DELETE | FILE_DISPOSITION_FLAG_POSIX_SEMANTICS,
1408 };
1409 if unsafe {
1410 SetFileInformationByHandle(
1411 file.as_raw_handle(),
1412 FileDispositionInfoEx,
1413 (&raw const posix).cast(),
1414 std::mem::size_of::<FILE_DISPOSITION_INFO_EX>() as u32,
1415 )
1416 } != 0
1417 {
1418 return Ok(());
1419 }
1420 let error = std::io::Error::last_os_error();
1421 if !matches!(
1422 error.raw_os_error().map(|code| code as u32),
1423 Some(ERROR_INVALID_PARAMETER | ERROR_NOT_SUPPORTED | ERROR_INVALID_FUNCTION)
1424 ) {
1425 return Err(error).context("marking exact private file handle for deletion");
1426 }
1427 let disposition = FILE_DISPOSITION_INFO { DeleteFile: true };
1428 // SAFETY: the disposition buffer has the documented structure and the
1429 // handle remains owned until after the call. Windows marks this exact file
1430 // object delete-pending rather than resolving the path again.
1431 if unsafe {
1432 SetFileInformationByHandle(
1433 file.as_raw_handle(),
1434 FileDispositionInfo,
1435 (&raw const disposition).cast(),
1436 std::mem::size_of::<FILE_DISPOSITION_INFO>() as u32,
1437 )
1438 } == 0
1439 {
1440 return Err(std::io::Error::last_os_error())
1441 .context("marking exact private file handle for deletion");
1442 }
1443 Ok(())
1444 }
1445
1446 #[cfg(windows)]
1447 fn cleanup_windows_secret_after_error(
1448 file: &File,
1449 error: anyhow::Error,
1450 label: &str,
1451 ) -> anyhow::Error {
1452 match mark_windows_file_handle_for_deletion(file) {
1453 Ok(()) => error,
1454 Err(cleanup) => error.context(format!(
1455 "also failed to delete the xAI OAuth {label} by exact handle: {cleanup:#}"
1456 )),
1457 }
1458 }
1459
1460 #[cfg(all(windows, test))]
1461 static WINDOWS_POST_PERSIST_VALIDATION_FAILURE: Mutex<Option<PathBuf>> = Mutex::new(None);
1462
1463 #[cfg(windows)]
1464 fn validate_persisted_windows_owned_file(file: &File, path: &Path) -> Result<fs::Metadata> {
1465 #[cfg(test)]
1466 {
1467 let mut injected = WINDOWS_POST_PERSIST_VALIDATION_FAILURE
1468 .lock()
1469 .unwrap_or_else(std::sync::PoisonError::into_inner);
1470 if injected.as_deref() == Some(path) {
1471 *injected = None;
1472 bail!("injected post-persistence xAI OAuth validation failure");
1473 }
1474 }
1475 validate_windows_owned_file_handle(file, path)
1476 }
1477
1478 #[cfg(all(windows, test))]
1479 pub(crate) fn fail_next_windows_post_persist_validation(path: &Path) {
1480 *WINDOWS_POST_PERSIST_VALIDATION_FAILURE
1481 .lock()
1482 .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(path.to_path_buf());
1483 }
1484
1485 #[cfg(windows)]
1486 pub(crate) fn validate_owned_file_handle(
1487 file: &File,
1488 path: &Path,
1489 _guard: PrivateGuard,
1490 ) -> Result<fs::Metadata> {
1491 validate_windows_owned_file_handle(file, path)
1492 }
1493
1494 #[cfg(windows)]
1495 fn validate_windows_owned_file_handle(file: &File, path: &Path) -> Result<fs::Metadata> {
1496 let metadata = validate_windows_file_shape(file, path)?;
1497 verify_windows_owner_only_handle(file)
1498 .context("Codewhale-owned xAI OAuth file is not current-user-only")?;
1499 Ok(metadata)
1500 }
1501
1502 #[cfg(windows)]
1503 pub(crate) fn validate_windows_file_shape(file: &File, path: &Path) -> Result<fs::Metadata> {
1504 use std::os::windows::io::AsRawHandle as _;
1505 use windows_sys::Win32::Storage::FileSystem::{
1506 BY_HANDLE_FILE_INFORMATION, GetFileInformationByHandle,
1507 };
1508
1509 let metadata = validate_windows_handle_path(file, path, false)?;
1510 let mut information = BY_HANDLE_FILE_INFORMATION::default();
1511 // SAFETY: both pointers remain valid for the duration of the call.
1512 if unsafe { GetFileInformationByHandle(file.as_raw_handle(), &mut information) } == 0 {
1513 return Err(std::io::Error::last_os_error())
1514 .context("inspecting xAI OAuth file link count");
1515 }
1516 anyhow::ensure!(
1517 information.nNumberOfLinks == 1,
1518 "xAI OAuth file must not have multiple filesystem links"
1519 );
1520 Ok(metadata)
1521 }
1522
1523 #[cfg(windows)]
1524 fn validate_windows_handle_path(
1525 file: &File,
1526 expected: &Path,
1527 expect_directory: bool,
1528 ) -> Result<fs::Metadata> {
1529 use std::os::windows::fs::MetadataExt as _;
1530 use windows_sys::Win32::Storage::FileSystem::FILE_ATTRIBUTE_REPARSE_POINT;
1531
1532 let metadata = file.metadata().with_context(|| {
1533 format!(
1534 "inspecting Codewhale-owned path {}",
1535 crate::quote_os_path(expected)
1536 )
1537 })?;
1538 anyhow::ensure!(
1539 metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT == 0,
1540 "Codewhale-owned xAI OAuth path must not be a reparse point"
1541 );
1542 anyhow::ensure!(
1543 if expect_directory {
1544 metadata.is_dir()
1545 } else {
1546 metadata.is_file()
1547 },
1548 "Codewhale-owned xAI OAuth path has the wrong filesystem type"
1549 );
1550
1551 // Compare the current selection to the captured object, not its lexical
1552 // spelling: Windows can select the same object through an 8.3 short name.
1553 // Reparse points are refused at every component. These attribute-only
1554 // handles do not pin the path (they bypass share checks); a component
1555 // swapped mid-walk either fails to open or selects a different identity,
1556 // which this comparison refuses.
1557 let components = open_windows_selected_components(expected, expect_directory)?;
1558 let selected = components
1559 .last()
1560 .context("private selected path unavailable")?;
1561 anyhow::ensure!(
1562 windows_file_identity(file)? == windows_file_identity(selected)?
1563 && normalize_windows_path_for_comparison(&windows_final_handle_path(file)?)?
1564 == normalize_windows_path_for_comparison(&windows_final_handle_path(selected)?)?,
1565 "Codewhale-owned xAI OAuth path was redirected while opening"
1566 );
1567 Ok(metadata)
1568 }
1569
1570 #[cfg(windows)]
1571 fn open_windows_selected_components(expected: &Path, expect_directory: bool) -> Result<Vec<File>> {
1572 use std::os::windows::fs::{MetadataExt as _, OpenOptionsExt as _};
1573 use windows_sys::Win32::Storage::FileSystem::{
1574 FILE_ATTRIBUTE_REPARSE_POINT, FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OPEN_REPARSE_POINT,
1575 FILE_READ_ATTRIBUTES, FILE_SHARE_DELETE, FILE_SHARE_READ, FILE_SHARE_WRITE,
1576 };
1577
1578 anyhow::ensure!(
1579 expected.is_absolute(),
1580 "private selected path must be absolute"
1581 );
1582 let mut current = PathBuf::new();
1583 let mut handles = Vec::new();
1584 let mut components = expected.components().peekable();
1585 while let Some(component) = components.next() {
1586 match component {
1587 Component::Prefix(prefix) => current.push(prefix.as_os_str()),
1588 Component::RootDir => current.push(Path::new(r"\")),
1589 Component::Normal(name) => {
1590 current.push(name);
1591 let directory = components.peek().is_some() || expect_directory;
1592 let handle = fs::OpenOptions::new()
1593 .access_mode(FILE_READ_ATTRIBUTES)
1594 .share_mode(
1595 FILE_SHARE_READ
1596 | FILE_SHARE_WRITE
1597 | if directory { 0 } else { FILE_SHARE_DELETE },
1598 )
1599 .custom_flags(FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT)
1600 .open(&current)
1601 .context("opening the current private path selection")?;
1602 let metadata = handle.metadata()?;
1603 anyhow::ensure!(
1604 metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT == 0,
1605 "Codewhale-owned xAI OAuth path must not be a reparse point"
1606 );
1607 anyhow::ensure!(
1608 if directory {
1609 metadata.is_dir()
1610 } else {
1611 metadata.is_file()
1612 },
1613 "Codewhale-owned xAI OAuth path has the wrong filesystem type"
1614 );
1615 handles.push(handle);
1616 }
1617 Component::CurDir | Component::ParentDir => {
1618 bail!("private selected path must be lexically normalized")
1619 }
1620 }
1621 }
1622 anyhow::ensure!(
1623 !handles.is_empty(),
1624 "private selected path cannot be a volume root"
1625 );
1626 Ok(handles)
1627 }
1628
1629 #[cfg(windows)]
1630 fn windows_final_handle_path(file: &File) -> Result<PathBuf> {
1631 use std::ffi::OsString;
1632 use std::os::windows::ffi::OsStringExt as _;
1633 use std::os::windows::io::AsRawHandle as _;
1634 use windows_sys::Win32::Storage::FileSystem::{
1635 FILE_NAME_NORMALIZED, GetFinalPathNameByHandleW, VOLUME_NAME_DOS,
1636 };
1637
1638 let flags = FILE_NAME_NORMALIZED | VOLUME_NAME_DOS;
1639 let handle = file.as_raw_handle();
1640 // SAFETY: null output asks only for the required UTF-16 length.
1641 let needed = unsafe { GetFinalPathNameByHandleW(handle, std::ptr::null_mut(), 0, flags) };
1642 if needed == 0 {
1643 return Err(std::io::Error::last_os_error())
1644 .context("resolving Codewhale-owned xAI OAuth handle path");
1645 }
1646 let mut buffer = vec![0u16; needed as usize + 1];
1647 // SAFETY: the buffer is writable and the handle remains valid.
1648 let written = unsafe {
1649 GetFinalPathNameByHandleW(handle, buffer.as_mut_ptr(), buffer.len() as u32, flags)
1650 };
1651 if written == 0 || written as usize >= buffer.len() {
1652 return Err(std::io::Error::last_os_error())
1653 .context("resolving Codewhale-owned xAI OAuth handle path");
1654 }
1655 Ok(PathBuf::from(OsString::from_wide(
1656 &buffer[..written as usize],
1657 )))
1658 }
1659
1660 #[cfg(all(test, windows))]
1661 mod windows_tests {
1662 use super::*;
1663 use std::os::windows::fs::OpenOptionsExt as _;
1664 use windows_sys::Win32::Storage::FileSystem::{
1665 FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OPEN_REPARSE_POINT, FILE_SHARE_DELETE,
1666 FILE_SHARE_READ, FILE_SHARE_WRITE,
1667 };
1668
1669 #[test]
1670 fn selected_path_alias_keeps_identity_and_replacement_is_refused() {
1671 let root = tempfile::tempdir().expect("temporary root");
1672 let selected = root.path().join("credentials");
1673 fs::create_dir(&selected).expect("selected directory");
1674 // Hosted Windows temporary roots can contain RUNNER~1 while the kernel
1675 // reports the long spelling. Both must select the same retained object.
1676 let canonical = selected
1677 .canonicalize()
1678 .expect("canonical selected directory");
1679 let held = fs::OpenOptions::new()
1680 .read(true)
1681 .share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE)
1682 .custom_flags(FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT)
1683 .open(&selected)
1684 .expect("captured selected directory");
1685 validate_windows_handle_path(&held, &selected, true).expect("selected spelling");
1686 validate_windows_handle_path(&held, &canonical, true).expect("canonical spelling");
1687
1688 let retained = root.path().join("retained");
1689 fs::rename(&selected, &retained).expect("move captured object");
1690 fs::create_dir(&selected).expect("replacement at the same selected path");
1691 assert!(
1692 validate_windows_handle_path(&held, &selected, true).is_err(),
1693 "a replacement at the selected path must not inherit the captured identity"
1694 );
1695 validate_windows_handle_path(&held, &retained, true).expect("actual retained object");
1696 fs::create_dir(root.path().join("other")).expect("existing unnormalized path component");
1697 assert!(
1698 validate_windows_handle_path(&held, &root.path().join("other/../retained"), true)
1699 .is_err(),
1700 "lexically unnormalized paths remain inadmissible"
1701 );
1702 }
1703
1704 #[test]
1705 fn owner_with_modify_but_not_full_control_secures_its_private_directory() {
1706 use windows_sys::Win32::Foundation::{CloseHandle, HANDLE, LUID};
1707 use windows_sys::Win32::Security::{
1708 AdjustTokenPrivileges, DuplicateTokenEx, LUID_AND_ATTRIBUTES, LookupPrivilegeValueW,
1709 RevertToSelf, SE_CHANGE_NOTIFY_NAME, SE_PRIVILEGE_ENABLED, SecurityImpersonation,
1710 TOKEN_ADJUST_PRIVILEGES, TOKEN_DUPLICATE, TOKEN_IMPERSONATE, TOKEN_PRIVILEGES,
1711 TOKEN_QUERY, TokenImpersonation,
1712 };
1713 use windows_sys::Win32::Storage::FileSystem::{FILE_GENERIC_READ, WRITE_DAC, WRITE_OWNER};
1714 use windows_sys::Win32::System::Threading::{
1715 GetCurrentProcess, OpenProcessToken, SetThreadToken,
1716 };
1717
1718 struct UnprivilegedThread(HANDLE, HANDLE);
1719 impl Drop for UnprivilegedThread {
1720 fn drop(&mut self) {
1721 // SAFETY: reverts this thread and closes the two handles it owns.
1722 unsafe {
1723 RevertToSelf();
1724 CloseHandle(self.1);
1725 CloseHandle(self.0);
1726 }
1727 }
1728 }
1729
1730 let root = tempfile::tempdir().expect("temporary root");
1731 let state = root.path().join("state");
1732 fs::create_dir(&state).expect("state directory");
1733 let sid = CurrentWindowsUser::open()
1734 .and_then(|user| user.sid_string())
1735 .expect("current user SID");
1736 let icacls = |args: &[&str]| {
1737 let output = std::process::Command::new("icacls")
1738 .arg(&state)
1739 .args(args)
1740 .output()
1741 .expect("run icacls");
1742 assert!(
1743 output.status.success(),
1744 "icacls {args:?}: {}",
1745 String::from_utf8_lossy(&output.stdout)
1746 );
1747 };
1748 icacls(&["/setowner", &format!("*{sid}")]);
1749 icacls(&["/inheritance:r", "/grant:r", &format!("*{sid}:(OI)(CI)M")]);
1750
1751 let mut process_token: HANDLE = std::ptr::null_mut();
1752 let mut restricted: HANDLE = std::ptr::null_mut();
1753 // SAFETY: pseudo process handle and writable outputs; both handles are
1754 // owned by the guard, which reverts and closes them.
1755 let _unprivileged = unsafe {
1756 assert_ne!(
1757 OpenProcessToken(
1758 GetCurrentProcess(),
1759 TOKEN_DUPLICATE | TOKEN_QUERY,
1760 &mut process_token
1761 ),
1762 0
1763 );
1764 assert_ne!(
1765 DuplicateTokenEx(
1766 process_token,
1767 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY | TOKEN_IMPERSONATE,
1768 std::ptr::null(),
1769 SecurityImpersonation,
1770 TokenImpersonation,
1771 &mut restricted,
1772 ),
1773 0
1774 );
1775 let guard = UnprivilegedThread(process_token, restricted);
1776 assert_ne!(
1777 AdjustTokenPrivileges(
1778 restricted,
1779 1,
1780 std::ptr::null(),
1781 0,
1782 std::ptr::null_mut(),
1783 std::ptr::null_mut()
1784 ),
1785 0
1786 );
1787 let mut traverse = TOKEN_PRIVILEGES {
1788 PrivilegeCount: 1,
1789 Privileges: [LUID_AND_ATTRIBUTES {
1790 Luid: LUID::default(),
1791 Attributes: SE_PRIVILEGE_ENABLED,
1792 }],
1793 };
1794 assert_ne!(
1795 LookupPrivilegeValueW(
1796 std::ptr::null(),
1797 SE_CHANGE_NOTIFY_NAME,
1798 &mut traverse.Privileges[0].Luid
1799 ),
1800 0
1801 );
1802 assert_ne!(
1803 AdjustTokenPrivileges(
1804 restricted,
1805 0,
1806 &traverse,
1807 0,
1808 std::ptr::null_mut(),
1809 std::ptr::null_mut()
1810 ),
1811 0
1812 );
1813 assert_ne!(SetThreadToken(std::ptr::null(), restricted), 0);
1814 guard
1815 };
1816
1817 match fs::OpenOptions::new()
1818 .access_mode(FILE_GENERIC_READ | WRITE_DAC | WRITE_OWNER)
1819 .share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE)
1820 .custom_flags(FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT)
1821 .open(&state)
1822 {
1823 Err(denied) => assert_eq!(denied.raw_os_error(), Some(5)),
1824 Ok(_) => eprintln!("this account is granted WRITE_OWNER here; fallback not exercised"),
1825 }
1826
1827 drop(
1828 PrivateDirectory::open(&state)
1829 .expect("the owner secures its directory without WRITE_OWNER"),
1830 );
1831 PrivateDirectory::inspect(&state).expect("the secured directory is current-user-only");
1832 }
1833 }
1834
1835 #[cfg(windows)]
1836 pub(crate) fn normalize_windows_path_for_comparison(path: &Path) -> Result<String> {
1837 let text = path.to_str().ok_or_else(|| {
1838 anyhow::anyhow!(
1839 "xAI OAuth path {} contains invalid Unicode and cannot be compared safely",
1840 crate::quote_os_path(path)
1841 )
1842 })?;
1843 let without_device_prefix = text.strip_prefix(r"\\?\").unwrap_or(text);
1844 let normalized_prefix = without_device_prefix.strip_prefix("UNC\\").map_or_else(
1845 || without_device_prefix.to_string(),
1846 |rest| format!(r"\\{rest}"),
1847 );
1848 Ok(normalized_prefix
1849 .replace('/', "\\")
1850 .trim_end_matches('\\')
1851 .to_lowercase())
1852 }
1853
1854 #[cfg(windows)]
1855 fn secure_windows_owner_only_handle(
1856 file: &File,
1857 inherit_to_children: bool,
1858 set_owner: bool,
1859 ) -> Result<()> {
1860 use std::os::windows::io::AsRawHandle as _;
1861 use windows_sys::Win32::Foundation::ERROR_SUCCESS;
1862 use windows_sys::Win32::Security::Authorization::{
1863 GetSecurityInfo, SE_FILE_OBJECT, SetSecurityInfo,
1864 };
1865 use windows_sys::Win32::Security::{
1866 DACL_SECURITY_INFORMATION, EqualSid, OWNER_SECURITY_INFORMATION,
1867 PROTECTED_DACL_SECURITY_INFORMATION, PSECURITY_DESCRIPTOR, PSID,
1868 };
1869 use windows_sys::Win32::Storage::FileSystem::FILE_ALL_ACCESS;
1870
1871 let acl = crate::windows_identity::OwnerOnlyAcl::new(FILE_ALL_ACCESS, inherit_to_children)?;
1872 if !set_owner {
1873 let mut owner: PSID = std::ptr::null_mut();
1874 let mut descriptor: PSECURITY_DESCRIPTOR = std::ptr::null_mut();
1875 // SAFETY: the handle remains valid and all output pointers are writable.
1876 let result = unsafe {
1877 GetSecurityInfo(
1878 file.as_raw_handle(),
1879 SE_FILE_OBJECT,
1880 OWNER_SECURITY_INFORMATION,
1881 &mut owner,
1882 std::ptr::null_mut(),
1883 std::ptr::null_mut(),
1884 std::ptr::null_mut(),
1885 &mut descriptor,
1886 )
1887 };
1888 if result != ERROR_SUCCESS {
1889 return Err(std::io::Error::from_raw_os_error(result as i32))
1890 .context("reading the owner of Codewhale-owned private storage");
1891 }
1892 let _descriptor = WindowsLocalAllocation(descriptor.cast());
1893 // SAFETY: `owner` belongs to the live descriptor; the ACL owns its SID.
1894 anyhow::ensure!(
1895 !owner.is_null() && unsafe { EqualSid(owner, acl.user_sid()) } != 0,
1896 "Codewhale-owned private storage is owned by another account"
1897 );
1898 }
1899 let (security_information, owner) = if set_owner {
1900 (
1901 OWNER_SECURITY_INFORMATION
1902 | DACL_SECURITY_INFORMATION
1903 | PROTECTED_DACL_SECURITY_INFORMATION,
1904 acl.user_sid(),
1905 )
1906 } else {
1907 (
1908 DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION,
1909 std::ptr::null_mut(),
1910 )
1911 };
1912 // SAFETY: the file handle remains owned by `file`, and the ACL remains
1913 // allocated for the duration of the call. The protected DACL is committed
1914 // together with the owner, or after proving the owner is already the
1915 // current user, so the verifier never observes a half-secured file.
1916 let result = unsafe {
1917 SetSecurityInfo(
1918 file.as_raw_handle(),
1919 SE_FILE_OBJECT,
1920 security_information,
1921 owner,
1922 std::ptr::null_mut(),
1923 acl.acl(),
1924 std::ptr::null(),
1925 )
1926 };
1927 if result != ERROR_SUCCESS {
1928 return Err(std::io::Error::from_raw_os_error(result as i32))
1929 .context("applying a current-user-only DACL to Codewhale-owned xAI OAuth storage");
1930 }
1931 Ok(())
1932 }
1933
1934 #[cfg(windows)]
1935 pub(crate) fn verify_windows_owner_only_handle(file: &File) -> Result<()> {
1936 use windows_sys::Win32::Storage::FileSystem::FILE_ALL_ACCESS;
1937
1938 verify_windows_owner_only_handle_access(file, FILE_ALL_ACCESS)
1939 }
1940
1941 #[cfg(windows)]
1942 pub fn verify_windows_finalized_read_only_handle(file: &File) -> Result<()> {
1943 use std::os::windows::io::AsRawHandle as _;
1944 use windows_sys::Win32::Foundation::{
1945 ERROR_SUCCESS, GENERIC_ALL, GENERIC_EXECUTE, GENERIC_READ, GENERIC_WRITE,
1946 };
1947 use windows_sys::Win32::Security::Authorization::{GetSecurityInfo, SE_FILE_OBJECT};
1948 use windows_sys::Win32::Security::{
1949 ACCESS_ALLOWED_ACE, ACL, DACL_SECURITY_INFORMATION, EqualSid, GetAce,
1950 GetSecurityDescriptorControl, GetSidIdentifierAuthority, GetSidSubAuthority,
1951 GetSidSubAuthorityCount, IsValidSid, OWNER_SECURITY_INFORMATION, PSECURITY_DESCRIPTOR,
1952 PSID, SE_DACL_PROTECTED,
1953 };
1954 use windows_sys::Win32::Storage::FileSystem::{
1955 FILE_ALL_ACCESS, FILE_GENERIC_EXECUTE, FILE_GENERIC_READ, FILE_GENERIC_WRITE,
1956 };
1957
1958 const ACCESS_ALLOWED_ACE_TYPE: u8 = 0;
1959 const INHERIT_ONLY_ACE: u8 = 0x08;
1960 const APP_PACKAGE_AUTHORITY: [u8; 6] = [0, 0, 0, 0, 0, 15];
1961 const APP_PACKAGE_BASE_RID: u32 = 2;
1962 const READ_EXECUTE: u32 = FILE_GENERIC_READ | FILE_GENERIC_EXECUTE;
1963
1964 let user = CurrentWindowsUser::open()?;
1965 let mut owner: PSID = std::ptr::null_mut();
1966 let mut dacl: *mut ACL = std::ptr::null_mut();
1967 let mut descriptor: PSECURITY_DESCRIPTOR = std::ptr::null_mut();
1968 // SAFETY: the handle remains valid and all output pointers are writable.
1969 let result = unsafe {
1970 GetSecurityInfo(
1971 file.as_raw_handle(),
1972 SE_FILE_OBJECT,
1973 OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
1974 &mut owner,
1975 std::ptr::null_mut(),
1976 &mut dacl,
1977 std::ptr::null_mut(),
1978 &mut descriptor,
1979 )
1980 };
1981 if result != ERROR_SUCCESS {
1982 return Err(std::io::Error::from_raw_os_error(result as i32))
1983 .context("reading Codewhale-owned read-only storage security descriptor");
1984 }
1985 let _descriptor = WindowsLocalAllocation(descriptor.cast());
1986 let mut control = 0;
1987 let mut revision = 0;
1988 // SAFETY: `descriptor` is the live descriptor returned above.
1989 if unsafe { GetSecurityDescriptorControl(descriptor, &mut control, &mut revision) } == 0 {
1990 return Err(std::io::Error::last_os_error())
1991 .context("reading Codewhale-owned storage DACL protection");
1992 }
1993 anyhow::ensure!(
1994 control & SE_DACL_PROTECTED != 0,
1995 "Codewhale-owned storage DACL is not protected"
1996 );
1997 // SAFETY: `owner` is non-null; `user.sid()` is owned by `user`.
1998 anyhow::ensure!(
1999 !owner.is_null() && unsafe { EqualSid(owner, user.sid()) } != 0,
2000 "Codewhale-owned read-only storage owner is not the current user"
2001 );
2002 anyhow::ensure!(
2003 !dacl.is_null(),
2004 "Codewhale-owned read-only storage must have a DACL"
2005 );
2006 let normalized_access = |access: u32| {
2007 let mut normalized =
2008 access & !(GENERIC_ALL | GENERIC_EXECUTE | GENERIC_READ | GENERIC_WRITE);
2009 for (generic, specific) in [
2010 (GENERIC_ALL, FILE_ALL_ACCESS),
2011 (GENERIC_EXECUTE, FILE_GENERIC_EXECUTE),
2012 (GENERIC_READ, FILE_GENERIC_READ),
2013 (GENERIC_WRITE, FILE_GENERIC_WRITE),
2014 ] {
2015 if access & generic != 0 {
2016 normalized |= specific;
2017 }
2018 }
2019 normalized
2020 };
2021 // SAFETY: `dacl` belongs to the live descriptor.
2022 let ace_count = u32::from(unsafe { (*dacl).AceCount });
2023 let mut user_access = 0;
2024 for index in 0..ace_count {
2025 let mut raw = std::ptr::null_mut();
2026 // SAFETY: `index` is below the ACL's own ACE count.
2027 if unsafe { GetAce(dacl, index, &mut raw) } == 0 || raw.is_null() {
2028 return Err(std::io::Error::last_os_error())
2029 .context("reading Codewhale-owned read-only storage DACL entry");
2030 }
2031 // SAFETY: every ACE begins with ACE_HEADER, which ACCESS_ALLOWED_ACE
2032 // starts with; the type is checked before the SID is read.
2033 let ace = unsafe { &*raw.cast::<ACCESS_ALLOWED_ACE>() };
2034 anyhow::ensure!(
2035 ace.Header.AceType == ACCESS_ALLOWED_ACE_TYPE,
2036 "Codewhale-owned read-only storage DACL holds an unexpected entry type"
2037 );
2038 let sid: PSID = std::ptr::addr_of!(ace.SidStart).cast_mut().cast();
2039 // SAFETY: an access-allowed ACE stores its SID at `SidStart`.
2040 anyhow::ensure!(
2041 unsafe { IsValidSid(sid) } != 0,
2042 "Codewhale-owned read-only storage DACL holds an invalid SID"
2043 );
2044 let access = normalized_access(ace.Mask);
2045 anyhow::ensure!(
2046 access & !READ_EXECUTE == 0,
2047 "Codewhale-owned read-only storage DACL grants more than read and execute"
2048 );
2049 // SAFETY: `sid` was validated above; `user.sid()` is owned by `user`.
2050 if unsafe { EqualSid(sid, user.sid()) } != 0 {
2051 if ace.Header.AceFlags & INHERIT_ONLY_ACE == 0 {
2052 user_access |= access;
2053 }
2054 continue;
2055 }
2056 // SAFETY: `sid` was validated above, so its authority, count and
2057 // first sub-authority are readable.
2058 let is_app_container = unsafe {
2059 (*GetSidIdentifierAuthority(sid)).Value == APP_PACKAGE_AUTHORITY
2060 && *GetSidSubAuthorityCount(sid) > 0
2061 && *GetSidSubAuthority(sid, 0) == APP_PACKAGE_BASE_RID
2062 };
2063 anyhow::ensure!(
2064 is_app_container,
2065 "Codewhale-owned read-only storage DACL grants another user"
2066 );
2067 }
2068 anyhow::ensure!(
2069 user_access == READ_EXECUTE,
2070 "Codewhale-owned read-only storage DACL does not grant the current user read and execute"
2071 );
2072 Ok(())
2073 }
2074
2075 #[cfg(windows)]
2076 fn verify_windows_owner_only_handle_access(file: &File, expected_access: u32) -> Result<()> {
2077 use std::os::windows::io::AsRawHandle as _;
2078 use windows_sys::Win32::Foundation::{
2079 ERROR_SUCCESS, GENERIC_ALL, GENERIC_EXECUTE, GENERIC_READ, GENERIC_WRITE,
2080 };
2081 use windows_sys::Win32::Security::Authorization::{
2082 EXPLICIT_ACCESS_W, GRANT_ACCESS, GetExplicitEntriesFromAclW, GetSecurityInfo,
2083 SE_FILE_OBJECT, SET_ACCESS, TRUSTEE_IS_SID,
2084 };
2085 use windows_sys::Win32::Security::{
2086 ACL, DACL_SECURITY_INFORMATION, EqualSid, OWNER_SECURITY_INFORMATION, PSECURITY_DESCRIPTOR,
2087 PSID,
2088 };
2089 use windows_sys::Win32::Storage::FileSystem::{
2090 FILE_ALL_ACCESS, FILE_GENERIC_EXECUTE, FILE_GENERIC_READ, FILE_GENERIC_WRITE,
2091 };
2092
2093 let user = CurrentWindowsUser::open()?;
2094 let mut owner: PSID = std::ptr::null_mut();
2095 let mut dacl: *mut ACL = std::ptr::null_mut();
2096 let mut descriptor: PSECURITY_DESCRIPTOR = std::ptr::null_mut();
2097 // SAFETY: the handle remains valid and all output pointers are writable.
2098 let result = unsafe {
2099 GetSecurityInfo(
2100 file.as_raw_handle(),
2101 SE_FILE_OBJECT,
2102 OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
2103 &mut owner,
2104 std::ptr::null_mut(),
2105 &mut dacl,
2106 std::ptr::null_mut(),
2107 &mut descriptor,
2108 )
2109 };
2110 if result != ERROR_SUCCESS {
2111 return Err(std::io::Error::from_raw_os_error(result as i32))
2112 .context("reading Codewhale-owned xAI OAuth security descriptor");
2113 }
2114 let _descriptor = WindowsLocalAllocation(descriptor.cast());
2115 // SAFETY: `owner` is non-null; `user.sid()` is owned by `user`.
2116 anyhow::ensure!(
2117 !owner.is_null() && unsafe { EqualSid(owner, user.sid()) } != 0,
2118 "Codewhale-owned xAI OAuth storage owner is not the current user"
2119 );
2120 anyhow::ensure!(
2121 !dacl.is_null(),
2122 "Codewhale-owned xAI OAuth storage must have an owner-only DACL"
2123 );
2124 let mut count = 0;
2125 let mut entries: *mut EXPLICIT_ACCESS_W = std::ptr::null_mut();
2126 // SAFETY: `dacl` belongs to the live descriptor; Windows allocates the
2127 // returned entry array, released by the guard below.
2128 let result = unsafe { GetExplicitEntriesFromAclW(dacl, &mut count, &mut entries) };
2129 if result != ERROR_SUCCESS {
2130 return Err(std::io::Error::from_raw_os_error(result as i32))
2131 .context("reading Codewhale-owned xAI OAuth DACL entries");
2132 }
2133 let _entries = WindowsLocalAllocation(entries.cast());
2134 anyhow::ensure!(
2135 count == 1 && !entries.is_null(),
2136 "Codewhale-owned xAI OAuth DACL must grant only one user"
2137 );
2138 // SAFETY: `count == 1` proves the first returned entry is initialized.
2139 let entry = unsafe { &*entries };
2140 let trustee_sid: PSID = entry.Trustee.ptstrName.cast();
2141 let normalized_access = |access: u32| {
2142 let mut normalized =
2143 access & !(GENERIC_ALL | GENERIC_EXECUTE | GENERIC_READ | GENERIC_WRITE);
2144 for (generic, specific) in [
2145 (GENERIC_ALL, FILE_ALL_ACCESS),
2146 (GENERIC_EXECUTE, FILE_GENERIC_EXECUTE),
2147 (GENERIC_READ, FILE_GENERIC_READ),
2148 (GENERIC_WRITE, FILE_GENERIC_WRITE),
2149 ] {
2150 if access & generic != 0 {
2151 normalized |= specific;
2152 }
2153 }
2154 normalized
2155 };
2156 // SAFETY: form and null checked in this expression; sid owned by `user`.
2157 anyhow::ensure!(
2158 entry.Trustee.TrusteeForm == TRUSTEE_IS_SID
2159 && !trustee_sid.is_null()
2160 && unsafe { EqualSid(trustee_sid, user.sid()) } != 0
2161 && matches!(entry.grfAccessMode, SET_ACCESS | GRANT_ACCESS)
2162 && normalized_access(entry.grfAccessPermissions) == normalized_access(expected_access),
2163 "Codewhale-owned xAI OAuth DACL is not current-user-only"
2164 );
2165 Ok(())
2166 }
2167
2168 #[cfg(not(any(unix, windows)))]
2169 fn open_owned_directory(
2170 directory: &Path,
2171 protect: bool,
2172 create: bool,
2173 _guard: PrivateGuard,
2174 ) -> Result<PrivateDirectory> {
2175 anyhow::ensure!(
2176 protect,
2177 "private endpoint authentication is unsupported on this platform"
2178 );
2179 if create {
2180 fs::create_dir_all(directory)?;
2181 }
2182 let metadata = fs::symlink_metadata(directory)?;
2183 anyhow::ensure!(
2184 metadata.is_dir(),
2185 "Codewhale credentials path must be a directory"
2186 );
2187 Ok(PrivateDirectory {
2188 directory: directory.to_path_buf(),
2189 })
2190 }
2191
2192 #[cfg(not(any(unix, windows)))]
2193 impl PrivateDirectory {
2194 pub fn open_owned_file_for_read(&self, name: &str) -> Result<Option<File>> {
2195 validate_private_basename(name)?;
2196 match File::open(self.directory.join(name)) {
2197 Ok(file) => Ok(Some(file)),
2198 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
2199 Err(error) => Err(error.into()),
2200 }
2201 }
2202
2203 pub fn open_internal_file(&self, name: &str) -> Result<File> {
2204 validate_private_basename(name)?;
2205 Ok(fs::OpenOptions::new()
2206 .read(true)
2207 .write(true)
2208 .create(true)
2209 .open(self.directory.join(name))?)
2210 }
2211
2212 pub fn write_owned_file(&self, name: &str, bytes: &[u8], allow_replace: bool) -> Result<()> {
2213 validate_private_basename(name)?;
2214 let path = self.directory.join(name);
2215 anyhow::ensure!(
2216 allow_replace || !path.exists(),
2217 "refusing to replace xAI OAuth generation"
2218 );
2219 crate::persistence::atomic_write(&path, bytes)
2220 }
2221
2222 pub fn remove_raw(&self, name: &str) -> Result<bool> {
2223 validate_private_basename(name)?;
2224 match fs::remove_file(self.directory.join(name)) {
2225 Ok(()) => Ok(true),
2226 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false),
2227 Err(error) => Err(error.into()),
2228 }
2229 }
2230
2231 pub fn rename_raw(&self, from: &str, to: &str) -> Result<()> {
2232 validate_private_basename(from)?;
2233 validate_private_basename(to)?;
2234 fs::rename(self.directory.join(from), self.directory.join(to))?;
2235 Ok(())
2236 }
2237 }
2238
2239 #[cfg(not(any(unix, windows)))]
2240 pub(crate) fn validate_owned_file_handle(
2241 file: &File,
2242 _path: &Path,
2243 _guard: PrivateGuard,
2244 ) -> Result<fs::Metadata> {
2245 let metadata = file.metadata()?;
2246 anyhow::ensure!(metadata.is_file(), "xAI OAuth path must be a regular file");
2247 Ok(metadata)
2248 }
2249
2250 /// Filesystem identity of an owned Unix socket below a retained private parent.
2251 #[cfg(unix)]
2252 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
2253 pub struct PrivateSocketIdentity {
2254 device: libc::dev_t,
2255 inode: libc::ino_t,
2256 }
2257
2258 #[cfg(unix)]
2259 impl PrivateDirectory {
2260 pub fn socket_identity(&self, name: &str) -> Result<Option<PrivateSocketIdentity>> {
2261 use std::os::fd::AsRawFd as _;
2262 validate_private_basename(name)?;
2263 let name = CString::new(name)?;
2264 let mut metadata = std::mem::MaybeUninit::<libc::stat>::uninit();
2265 // SAFETY: one basename below the retained directory; output is writable.
2266 if unsafe {
2267 libc::fstatat(
2268 self.directory_handle.as_raw_fd(),
2269 name.as_ptr(),
2270 metadata.as_mut_ptr(),
2271 libc::AT_SYMLINK_NOFOLLOW,
2272 )
2273 } != 0
2274 {
2275 let error = std::io::Error::last_os_error();
2276 if error.kind() == std::io::ErrorKind::NotFound {
2277 return Ok(None);
2278 }
2279 return Err(error.into());
2280 }
2281 // SAFETY: successful fstatat initialized the entire stat object.
2282 let metadata = unsafe { metadata.assume_init() };
2283 if metadata.st_mode & libc::S_IFMT != libc::S_IFSOCK {
2284 return Err(std::io::Error::new(
2285 std::io::ErrorKind::InvalidInput,
2286 "private endpoint exists and is not a socket",
2287 )
2288 .into());
2289 }
2290 // Ownership is evidence only where the mount stores it. The socket
2291 // type above and the identity this returns are stored properties, so
2292 // they still hold on a mount that reports an owner of its own.
2293 if matches!(self.guard, PrivateGuard::Required) {
2294 anyhow::ensure!(
2295 metadata.st_uid == Self::current_user_id(),
2296 "private socket is not owned by the current user"
2297 );
2298 }
2299 Ok(Some(PrivateSocketIdentity {
2300 device: metadata.st_dev,
2301 inode: metadata.st_ino,
2302 }))
2303 }
2304
2305 /// Never follows a substituted leaf to change another object's permissions.
2306 pub fn protect_socket(&self, name: &str, identity: PrivateSocketIdentity) -> Result<()> {
2307 use std::os::fd::AsRawFd as _;
2308 anyhow::ensure!(
2309 self.socket_identity(name)? == Some(identity),
2310 "private socket changed before protection"
2311 );
2312 let name_c = CString::new(name)?;
2313 // SAFETY: retained directory, one component; no-follow is mandatory.
2314 if unsafe {
2315 libc::fchmodat(
2316 self.directory_handle.as_raw_fd(),
2317 name_c.as_ptr(),
2318 0o600,
2319 libc::AT_SYMLINK_NOFOLLOW,
2320 )
2321 } != 0
2322 {
2323 return Err(std::io::Error::last_os_error())
2324 .context("protecting private socket without following links");
2325 }
2326 anyhow::ensure!(
2327 self.socket_identity(name)? == Some(identity),
2328 "private socket changed during protection"
2329 );
2330 Ok(())
2331 }
2332
2333 #[cfg(any(target_os = "macos", target_os = "linux", target_os = "android"))]
2334 fn move_no_replace(&self, from: &str, to: &str) -> Result<()> {
2335 use std::os::fd::AsRawFd as _;
2336 validate_private_basename(from)?;
2337 validate_private_basename(to)?;
2338 let from = CString::new(from)?;
2339 let to = CString::new(to)?;
2340 #[cfg(target_os = "macos")]
2341 // SAFETY: both basenames and retained descriptors remain valid; EXCL refuses replacement.
2342 let result = unsafe {
2343 libc::renameatx_np(
2344 self.directory_handle.as_raw_fd(),
2345 from.as_ptr(),
2346 self.directory_handle.as_raw_fd(),
2347 to.as_ptr(),
2348 libc::RENAME_EXCL,
2349 )
2350 };
2351 #[cfg(any(target_os = "linux", target_os = "android"))]
2352 // Use the kernel syscall because musl need not export a renameat2 wrapper.
2353 // SAFETY: same retained directory; NOREPLACE is required, never emulated by a check.
2354 let result = unsafe {
2355 libc::syscall(
2356 libc::SYS_renameat2,
2357 self.directory_handle.as_raw_fd(),
2358 from.as_ptr(),
2359 self.directory_handle.as_raw_fd(),
2360 to.as_ptr(),
2361 libc::RENAME_NOREPLACE,
2362 )
2363 };
2364 if result != 0 {
2365 return Err(std::io::Error::last_os_error())
2366 .context("moving private entry without replacement");
2367 }
2368 Ok(())
2369 }
2370
2371 #[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "android")))]
2372 fn move_no_replace(&self, _from: &str, _to: &str) -> Result<()> {
2373 bail!("exclusive endpoint retirement is unsupported on this platform")
2374 }
2375
2376 pub fn retire_socket(&self, name: &str, expected: PrivateSocketIdentity) -> Result<bool> {
2377 use std::os::fd::AsRawFd as _;
2378 if self.socket_identity(name)? != Some(expected) {
2379 return Ok(false);
2380 }
2381 static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
2382 let retired = format!(
2383 ".cw-endpoint-{}-{}-{}.retired",
2384 std::process::id(),
2385 SystemTime::now().duration_since(UNIX_EPOCH)?.as_nanos(),
2386 COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
2387 );
2388 self.move_no_replace(name, &retired)?;
2389 if self.socket_identity(&retired)? != Some(expected) {
2390 let restored = self.move_no_replace(&retired, name);
2391 return Err(anyhow::anyhow!(
2392 "endpoint identity changed; replacement preserved (restore: {restored:?})"
2393 ));
2394 }
2395 let retired_c = CString::new(retired)?;
2396 // SAFETY: the exclusively retired, matching socket is below the retained private parent.
2397 if unsafe { libc::unlinkat(self.directory_handle.as_raw_fd(), retired_c.as_ptr(), 0) } != 0
2398 {
2399 return Err(std::io::Error::last_os_error())
2400 .context("removing exact retired private socket");
2401 }
2402 self.directory_handle.sync_all()?;
2403 Ok(true)
2404 }
2405 }
2406
2407 #[cfg(all(test, unix))]
2408 mod tests {
2409 use super::*;
2410 use std::os::unix::fs::{PermissionsExt as _, symlink};
2411 use std::os::unix::net::UnixListener;
2412
2413 fn root() -> tempfile::TempDir {
2414 let selected = Path::new("/tmp").canonicalize().unwrap();
2415 tempfile::Builder::new()
2416 .prefix("cw-pd-")
2417 .tempdir_in(selected)
2418 .unwrap()
2419 }
2420
2421 #[test]
2422 fn private_footing_is_native_where_the_mount_stores_modes() {
2423 let root = root();
2424 assert_eq!(
2425 private_footing(&root.path().join("state")).unwrap(),
2426 PrivateFooting::Native,
2427 "a mount that keeps the mode it is given is native footing"
2428 );
2429 assert_eq!(
2430 fs::read_dir(root.path()).unwrap().count(),
2431 0,
2432 "the probe must remove itself"
2433 );
2434 }
2435
2436 /// The synthesised branch cannot be built on a filesystem that stores
2437 /// ownership and mode; the rule is pinned here instead. The observed values
2438 /// are the ones HarmonyOS hmdfs produces for an app-created `0o700`
2439 /// directory: the logged-in user's uid, and a group-writable mode.
2440 #[test]
2441 fn probe_footing_separates_a_native_mount_from_one_that_invents_ownership() {
2442 assert_eq!(
2443 classify_probe_footing(1000, 0o700, 1000),
2444 PrivateFooting::Native
2445 );
2446 assert_eq!(
2447 classify_probe_footing(1000, 0o500, 1000),
2448 PrivateFooting::Native
2449 );
2450 assert_eq!(
2451 classify_probe_footing(20001006, 0o2771, 20020225),
2452 PrivateFooting::Synthesised {
2453 observed_uid: 20001006,
2454 observed_mode: 0o2771
2455 },
2456 "hmdfs: a different uid and a group-writable mode for our own directory"
2457 );
2458 assert_eq!(
2459 classify_probe_footing(20020225, 0o2771, 20020225),
2460 PrivateFooting::Synthesised {
2461 observed_uid: 20020225,
2462 observed_mode: 0o2771
2463 },
2464 "the right owner with the wrong mode is still not a private directory"
2465 );
2466 assert_eq!(
2467 classify_probe_footing(0, 0o700, 1000),
2468 PrivateFooting::Synthesised {
2469 observed_uid: 0,
2470 observed_mode: 0o700
2471 },
2472 "a root-owned directory is not ours even when the mode looks right"
2473 );
2474 }
2475
2476 /// A mount that applied an unexpected mode at creation but honours the one
2477 /// it is asked for stores modes: it must not be reclassified as one that
2478 /// cannot express ownership, because that would relax a real guard. This is
2479 /// the difference between a default ACL and hmdfs.
2480 #[test]
2481 fn narrowing_rescues_a_mode_storing_mount_and_not_a_synthesising_one() {
2482 // A default ACL widened the new directory, and the mount then applied
2483 // the 0o700 it was asked for.
2484 assert_eq!(
2485 footing_from_observations((1000, 0o750), Some((1000, 0o700)), 1000),
2486 PrivateFooting::Native
2487 );
2488 // hmdfs refuses the request and keeps reporting its own values.
2489 assert_eq!(
2490 footing_from_observations((20001006, 0o2771), None, 20020225),
2491 PrivateFooting::Synthesised {
2492 observed_uid: 20001006,
2493 observed_mode: 0o2771
2494 }
2495 );
2496 // A mount that accepts the call but ignores it is still synthesising.
2497 assert_eq!(
2498 footing_from_observations((20001006, 0o2771), Some((20001006, 0o2771)), 20020225),
2499 PrivateFooting::Synthesised {
2500 observed_uid: 20001006,
2501 observed_mode: 0o2771
2502 }
2503 );
2504 // A mount that honours it and is owned by us holds the guard.
2505 assert_eq!(
2506 footing_from_observations((1000, 0o700), None, 1000),
2507 PrivateFooting::Native,
2508 "the first observation already proves a native mount"
2509 );
2510 }
2511
2512 /// The cached entry point is what the write paths call, so it must answer
2513 /// the same thing the probe does and leave nothing behind.
2514 #[test]
2515 fn cached_footing_answers_native_here_and_leaves_nothing_behind() {
2516 let root = root();
2517 assert_eq!(
2518 mount_footing(&root.path().join("state")),
2519 PrivateFooting::Native
2520 );
2521 assert_eq!(
2522 mount_footing(&root.path().join("state")),
2523 PrivateFooting::Native,
2524 "the cached answer is the same answer"
2525 );
2526 assert_eq!(
2527 fs::read_dir(root.path()).unwrap().count(),
2528 0,
2529 "no probe may survive either answer"
2530 );
2531 let handle = File::open(root.path()).unwrap();
2532 assert_eq!(mount_footing_of(&handle), PrivateFooting::Native);
2533 }
2534
2535 /// The trusting constructors exist for one reason: on a mount that reports
2536 /// its own ownership, the strict proof can never hold, and refusing would
2537 /// disable the feature for every app on that platform. On a filesystem that
2538 /// stores ownership they must behave exactly like the strict ones — this is
2539 /// the half a portable test can reach.
2540 #[test]
2541 fn trusting_constructors_keep_the_strict_guard_where_the_mount_stores_it() {
2542 let root = root();
2543 let selected = root.path().join("strict");
2544 fs::create_dir(&selected).unwrap();
2545 fs::set_permissions(&selected, fs::Permissions::from_mode(0o755)).unwrap();
2546 assert!(
2547 PrivateDirectory::admit_trusting_mount(&selected).is_err(),
2548 "a group-accessible directory is still refused on a native mount"
2549 );
2550
2551 let owned = root.path().join("owned");
2552 let private = PrivateDirectory::admit_trusting_mount(&owned).unwrap();
2553 assert_eq!(
2554 private.guard(),
2555 PrivateGuard::Required,
2556 "a native mount keeps the full guard"
2557 );
2558 private
2559 .write_owned_file("owner.json", b"{}", false)
2560 .unwrap();
2561 assert_eq!(
2562 private
2563 .read_private_receipt("owner.json", 64)
2564 .unwrap()
2565 .unwrap()
2566 .0,
2567 b"{}"
2568 );
2569 }
2570
2571 /// A linked component is refused on every mount: the no-follow walk is not
2572 /// the part a synthesising filesystem cannot express.
2573 #[test]
2574 fn trusting_constructors_still_refuse_a_linked_component() {
2575 let root = root();
2576 let original = root.path().join("original");
2577 fs::create_dir(&original).unwrap();
2578 symlink(&original, root.path().join("alias")).unwrap();
2579 assert!(PrivateDirectory::admit_trusting_mount(&root.path().join("alias")).is_err());
2580 }
2581
2582 #[test]
2583 fn a_probe_that_cannot_run_is_an_error_not_a_mount_limitation() {
2584 if PrivateDirectory::current_user_id() == 0 {
2585 // Root ignores the mode this test relies on.
2586 return;
2587 }
2588 let root = root();
2589 let blocked = root.path().join("blocked");
2590 fs::create_dir(&blocked).unwrap();
2591 fs::set_permissions(&blocked, fs::Permissions::from_mode(0o500)).unwrap();
2592 let result = private_footing(&blocked.join("state"));
2593 fs::set_permissions(&blocked, fs::Permissions::from_mode(0o700)).unwrap();
2594 assert!(
2595 result.is_err(),
2596 "a directory this process cannot write to keeps the strict refusal instead of \
2597 being reclassified as a mount that synthesises ownership"
2598 );
2599 }
2600
2601 #[test]
2602 fn owner_receipt_read_is_bounded_and_refuses_links_or_public_permissions() {
2603 let root = root();
2604 let parent = PrivateDirectory::admit(&root.path().join("run")).unwrap();
2605 parent
2606 .write_owned_file("owner.json", b"12345678", false)
2607 .unwrap();
2608 assert!(parent.read_private_receipt("owner.json", 7).is_err());
2609 assert_eq!(
2610 parent
2611 .read_private_receipt("owner.json", 8)
2612 .unwrap()
2613 .unwrap()
2614 .0,
2615 b"12345678"
2616 );
2617 let path = parent.directory.join("owner.json");
2618 fs::hard_link(&path, parent.directory.join("linked.json")).unwrap();
2619 assert!(parent.read_private_receipt("owner.json", 8).is_err());
2620 fs::remove_file(parent.directory.join("linked.json")).unwrap();
2621 fs::set_permissions(&path, fs::Permissions::from_mode(0o644)).unwrap();
2622 assert!(parent.read_private_receipt("owner.json", 8).is_err());
2623 fs::set_permissions(&path, fs::Permissions::from_mode(0o600)).unwrap();
2624 symlink(&path, parent.directory.join("alias.json")).unwrap();
2625 assert!(parent.read_private_receipt("alias.json", 8).is_err());
2626 }
2627
2628 #[test]
2629 fn owner_receipt_opened_before_retirement_is_rejected_as_unlinked_not_hardlinked() {
2630 let root = root();
2631 let parent = PrivateDirectory::admit(&root.path().join("run")).unwrap();
2632 parent
2633 .write_owned_file("owner.json", b"receipt", false)
2634 .unwrap();
2635 let file = parent
2636 .open_owned_file_for_read("owner.json")
2637 .unwrap()
2638 .unwrap();
2639 assert!(parent.remove_raw("owner.json").unwrap());
2640 let error = parent
2641 .read_private_receipt_file("owner.json", 8, file)
2642 .unwrap_err();
2643 assert!(error.is::<UnlinkedPrivateFile>());
2644
2645 parent
2646 .write_owned_file("owner.json", b"receipt", false)
2647 .unwrap();
2648 fs::hard_link(
2649 parent.directory.join("owner.json"),
2650 parent.directory.join("alias.json"),
2651 )
2652 .unwrap();
2653 let error = parent.read_private_receipt("owner.json", 8).unwrap_err();
2654 assert!(
2655 !error.is::<UnlinkedPrivateFile>(),
2656 "a linked receipt must remain unsafe, not retryable"
2657 );
2658 }
2659
2660 #[cfg(any(target_os = "macos", target_os = "linux"))]
2661 #[test]
2662 fn private_exclusive_publication_keeps_one_link_and_preserves_existing_destination() {
2663 use std::os::unix::fs::MetadataExt as _;
2664 let root = root();
2665 let parent = PrivateDirectory::admit(&root.path().join("run")).unwrap();
2666 let mut staging = parent.open_internal_file("staging").unwrap();
2667 staging.write_all(b"receipt").unwrap();
2668 staging.sync_all().unwrap();
2669 parent.move_no_replace("staging", "owner.json").unwrap();
2670 assert_eq!(staging.metadata().unwrap().nlink(), 1);
2671 assert!(
2672 parent
2673 .open_owned_file_for_read("staging")
2674 .unwrap()
2675 .is_none()
2676 );
2677 assert!(
2678 parent
2679 .write_owned_file("owner.json", b"replacement", false)
2680 .is_err()
2681 );
2682 assert_eq!(
2683 parent
2684 .read_private_receipt("owner.json", 8)
2685 .unwrap()
2686 .unwrap()
2687 .0,
2688 b"receipt"
2689 );
2690 assert_eq!(
2691 fs::read_dir(&parent.directory).unwrap().count(),
2692 1,
2693 "failed publication must clean only its own staging file"
2694 );
2695 }
2696
2697 #[cfg(any(target_os = "macos", target_os = "linux"))]
2698 #[test]
2699 fn owner_receipt_retirement_preserves_a_replacement_and_uses_captured_file() {
2700 let root = root();
2701 let parent = PrivateDirectory::admit(&root.path().join("run")).unwrap();
2702 parent
2703 .write_owned_file("owner.json", b"captured", false)
2704 .unwrap();
2705 let (_, captured) = parent
2706 .read_private_receipt("owner.json", 8)
2707 .unwrap()
2708 .unwrap();
2709 fs::rename(
2710 parent.directory.join("owner.json"),
2711 parent.directory.join("old.json"),
2712 )
2713 .unwrap();
2714 parent
2715 .write_owned_file("owner.json", b"replaced", false)
2716 .unwrap();
2717 assert!(
2718 !parent
2719 .retire_private_receipt("owner.json", &captured)
2720 .unwrap()
2721 );
2722 assert_eq!(
2723 parent
2724 .read_private_receipt("owner.json", 8)
2725 .unwrap()
2726 .unwrap()
2727 .0,
2728 b"replaced"
2729 );
2730 assert!(
2731 parent
2732 .retire_private_receipt("old.json", &captured)
2733 .unwrap()
2734 );
2735 assert!(
2736 parent
2737 .read_private_receipt("old.json", 8)
2738 .unwrap()
2739 .is_none()
2740 );
2741 }
2742
2743 #[cfg(any(target_os = "macos", target_os = "linux"))]
2744 #[test]
2745 fn local_process_generation_is_kernel_bound_and_refuses_invalid_pid() {
2746 let first = unix_process_start(std::process::id()).unwrap();
2747 assert!(!first.is_empty());
2748 assert_eq!(unix_process_start(std::process::id()).unwrap(), first);
2749 assert!(unix_process_start(0).is_err());
2750 assert!(unix_process_start(u32::MAX).is_err());
2751 }
2752
2753 #[cfg(any(target_os = "macos", target_os = "linux"))]
2754 #[test]
2755 fn unix_process_status_requires_positive_kernel_absence() {
2756 assert_eq!(
2757 unix_process_status(std::process::id()).unwrap(),
2758 UnixProcessStatus::Present {
2759 start: unix_process_start(std::process::id()).unwrap()
2760 }
2761 );
2762 let mut child = std::process::Command::new("/bin/sh")
2763 .args(["-c", "exit 0"])
2764 .spawn()
2765 .unwrap();
2766 let pid = child.id();
2767 child.wait().unwrap();
2768 assert_eq!(unix_process_status(pid).unwrap(), UnixProcessStatus::Absent);
2769 assert!(unix_process_status(0).is_err());
2770 assert!(unix_process_status(u32::MAX).is_err());
2771 }
2772
2773 #[cfg(unix)]
2774 #[test]
2775 fn unix_process_status_never_converts_uncertainty_to_death() {
2776 assert!(unix_pid_is_absent(
2777 -1,
2778 &std::io::Error::from_raw_os_error(libc::ESRCH)
2779 ));
2780 for code in [libc::EPERM, libc::EACCES, libc::EINVAL] {
2781 assert!(!unix_pid_is_absent(
2782 -1,
2783 &std::io::Error::from_raw_os_error(code)
2784 ));
2785 }
2786 assert!(!unix_pid_is_absent(
2787 0,
2788 &std::io::Error::from_raw_os_error(libc::ESRCH)
2789 ));
2790 }
2791
2792 #[cfg(target_os = "linux")]
2793 #[test]
2794 fn linux_process_generation_survives_nondumpable_hardening() {
2795 const CHILD: &str = "CODEWHALE_PROCESS_IDENTITY_TEST_CHILD";
2796 if std::env::var_os(CHILD).is_some() {
2797 let pid = std::process::id();
2798 let before = unix_process_start(pid).unwrap();
2799 // SAFETY: changes only this isolated child test process.
2800 assert_eq!(unsafe { libc::prctl(libc::PR_SET_DUMPABLE, 0, 0, 0, 0) }, 0);
2801 // SAFETY: queries only the calling process with no pointer arguments.
2802 assert_eq!(unsafe { libc::prctl(libc::PR_GET_DUMPABLE, 0, 0, 0, 0) }, 0);
2803 if PrivateDirectory::current_user_id() != 0 {
2804 use std::os::unix::fs::MetadataExt as _;
2805 assert_eq!(fs::metadata(format!("/proc/{pid}/stat")).unwrap().uid(), 0);
2806 }
2807 assert_eq!(unix_process_start(pid).unwrap(), before);
2808 assert!(unix_process_start(0).is_err());
2809 assert!(unix_process_start(u32::MAX).is_err());
2810 println!("HARDENED_PROCESS_GENERATION_VERIFIED");
2811 return;
2812 }
2813 let output = std::process::Command::new(std::env::current_exe().unwrap())
2814 .args([
2815 "private_directory::tests::linux_process_generation_survives_nondumpable_hardening",
2816 "--exact",
2817 "--nocapture",
2818 ])
2819 .env_clear()
2820 .env(CHILD, "1")
2821 .output()
2822 .unwrap();
2823 assert!(
2824 output.status.success(),
2825 "isolated hardened process failed: {}",
2826 String::from_utf8_lossy(&output.stderr)
2827 );
2828 assert!(
2829 String::from_utf8_lossy(&output.stdout)
2830 .contains("HARDENED_PROCESS_GENERATION_VERIFIED")
2831 );
2832 }
2833
2834 #[cfg(target_os = "linux")]
2835 #[test]
2836 fn linux_process_status_refuses_foreign_or_malformed_principals() {
2837 let valid = "Name:\tfixture\nPid:\t42\nUid:\t100\t101\t102\t103\n";
2838 assert!(validate_linux_process_status(valid, 42, 101).is_ok());
2839 assert!(validate_linux_process_status(valid, 42, 100).is_err());
2840 assert!(validate_linux_process_status(valid, 43, 101).is_err());
2841 for status in [
2842 "Uid:\t100 101 102 103\n",
2843 "Pid:\t42\n",
2844 "Pid:\t42\nUid:\t100 101 102\n",
2845 "Pid:\t42\nUid:\t100 101 102 103 104\n",
2846 "Pid:\t42\nUid:\t100 invalid 102 103\n",
2847 "Pid:\t42\nPid:\t42\nUid:\t100 101 102 103\n",
2848 "Pid:\t42\nUid:\t100 101 102 103\nUid:\t100 101 102 103\n",
2849 ] {
2850 assert!(validate_linux_process_status(status, 42, 101).is_err());
2851 }
2852 }
2853
2854 #[test]
2855 fn endpoint_admission_refuses_public_existing_directory_without_repair() {
2856 let root = root();
2857 let selected = root.path().join("public");
2858 fs::create_dir(&selected).unwrap();
2859 fs::set_permissions(&selected, fs::Permissions::from_mode(0o755)).unwrap();
2860 assert!(PrivateDirectory::admit(&selected).is_err());
2861 assert_eq!(
2862 fs::metadata(&selected).unwrap().permissions().mode() & 0o777,
2863 0o755
2864 );
2865 #[cfg(target_os = "linux")]
2866 fs::set_permissions(root.path(), fs::Permissions::from_mode(0o111)).unwrap();
2867 let credentials = PrivateDirectory::open(&selected);
2868 #[cfg(target_os = "linux")]
2869 fs::set_permissions(root.path(), fs::Permissions::from_mode(0o700)).unwrap();
2870 let credentials = credentials.unwrap();
2871 assert_eq!(
2872 credentials
2873 .directory_handle
2874 .metadata()
2875 .unwrap()
2876 .permissions()
2877 .mode()
2878 & 0o777,
2879 0o700
2880 );
2881 }
2882
2883 #[test]
2884 fn endpoint_admission_refuses_linked_component_and_changed_selected_parent() {
2885 let root = root();
2886 let original = root.path().join("original");
2887 let held = PrivateDirectory::admit(&original).unwrap();
2888 symlink(&original, root.path().join("alias")).unwrap();
2889 assert!(PrivateDirectory::admit(&root.path().join("alias")).is_err());
2890 fs::rename(&original, root.path().join("retained")).unwrap();
2891 PrivateDirectory::admit(&original).unwrap();
2892 assert!(!held.is_at_selected_path().unwrap());
2893 }
2894
2895 #[cfg(any(target_os = "macos", target_os = "linux"))]
2896 #[test]
2897 fn exact_endpoint_retirement_preserves_replacement_and_removes_captured_socket() {
2898 let root = root();
2899 let parent = PrivateDirectory::admit(&root.path().join("run")).unwrap();
2900 let path = parent.directory.join("owner.sock");
2901 let original = UnixListener::bind(&path).unwrap();
2902 let identity = parent.socket_identity("owner.sock").unwrap().unwrap();
2903 fs::rename(&path, parent.directory.join("old.sock")).unwrap();
2904 let replacement = UnixListener::bind(&path).unwrap();
2905 assert!(!parent.retire_socket("owner.sock", identity).unwrap());
2906 assert!(path.exists());
2907 assert_eq!(parent.socket_identity("old.sock").unwrap(), Some(identity));
2908 assert!(parent.retire_socket("old.sock", identity).unwrap());
2909 assert!(!parent.directory.join("old.sock").exists());
2910 assert!(path.exists());
2911 drop((original, replacement));
2912 }
2913
2914 #[cfg(any(target_os = "macos", target_os = "linux"))]
2915 #[test]
2916 fn endpoint_move_refuses_to_replace_existing_socket() {
2917 let root = root();
2918 let parent = PrivateDirectory::admit(&root.path().join("run")).unwrap();
2919 let original = UnixListener::bind(parent.directory.join("owner.sock")).unwrap();
2920 let destination = UnixListener::bind(parent.directory.join("retired.sock")).unwrap();
2921 let original_identity = parent.socket_identity("owner.sock").unwrap().unwrap();
2922 let destination_identity = parent.socket_identity("retired.sock").unwrap().unwrap();
2923
2924 let error = parent
2925 .move_no_replace("owner.sock", "retired.sock")
2926 .unwrap_err();
2927 assert_eq!(
2928 error.downcast_ref::<std::io::Error>().unwrap().kind(),
2929 std::io::ErrorKind::AlreadyExists
2930 );
2931 assert_eq!(
2932 parent.socket_identity("owner.sock").unwrap(),
2933 Some(original_identity)
2934 );
2935 assert_eq!(
2936 parent.socket_identity("retired.sock").unwrap(),
2937 Some(destination_identity)
2938 );
2939 drop((original, destination));
2940 }
2941
2942 #[test]
2943 fn endpoint_leaf_symlink_is_never_followed_for_protection_or_retirement() {
2944 let root = root();
2945 let parent = PrivateDirectory::admit(&root.path().join("run")).unwrap();
2946 let path = parent.directory.join("owner.sock");
2947 let original = UnixListener::bind(&path).unwrap();
2948 let identity = parent.socket_identity("owner.sock").unwrap().unwrap();
2949 fs::remove_file(&path).unwrap();
2950 let other = root.path().join("operator-file");
2951 fs::write(&other, b"preserve").unwrap();
2952 fs::set_permissions(&other, fs::Permissions::from_mode(0o644)).unwrap();
2953 symlink(&other, &path).unwrap();
2954 assert!(parent.protect_socket("owner.sock", identity).is_err());
2955 assert!(parent.retire_socket("owner.sock", identity).is_err());
2956 assert_eq!(fs::read(&other).unwrap(), b"preserve");
2957 assert_eq!(
2958 fs::metadata(&other).unwrap().permissions().mode() & 0o777,
2959 0o644
2960 );
2961 assert!(
2962 fs::symlink_metadata(&path)
2963 .unwrap()
2964 .file_type()
2965 .is_symlink()
2966 );
2967 drop(original);
2968 }
2969 }
2970
2971 /// A current-user process identity or positive kernel absence. Query failures
2972 /// remain errors; an unreadable process record never establishes death.
2973 #[cfg(unix)]
2974 #[derive(Debug, PartialEq, Eq)]
2975 pub enum UnixProcessStatus {
2976 Present { start: String },
2977 Absent,
2978 }
2979
2980 #[cfg(unix)]
2981 fn unix_pid_is_absent(result: i32, error: &std::io::Error) -> bool {
2982 result == -1 && error.raw_os_error() == Some(libc::ESRCH)
2983 }
2984
2985 /// Read on the existing bounded owner worker. Signal zero never terminates a
2986 /// process; only ESRCH after validating a positive PID proves absence.
2987 #[cfg(unix)]
2988 pub fn unix_process_status(pid: u32) -> Result<UnixProcessStatus> {
2989 let kernel_pid = i32::try_from(pid).context("invalid local process PID")?;
2990 anyhow::ensure!(kernel_pid > 0, "invalid local process PID");
2991 match unix_process_start(pid) {
2992 Ok(start) => Ok(UnixProcessStatus::Present { start }),
2993 Err(identity_error) => {
2994 // SAFETY: a validated positive PID and signal zero only query
2995 // existence. No process-group selection or signal is possible.
2996 let result = unsafe { libc::kill(kernel_pid, 0) };
2997 let error = std::io::Error::last_os_error();
2998 if unix_pid_is_absent(result, &error) {
2999 Ok(UnixProcessStatus::Absent)
3000 } else {
3001 Err(identity_error).context("selected process identity/liveness is uncertain")
3002 }
3003 }
3004 }
3005 }
3006
3007 /// Kernel process creation identity for the authenticated local Unix peer.
3008 /// Run on the existing bounded owner worker; PID alone is never sufficient.
3009 #[cfg(unix)]
3010 pub fn unix_process_start(pid: u32) -> Result<String> {
3011 anyhow::ensure!(pid > 0, "invalid local process PID");
3012 #[cfg(target_os = "macos")]
3013 {
3014 let mut info = std::mem::MaybeUninit::<libc::proc_bsdinfo>::uninit();
3015 let size = std::mem::size_of::<libc::proc_bsdinfo>();
3016 // SAFETY: kernel writes the initialized fixed-size BSD process buffer.
3017 let read = unsafe {
3018 libc::proc_pidinfo(
3019 i32::try_from(pid)?,
3020 libc::PROC_PIDTBSDINFO,
3021 0,
3022 info.as_mut_ptr().cast(),
3023 i32::try_from(size)?,
3024 )
3025 };
3026 anyhow::ensure!(
3027 usize::try_from(read).ok() == Some(size),
3028 "local process creation identity unavailable"
3029 );
3030 // SAFETY: exact-size successful kernel query initialized the buffer.
3031 let info = unsafe { info.assume_init() };
3032 anyhow::ensure!(
3033 info.pbi_pid == pid && info.pbi_uid == PrivateDirectory::current_user_id(),
3034 "local process principal changed"
3035 );
3036 Ok(format!(
3037 "macos:{}:{}",
3038 info.pbi_start_tvsec, info.pbi_start_tvusec
3039 ))
3040 }
3041 #[cfg(any(target_os = "linux", target_os = "android"))]
3042 {
3043 use std::io::Read as _;
3044 use std::os::fd::{AsRawFd as _, FromRawFd as _};
3045 use std::os::unix::fs::OpenOptionsExt as _;
3046
3047 // Keep stat and credentials on one kernel process object. A retained
3048 // proc directory cannot be redirected to a reused PID after exit.
3049 let directory = fs::OpenOptions::new()
3050 .read(true)
3051 .custom_flags(libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC)
3052 .open(format!("/proc/{pid}"))?;
3053 let mut filesystem = std::mem::MaybeUninit::<libc::statfs>::uninit();
3054 // SAFETY: the live directory descriptor and output buffer are valid.
3055 let result = unsafe { libc::fstatfs(directory.as_raw_fd(), filesystem.as_mut_ptr()) };
3056 if result != 0 {
3057 return Err(std::io::Error::last_os_error())
3058 .context("inspecting kernel process directory");
3059 }
3060 // SAFETY: successful fstatfs initialized the output buffer.
3061 anyhow::ensure!(
3062 i128::from(unsafe { filesystem.assume_init() }.f_type)
3063 == i128::from(libc::PROC_SUPER_MAGIC),
3064 "local process identity is not on procfs"
3065 );
3066 let open = |name: &std::ffi::CStr| -> Result<File> {
3067 // SAFETY: the retained directory and constant basename remain valid.
3068 let fd = unsafe {
3069 libc::openat(
3070 directory.as_raw_fd(),
3071 name.as_ptr(),
3072 libc::O_RDONLY | libc::O_CLOEXEC | libc::O_NOFOLLOW,
3073 )
3074 };
3075 if fd < 0 {
3076 return Err(std::io::Error::last_os_error())
3077 .context("opening kernel process identity");
3078 }
3079 // SAFETY: openat returned a newly owned descriptor.
3080 Ok(unsafe { File::from_raw_fd(fd) })
3081 };
3082 let mut bytes = Vec::new();
3083 open(c"stat")?.take(8193).read_to_end(&mut bytes)?;
3084 anyhow::ensure!(bytes.len() <= 8192, "oversized kernel process identity");
3085 let stat = std::str::from_utf8(&bytes)?;
3086 anyhow::ensure!(
3087 stat.split_once(' ')
3088 .is_some_and(|(actual, _)| actual.parse::<u32>().ok() == Some(pid)),
3089 "kernel process PID changed"
3090 );
3091 let end = stat.rfind(')').context("invalid kernel process identity")?;
3092 let start = stat[end + 1..]
3093 .split_whitespace()
3094 .nth(19)
3095 .context("kernel process start field unavailable")?
3096 .parse::<u64>()?;
3097 // PR_SET_DUMPABLE=0 makes proc inode ownership root even for a local
3098 // user's process. Authenticate the effective UID in the kernel status
3099 // header instead; do not disable hardening or trust the inode owner.
3100 // Pid/Uid precede potentially large supplementary-group lists.
3101 let mut status = String::new();
3102 open(c"status")?.take(8192).read_to_string(&mut status)?;
3103 validate_linux_process_status(&status, pid, PrivateDirectory::current_user_id())?;
3104 Ok(format!("linux:{}:{start}", linux_boot_id()?))
3105 }
3106 #[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "android")))]
3107 bail!("local process generation authentication unsupported on this platform")
3108 }
3109
3110 #[cfg(any(target_os = "linux", target_os = "android"))]
3111 fn linux_boot_id() -> Result<String> {
3112 use std::io::Read as _;
3113 let mut boot = String::new();
3114 File::open("/proc/sys/kernel/random/boot_id")?
3115 .take(65)
3116 .read_to_string(&mut boot)?;
3117 let boot = boot.trim();
3118 anyhow::ensure!(
3119 boot.len() == 36 && boot.bytes().all(|b| b.is_ascii_hexdigit() || b == b'-'),
3120 "kernel boot identity unavailable"
3121 );
3122 Ok(boot.to_string())
3123 }
3124
3125 #[cfg(any(target_os = "linux", target_os = "android"))]
3126 pub fn linux_process_start_predates_boot(recorded: &str) -> Result<bool> {
3127 let recorded_boot = recorded
3128 .strip_prefix("linux:")
3129 .and_then(|rest| rest.split_once(':'))
3130 .map(|(boot, _)| boot)
3131 .context("invalid recorded Linux process identity")?;
3132 Ok(recorded_boot != linux_boot_id()?)
3133 }
3134
3135 #[cfg(any(target_os = "linux", target_os = "android"))]
3136 fn validate_linux_process_status(status: &str, pid: u32, uid: u32) -> Result<()> {
3137 let mut actual_pid = None;
3138 let mut actual_uid = None;
3139 for line in status.lines() {
3140 if let Some(value) = line.strip_prefix("Pid:") {
3141 anyhow::ensure!(actual_pid.is_none(), "duplicate kernel process PID");
3142 actual_pid = Some(value.trim().parse::<u32>()?);
3143 } else if let Some(value) = line.strip_prefix("Uid:") {
3144 anyhow::ensure!(actual_uid.is_none(), "duplicate kernel process credentials");
3145 let values = value
3146 .split_whitespace()
3147 .map(str::parse::<u32>)
3148 .collect::<std::result::Result<Vec<_>, _>>()?;
3149 anyhow::ensure!(values.len() == 4, "invalid kernel process credentials");
3150 actual_uid = Some(values[1]);
3151 }
3152 }
3153 anyhow::ensure!(actual_pid == Some(pid), "kernel process PID changed");
3154 anyhow::ensure!(actual_uid == Some(uid), "local process principal changed");
3155 Ok(())
3156 }
3157
3158 #[cfg(unix)]
3159 impl PrivateDirectory {
3160 /// The same anchored owned-file opener used by credentials, with a bounded
3161 /// read and retained object for exact receipt retirement.
3162 pub fn read_private_receipt(&self, name: &str, max: usize) -> Result<Option<(Vec<u8>, File)>> {
3163 let Some(file) = self.open_at(name, libc::O_RDONLY | libc::O_NONBLOCK, 0)? else {
3164 return Ok(None);
3165 };
3166 self.read_private_receipt_file(name, max, file).map(Some)
3167 }
3168
3169 fn read_private_receipt_file(
3170 &self,
3171 name: &str,
3172 max: usize,
3173 mut file: File,
3174 ) -> Result<(Vec<u8>, File)> {
3175 use std::io::Read as _;
3176 use std::os::unix::fs::MetadataExt as _;
3177 let before = validate_owned_file_handle(&file, &self.directory.join(name), self.guard)?;
3178 // The mode is evidence only where the mount stores it; on a mount that
3179 // invents one it is always wider than 0o600 and proves nothing. The
3180 // size bound is a stored property and always applies.
3181 let mode_private =
3182 !matches!(self.guard, PrivateGuard::Required) || before.mode() & 0o077 == 0;
3183 anyhow::ensure!(
3184 mode_private && before.len() <= u64::try_from(max)?,
3185 "private owner receipt permissions or size refused"
3186 );
3187 let mut bytes = Vec::new();
3188 (&mut file)
3189 .take(
3190 u64::try_from(max)?
3191 .checked_add(1)
3192 .context("receipt limit overflow")?,
3193 )
3194 .read_to_end(&mut bytes)?;
3195 let after = validate_owned_file_handle(&file, &self.directory.join(name), self.guard)?;
3196 anyhow::ensure!(
3197 bytes.len() <= max
3198 && u64::try_from(bytes.len())? == before.len()
3199 && before.len() == after.len()
3200 && before.mtime() == after.mtime()
3201 && before.mtime_nsec() == after.mtime_nsec(),
3202 "private owner receipt changed while reading"
3203 );
3204 Ok((bytes, file))
3205 }
3206
3207 pub fn retire_private_receipt(&self, name: &str, captured: &File) -> Result<bool> {
3208 use std::os::unix::fs::MetadataExt as _;
3209 let expected =
3210 validate_owned_file_handle(captured, &self.directory.join(name), self.guard)?;
3211 let Some(named) = self.open_owned_file_for_read(name)? else {
3212 return Ok(false);
3213 };
3214 let actual = validate_owned_file_handle(&named, &self.directory.join(name), self.guard)?;
3215 if (expected.dev(), expected.ino()) != (actual.dev(), actual.ino()) {
3216 return Ok(false);
3217 }
3218 let retired = format!(
3219 ".cw-owner-{}-{}.retired",
3220 std::process::id(),
3221 SystemTime::now().duration_since(UNIX_EPOCH)?.as_nanos()
3222 );
3223 self.move_no_replace(name, &retired)?;
3224 let Some(moved) = self.open_owned_file_for_read(&retired)? else {
3225 bail!("private receipt retirement is uncertain")
3226 };
3227 let moved_metadata =
3228 validate_owned_file_handle(&moved, &self.directory.join(&retired), self.guard)?;
3229 if (expected.dev(), expected.ino()) != (moved_metadata.dev(), moved_metadata.ino()) {
3230 let restored = self.move_no_replace(&retired, name);
3231 bail!("private receipt changed; retaining replacement (restore: {restored:?})");
3232 }
3233 self.remove_raw(&retired)?;
3234 self.directory_handle.sync_all()?;
3235 Ok(true)
3236 }
3237 }
3238
3239 #[cfg(windows)]
3240 impl PrivateDirectory {
3241 pub fn is_at_selected_path(&self) -> Result<bool> {
3242 let current = Self::inspect(&self.directory)?;
3243 let held = self
3244 ._component_handles
3245 .last()
3246 .context("private directory handle unavailable")?;
3247 let now = current
3248 ._component_handles
3249 .last()
3250 .context("private directory handle unavailable")?;
3251 validate_windows_handle_path(held, &self.directory, true)?;
3252 Ok(windows_file_identity(held)? == windows_file_identity(now)?)
3253 }
3254 pub fn read_private_receipt(&self, name: &str, max: usize) -> Result<Option<(Vec<u8>, File)>> {
3255 use std::io::Read as _;
3256 use std::os::windows::fs::{MetadataExt as _, OpenOptionsExt as _};
3257 use windows_sys::Win32::Storage::FileSystem::{
3258 DELETE, FILE_FLAG_OPEN_REPARSE_POINT, FILE_GENERIC_READ, FILE_SHARE_DELETE,
3259 FILE_SHARE_READ, FILE_SHARE_WRITE,
3260 };
3261 validate_private_basename(name)?;
3262 let path = self.directory.join(name);
3263 let file = match fs::OpenOptions::new()
3264 .access_mode(FILE_GENERIC_READ | DELETE)
3265 .share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE)
3266 .custom_flags(FILE_FLAG_OPEN_REPARSE_POINT)
3267 .open(&path)
3268 {
3269 Ok(file) => file,
3270 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
3271 Err(error) => return Err(error).context("opening private owner receipt"),
3272 };
3273 let before = validate_windows_owned_file_handle(&file, &path)?;
3274 anyhow::ensure!(
3275 before.len() <= max as u64,
3276 "private owner receipt exceeds bound"
3277 );
3278 let mut bytes = Vec::new();
3279 (&file).take(max as u64 + 1).read_to_end(&mut bytes)?;
3280 let after = validate_windows_owned_file_handle(&file, &path)?;
3281 anyhow::ensure!(
3282 bytes.len() as u64 == before.len()
3283 && before.len() == after.len()
3284 && before.last_write_time() == after.last_write_time(),
3285 "private owner receipt changed during bounded read"
3286 );
3287 Ok(Some((bytes, file)))
3288 }
3289 pub fn retire_private_receipt(&self, name: &str, captured: &File) -> Result<bool> {
3290 let Some((_, current)) = self.read_private_receipt(name, 16384)? else {
3291 return Ok(false);
3292 };
3293 if !Self::same_file_identity(captured, &current)? {
3294 return Ok(false);
3295 }
3296 anyhow::ensure!(
3297 self.is_at_selected_path()?,
3298 "private owner parent changed before retirement"
3299 );
3300 validate_windows_owned_file_handle(captured, &self.directory.join(name))?;
3301 // Exact retained handle deletion cannot unlink a substituted pathname.
3302 mark_windows_file_handle_for_deletion(captured)?;
3303 Ok(true)
3304 }
3305 }
3306
3307 #[cfg(windows)]
3308 fn windows_file_identity(file: &File) -> Result<(u32, u32, u32)> {
3309 use std::os::windows::io::AsRawHandle as _;
3310 use windows_sys::Win32::Storage::FileSystem::{
3311 BY_HANDLE_FILE_INFORMATION, GetFileInformationByHandle,
3312 };
3313 let mut info = BY_HANDLE_FILE_INFORMATION::default();
3314 anyhow::ensure!(
3315 unsafe { GetFileInformationByHandle(file.as_raw_handle(), &mut info) } != 0,
3316 "private file identity unavailable"
3317 );
3318 Ok((
3319 info.dwVolumeSerialNumber,
3320 info.nFileIndexHigh,
3321 info.nFileIndexLow,
3322 ))
3323 }
3324
3325 impl PrivateDirectory {
3326 pub fn same_file_identity(left: &File, right: &File) -> Result<bool> {
3327 #[cfg(unix)]
3328 {
3329 use std::os::unix::fs::MetadataExt as _;
3330 let a = left.metadata()?;
3331 let b = right.metadata()?;
3332 Ok(a.dev() == b.dev() && a.ino() == b.ino())
3333 }
3334 #[cfg(windows)]
3335 {
3336 Ok(windows_file_identity(left)? == windows_file_identity(right)?)
3337 }
3338 #[cfg(not(any(unix, windows)))]
3339 bail!("private file identity unsupported on this platform")
3340 }
3341 }
3342
3342 lines RUST