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