Skip to main content

node_auth/
fs.rs

1//! Path resolution and isolated, atomic configuration-file replacement.
2
3use crate::AuthError;
4use std::collections::BTreeMap;
5#[cfg(unix)]
6use std::fs::File;
7use std::fs::{self, Permissions};
8use std::io::Write;
9use std::path::{Path, PathBuf};
10use tempfile::{Builder, NamedTempFile};
11
12#[cfg(unix)]
13mod platform_lock {
14  use std::fs::File;
15  use std::io;
16  use std::path::Path;
17
18  pub(super) struct Lock {
19    _file: File,
20  }
21
22  impl Lock {
23    pub(super) fn acquire(directory: &Path) -> io::Result<Self> {
24      let file = File::open(directory)?;
25      file.lock()?;
26      Ok(Self { _file: file })
27    }
28  }
29}
30
31#[cfg(windows)]
32mod platform_lock {
33  use std::io;
34  use std::iter;
35  use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle, RawHandle};
36  use std::path::Path;
37
38  use windows_sys::Win32::Foundation::{WAIT_ABANDONED, WAIT_OBJECT_0};
39  use windows_sys::Win32::System::Threading::{
40    CreateMutexW, INFINITE, ReleaseMutex, WaitForSingleObject,
41  };
42
43  pub(super) struct Lock(OwnedHandle);
44
45  impl Lock {
46    pub(super) fn acquire(directory: &Path) -> io::Result<Self> {
47      // Use a stable, case-insensitive hash so every node-auth process in
48      // this login session addresses the same kernel object.
49      let mut hash = 0xcbf29ce484222325_u64;
50      for unit in directory
51        .as_os_str()
52        .to_string_lossy()
53        .to_lowercase()
54        .encode_utf16()
55      {
56        hash ^= u64::from(unit);
57        hash = hash.wrapping_mul(0x100000001b3);
58      }
59      let name = format!("Local\\node-auth-directory-{hash:016x}")
60        .encode_utf16()
61        .chain(iter::once(0))
62        .collect::<Vec<_>>();
63      let handle = unsafe { CreateMutexW(std::ptr::null(), 0, name.as_ptr()) };
64      if handle.is_null() {
65        return Err(io::Error::last_os_error());
66      }
67      let handle = unsafe { OwnedHandle::from_raw_handle(handle as RawHandle) };
68      match unsafe { WaitForSingleObject(handle.as_raw_handle() as _, INFINITE) } {
69        WAIT_OBJECT_0 | WAIT_ABANDONED => Ok(Self(handle)),
70        _ => Err(io::Error::last_os_error()),
71      }
72    }
73  }
74
75  impl Drop for Lock {
76    fn drop(&mut self) {
77      unsafe {
78        ReleaseMutex(self.0.as_raw_handle() as _);
79      }
80    }
81  }
82}
83
84#[cfg(windows)]
85mod windows_security {
86  use std::ffi::c_void;
87  use std::fs::File;
88  use std::io;
89  use std::iter;
90  use std::mem::size_of;
91  use std::os::windows::ffi::OsStrExt;
92  use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle, RawHandle};
93  use std::path::Path;
94
95  use windows_sys::Win32::Foundation::{
96    GENERIC_READ, GENERIC_WRITE, INVALID_HANDLE_VALUE, LocalFree,
97  };
98  #[cfg(test)]
99  use windows_sys::Win32::Security::Authorization::ConvertSecurityDescriptorToStringSecurityDescriptorW;
100  use windows_sys::Win32::Security::Authorization::{
101    ConvertSidToStringSidW, ConvertStringSecurityDescriptorToSecurityDescriptorW, SDDL_REVISION_1,
102  };
103  use windows_sys::Win32::Security::{
104    DACL_SECURITY_INFORMATION, GetFileSecurityW, GetSecurityDescriptorControl, GetTokenInformation,
105    PROTECTED_DACL_SECURITY_INFORMATION, PSECURITY_DESCRIPTOR, SE_DACL_PROTECTED,
106    SECURITY_ATTRIBUTES, SetFileSecurityW, TOKEN_QUERY, TOKEN_USER, TokenUser,
107    UNPROTECTED_DACL_SECURITY_INFORMATION,
108  };
109  use windows_sys::Win32::Storage::FileSystem::{
110    CREATE_NEW, CreateFileW, DELETE, FILE_ATTRIBUTE_TEMPORARY, FILE_SHARE_DELETE, FILE_SHARE_READ,
111    FILE_SHARE_WRITE,
112  };
113  use windows_sys::Win32::System::Threading::{GetCurrentProcess, OpenProcessToken};
114
115  #[derive(Clone)]
116  pub(super) struct SecurityDescriptor {
117    storage: Vec<usize>,
118  }
119
120  impl SecurityDescriptor {
121    fn as_ptr(&self) -> PSECURITY_DESCRIPTOR {
122      self.storage.as_ptr().cast_mut().cast()
123    }
124  }
125
126  struct LocalAllocation(*mut c_void);
127
128  impl Drop for LocalAllocation {
129    fn drop(&mut self) {
130      if !self.0.is_null() {
131        unsafe {
132          LocalFree(self.0);
133        }
134      }
135    }
136  }
137
138  fn wide(path: &Path) -> Vec<u16> {
139    path
140      .as_os_str()
141      .encode_wide()
142      .chain(iter::once(0))
143      .collect()
144  }
145
146  fn current_user_sid() -> io::Result<String> {
147    unsafe {
148      let mut token = std::ptr::null_mut();
149      if OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token) == 0 {
150        return Err(io::Error::last_os_error());
151      }
152      let token = OwnedHandle::from_raw_handle(token as RawHandle);
153
154      let mut required = 0;
155      GetTokenInformation(
156        token.as_raw_handle() as _,
157        TokenUser,
158        std::ptr::null_mut(),
159        0,
160        &mut required,
161      );
162      if required == 0 {
163        return Err(io::Error::last_os_error());
164      }
165      let words = (required as usize).div_ceil(size_of::<usize>());
166      let mut token_info = vec![0usize; words];
167      if GetTokenInformation(
168        token.as_raw_handle() as _,
169        TokenUser,
170        token_info.as_mut_ptr().cast(),
171        required,
172        &mut required,
173      ) == 0
174      {
175        return Err(io::Error::last_os_error());
176      }
177      let token_user = &*token_info.as_ptr().cast::<TOKEN_USER>();
178      let mut sid_string = std::ptr::null_mut();
179      if ConvertSidToStringSidW(token_user.User.Sid, &mut sid_string) == 0 {
180        return Err(io::Error::last_os_error());
181      }
182      let allocation = LocalAllocation(sid_string.cast());
183      let len = (0..).take_while(|&i| *sid_string.add(i) != 0).count();
184      let result = String::from_utf16(std::slice::from_raw_parts(sid_string, len))
185        .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error));
186      drop(allocation);
187      result
188    }
189  }
190
191  fn private_descriptor() -> io::Result<LocalAllocation> {
192    let sddl = format!("D:P(A;;FA;;;{})", current_user_sid()?);
193    let encoded = sddl.encode_utf16().chain(iter::once(0)).collect::<Vec<_>>();
194    let mut descriptor = std::ptr::null_mut();
195    unsafe {
196      if ConvertStringSecurityDescriptorToSecurityDescriptorW(
197        encoded.as_ptr(),
198        SDDL_REVISION_1,
199        &mut descriptor,
200        std::ptr::null_mut(),
201      ) == 0
202      {
203        return Err(io::Error::last_os_error());
204      }
205    }
206    Ok(LocalAllocation(descriptor))
207  }
208
209  /// Create a file whose DACL grants access only to the current user.
210  pub(super) fn create_private_file(path: &Path) -> io::Result<File> {
211    let descriptor = private_descriptor()?;
212    let attributes = SECURITY_ATTRIBUTES {
213      nLength: size_of::<SECURITY_ATTRIBUTES>() as u32,
214      lpSecurityDescriptor: descriptor.0,
215      bInheritHandle: 0,
216    };
217    let path = wide(path);
218    let handle = unsafe {
219      CreateFileW(
220        path.as_ptr(),
221        GENERIC_READ | GENERIC_WRITE | DELETE,
222        FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
223        &attributes,
224        CREATE_NEW,
225        FILE_ATTRIBUTE_TEMPORARY,
226        std::ptr::null_mut(),
227      )
228    };
229    if handle == INVALID_HANDLE_VALUE {
230      Err(io::Error::last_os_error())
231    } else {
232      // The returned handle is uniquely owned and becomes owned by File.
233      Ok(unsafe { File::from_raw_handle(handle as RawHandle) })
234    }
235  }
236
237  /// Capture the target DACL, including whether inheritance is protected.
238  pub(super) fn read_dacl(path: &Path) -> io::Result<SecurityDescriptor> {
239    let path = wide(path);
240    let mut required = 0;
241    unsafe {
242      GetFileSecurityW(
243        path.as_ptr(),
244        DACL_SECURITY_INFORMATION,
245        std::ptr::null_mut(),
246        0,
247        &mut required,
248      );
249    }
250    if required == 0 {
251      return Err(io::Error::last_os_error());
252    }
253    let words = (required as usize).div_ceil(size_of::<usize>());
254    let mut storage = vec![0usize; words];
255    if unsafe {
256      GetFileSecurityW(
257        path.as_ptr(),
258        DACL_SECURITY_INFORMATION,
259        storage.as_mut_ptr().cast(),
260        required,
261        &mut required,
262      )
263    } == 0
264    {
265      return Err(io::Error::last_os_error());
266    }
267    Ok(SecurityDescriptor { storage })
268  }
269
270  /// Apply a captured DACL without changing its inheritance protection state.
271  pub(super) fn apply_dacl(path: &Path, descriptor: &SecurityDescriptor) -> io::Result<()> {
272    let mut control = 0;
273    let mut revision = 0;
274    if unsafe { GetSecurityDescriptorControl(descriptor.as_ptr(), &mut control, &mut revision) }
275      == 0
276    {
277      return Err(io::Error::last_os_error());
278    }
279    let protection = if control & SE_DACL_PROTECTED != 0 {
280      PROTECTED_DACL_SECURITY_INFORMATION
281    } else {
282      UNPROTECTED_DACL_SECURITY_INFORMATION
283    };
284    let path = wide(path);
285    if unsafe {
286      SetFileSecurityW(
287        path.as_ptr(),
288        DACL_SECURITY_INFORMATION | protection,
289        descriptor.as_ptr(),
290      )
291    } == 0
292    {
293      Err(io::Error::last_os_error())
294    } else {
295      Ok(())
296    }
297  }
298
299  #[cfg(test)]
300  unsafe fn descriptor_to_sddl(descriptor: PSECURITY_DESCRIPTOR) -> io::Result<String> {
301    let mut text = std::ptr::null_mut();
302    if unsafe {
303      ConvertSecurityDescriptorToStringSecurityDescriptorW(
304        descriptor,
305        SDDL_REVISION_1,
306        DACL_SECURITY_INFORMATION,
307        &mut text,
308        std::ptr::null_mut(),
309      )
310    } == 0
311    {
312      return Err(io::Error::last_os_error());
313    }
314    let allocation = LocalAllocation(text.cast());
315    let len = (0..).take_while(|&i| unsafe { *text.add(i) != 0 }).count();
316    let result = String::from_utf16(unsafe { std::slice::from_raw_parts(text, len) })
317      .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error));
318    drop(allocation);
319    result
320  }
321
322  #[cfg(test)]
323  pub(super) fn dacl_sddl(path: &Path) -> io::Result<String> {
324    let descriptor = read_dacl(path)?;
325    unsafe { descriptor_to_sddl(descriptor.as_ptr()) }
326  }
327
328  #[cfg(test)]
329  pub(super) fn private_dacl_sddl() -> io::Result<String> {
330    let descriptor = private_descriptor()?;
331    unsafe { descriptor_to_sddl(descriptor.0) }
332  }
333}
334
335/// Resolve an existing path through symlinks, or resolve its nearest existing ancestor.
336pub fn resolve(path: &Path) -> Result<PathBuf, AuthError> {
337  let absolute = if path.is_absolute() {
338    path.to_path_buf()
339  } else {
340    std::env::current_dir()?.join(path)
341  };
342  match fs::symlink_metadata(&absolute) {
343    Ok(_) => Ok(absolute.canonicalize()?),
344    Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
345      let parent = absolute
346        .parent()
347        .ok_or_else(|| AuthError::Config(format!("Path has no parent: {}", absolute.display())))?;
348      let name = absolute.file_name().ok_or_else(|| {
349        AuthError::Config(format!("Path has no file name: {}", absolute.display()))
350      })?;
351      Ok(resolve(parent)?.join(name))
352    }
353    Err(e) => Err(e.into()),
354  }
355}
356
357#[derive(Clone)]
358struct Snapshot {
359  contents: Option<String>,
360  permissions: Option<Permissions>,
361  #[cfg(windows)]
362  dacl: Option<windows_security::SecurityDescriptor>,
363}
364
365/// Holds cooperative locks from the initial reads through all replacements.
366///
367/// Every output is staged before the first rename. Each rename is atomic, although
368/// replacing several different files cannot be a single filesystem transaction.
369pub struct FileTransaction {
370  snapshots: BTreeMap<PathBuf, Snapshot>,
371  staged: BTreeMap<PathBuf, NamedTempFile>,
372  _locks: Vec<platform_lock::Lock>,
373}
374
375impl FileTransaction {
376  /// Resolve and lock every path in sorted order, then read their contents.
377  pub fn new(paths: &[PathBuf]) -> Result<Self, AuthError> {
378    let mut resolved = paths
379      .iter()
380      .map(|p| resolve(p))
381      .collect::<Result<Vec<_>, _>>()?;
382    resolved.sort();
383    resolved.dedup();
384
385    let mut directories = resolved
386      .iter()
387      .map(|path| {
388        path
389          .parent()
390          .map(Path::to_path_buf)
391          .ok_or_else(|| AuthError::Config(format!("Path has no parent: {}", path.display())))
392      })
393      .collect::<Result<Vec<_>, _>>()?;
394    directories.sort();
395    directories.dedup();
396
397    let mut locks = Vec::with_capacity(directories.len());
398    for parent in directories {
399      fs::create_dir_all(&parent)?;
400      locks.push(platform_lock::Lock::acquire(&parent)?);
401    }
402
403    let mut snapshots = BTreeMap::new();
404    for path in resolved {
405      let snapshot = match fs::read_to_string(&path) {
406        Ok(contents) => Snapshot {
407          contents: Some(contents),
408          permissions: Some(fs::metadata(&path)?.permissions()),
409          #[cfg(windows)]
410          dacl: Some(windows_security::read_dacl(&path)?),
411        },
412        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Snapshot {
413          contents: None,
414          permissions: None,
415          #[cfg(windows)]
416          dacl: None,
417        },
418        Err(e) => return Err(e.into()),
419      };
420      snapshots.insert(path, snapshot);
421    }
422    Ok(Self {
423      snapshots,
424      staged: BTreeMap::new(),
425      _locks: locks,
426    })
427  }
428
429  /// Return the content read while the transaction held all requested locks.
430  pub fn contents(&self, path: &Path) -> Result<&str, AuthError> {
431    self
432      .snapshots
433      .get(path)
434      .map(|s| s.contents.as_deref().unwrap_or(""))
435      .ok_or_else(|| {
436        AuthError::Config(format!(
437          "Path was not included in the transaction: {}",
438          path.display()
439        ))
440      })
441  }
442
443  /// Whether the path existed when the transaction read it.
444  pub fn existed(&self, path: &Path) -> Result<bool, AuthError> {
445    self
446      .snapshots
447      .get(path)
448      .map(|s| s.contents.is_some())
449      .ok_or_else(|| {
450        AuthError::Config(format!(
451          "Path was not included in the transaction: {}",
452          path.display()
453        ))
454      })
455  }
456
457  /// Stage an output beside its destination without replacing that destination yet.
458  pub fn stage(&mut self, path: &Path, content: &str) -> Result<(), AuthError> {
459    let snapshot = self.snapshots.get(path).ok_or_else(|| {
460      AuthError::Config(format!(
461        "Path was not included in the transaction: {}",
462        path.display()
463      ))
464    })?;
465    if self.staged.contains_key(path) {
466      return Err(AuthError::Config(format!(
467        "File staged twice: {}",
468        path.display()
469      )));
470    }
471    let parent = path
472      .parent()
473      .ok_or_else(|| AuthError::Config(format!("Path has no parent: {}", path.display())))?;
474    #[cfg(windows)]
475    let mut temp = Builder::new()
476      .prefix(".node-auth-")
477      .make_in(parent, windows_security::create_private_file)?;
478    #[cfg(not(windows))]
479    let mut temp = Builder::new().prefix(".node-auth-").tempfile_in(parent)?;
480    #[cfg(windows)]
481    if let Some(dacl) = &snapshot.dacl {
482      windows_security::apply_dacl(temp.path(), dacl)?;
483    }
484    temp.write_all(content.as_bytes())?;
485    if let Some(permissions) = &snapshot.permissions {
486      temp.as_file().set_permissions(permissions.clone())?;
487    }
488    temp.as_file().sync_all()?;
489    self.staged.insert(path.to_path_buf(), temp);
490    Ok(())
491  }
492
493  /// Atomically replace each staged file, rejecting changes made since the initial read.
494  pub fn commit(mut self) -> Result<Vec<PathBuf>, AuthError> {
495    for (path, snapshot) in &self.snapshots {
496      let current = match fs::read_to_string(path) {
497        Ok(contents) => Some(contents),
498        Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
499        Err(e) => return Err(e.into()),
500      };
501      if current != snapshot.contents {
502        return Err(AuthError::Config(format!(
503          "Configuration changed during update: {}",
504          path.display()
505        )));
506      }
507    }
508
509    let mut written = Vec::new();
510    for (path, temp) in std::mem::take(&mut self.staged) {
511      temp.persist(&path).map_err(|e| AuthError::Io(e.error))?;
512      #[cfg(unix)]
513      File::open(path.parent().unwrap())?.sync_all()?;
514      written.push(path);
515    }
516    Ok(written)
517  }
518}
519
520#[cfg(test)]
521mod tests {
522  use super::*;
523  use tempfile::tempdir;
524
525  #[test]
526  fn resolves_aliases_and_replaces_atomically() {
527    let dir = tempdir().unwrap();
528    let path = dir.path().join(".npmrc");
529    fs::write(&path, "old").unwrap();
530    let alias = dir.path().join("./.npmrc");
531    assert_eq!(resolve(&path).unwrap(), resolve(&alias).unwrap());
532    let mut tx = FileTransaction::new(&[path.clone(), alias]).unwrap();
533    let resolved = resolve(&path).unwrap();
534    assert_eq!(tx.contents(&resolved).unwrap(), "old");
535    tx.stage(&resolved, "new").unwrap();
536    tx.commit().unwrap();
537    assert_eq!(fs::read_to_string(path).unwrap(), "new");
538    assert_eq!(fs::read_dir(dir.path()).unwrap().count(), 1);
539  }
540
541  #[cfg(unix)]
542  #[test]
543  fn new_file_is_private_and_existing_mode_is_preserved() {
544    use std::os::unix::fs::PermissionsExt;
545    let dir = tempdir().unwrap();
546    let new_path = dir.path().join("new.npmrc");
547    let mut tx = FileTransaction::new(std::slice::from_ref(&new_path)).unwrap();
548    tx.stage(&resolve(&new_path).unwrap(), "token").unwrap();
549    tx.commit().unwrap();
550    assert_eq!(
551      fs::metadata(&new_path).unwrap().permissions().mode() & 0o777,
552      0o600
553    );
554
555    fs::set_permissions(&new_path, Permissions::from_mode(0o640)).unwrap();
556    let mut tx = FileTransaction::new(std::slice::from_ref(&new_path)).unwrap();
557    tx.stage(&resolve(&new_path).unwrap(), "next").unwrap();
558    tx.commit().unwrap();
559    assert_eq!(
560      fs::metadata(&new_path).unwrap().permissions().mode() & 0o777,
561      0o640
562    );
563  }
564
565  #[cfg(windows)]
566  #[test]
567  fn new_file_is_private_and_existing_dacl_is_preserved() {
568    let dir = tempdir().unwrap();
569    let new_path = dir.path().join("new.npmrc");
570    let mut tx = FileTransaction::new(std::slice::from_ref(&new_path)).unwrap();
571    tx.stage(&resolve(&new_path).unwrap(), "token").unwrap();
572    tx.commit().unwrap();
573    assert_eq!(
574      windows_security::dacl_sddl(&new_path).unwrap(),
575      windows_security::private_dacl_sddl().unwrap()
576    );
577
578    let existing_path = dir.path().join("existing.npmrc");
579    fs::write(&existing_path, "old").unwrap();
580    let original_dacl = windows_security::dacl_sddl(&existing_path).unwrap();
581    let mut tx = FileTransaction::new(std::slice::from_ref(&existing_path)).unwrap();
582    tx.stage(&resolve(&existing_path).unwrap(), "next").unwrap();
583    tx.commit().unwrap();
584    assert_eq!(
585      windows_security::dacl_sddl(&existing_path).unwrap(),
586      original_dacl
587    );
588  }
589
590  #[test]
591  fn transactions_serialize_reads_and_writes() {
592    use std::sync::mpsc;
593    use std::time::Duration;
594    let dir = tempdir().unwrap();
595    let path = dir.path().join("shared.npmrc");
596    fs::write(&path, "old").unwrap();
597    let mut first = FileTransaction::new(std::slice::from_ref(&path)).unwrap();
598    let (started_tx, started_rx) = mpsc::channel();
599    let (content_tx, content_rx) = mpsc::channel();
600    let second_path = path.clone();
601    let worker = std::thread::spawn(move || {
602      started_tx.send(()).unwrap();
603      let second = FileTransaction::new(std::slice::from_ref(&second_path)).unwrap();
604      content_tx
605        .send(
606          second
607            .contents(&resolve(&second_path).unwrap())
608            .unwrap()
609            .to_string(),
610        )
611        .unwrap();
612    });
613    started_rx.recv().unwrap();
614    assert!(content_rx.recv_timeout(Duration::from_millis(50)).is_err());
615    first.stage(&resolve(&path).unwrap(), "new").unwrap();
616    first.commit().unwrap();
617    assert_eq!(
618      content_rx.recv_timeout(Duration::from_secs(2)).unwrap(),
619      "new"
620    );
621    worker.join().unwrap();
622  }
623}