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