Skip to main content

day_pieces/
file_access.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! Explicit leases for persistent macOS file access; no process-global URL leak.
5use crate::FileUrl;
6use std::io;
7
8/// A resolved file and the lifetime of its native access grant. Borrow the file while doing
9/// I/O; a cloned path alone does not retain access after this guard is dropped.
10pub struct FileAccess {
11    file: FileUrl,
12    stale: bool,
13    #[cfg(target_os = "macos")]
14    _access: apple::Access,
15}
16impl FileAccess {
17    pub fn file(&self) -> &FileUrl {
18        &self.file
19    }
20    /// Renew a stale bookmark with `file().bookmark(...)` while this guard is alive and
21    /// replace the stored bytes. A moved file may resolve to a different path.
22    pub fn was_stale(&self) -> bool {
23        self.stale
24    }
25}
26
27#[cfg(target_os = "macos")]
28mod apple {
29    use super::*;
30    use objc2::{rc::Retained, runtime::Bool};
31    use objc2_foundation::{
32        NSData, NSString, NSURL, NSURLBookmarkCreationOptions as Creation,
33        NSURLBookmarkResolutionOptions as Resolution,
34    };
35
36    pub(super) struct Access {
37        url: Retained<NSURL>,
38        active: bool,
39    }
40    impl Drop for Access {
41        fn drop(&mut self) {
42            if self.active {
43                unsafe { self.url.stopAccessingSecurityScopedResource() };
44            }
45        }
46    }
47    pub fn bookmark(file: &FileUrl, read_only: bool) -> io::Result<Vec<u8>> {
48        let path = file.local_path().ok_or(io::ErrorKind::InvalidInput)?;
49        if !path.is_absolute() {
50            return Err(io::ErrorKind::InvalidInput.into());
51        }
52        let path = path.to_str().ok_or(io::ErrorKind::InvalidInput)?;
53        let url = NSURL::fileURLWithPath(&NSString::from_str(path));
54        let mut options = Creation::WithSecurityScope;
55        if read_only {
56            options |= Creation::SecurityScopeAllowOnlyReadAccess;
57        }
58        let data = url
59            .bookmarkDataWithOptions_includingResourceValuesForKeys_relativeToURL_error(
60                options, None, None,
61            )
62            .map_err(|e| io::Error::other(e.to_string()))?;
63        Ok(data.to_vec())
64    }
65    pub fn resolve(bytes: &[u8]) -> io::Result<FileAccess> {
66        // Bookmarks are small metadata, not file contents. Reject accidental/untrusted bulk data.
67        if bytes.is_empty() || bytes.len() > 1024 * 1024 {
68            return Err(io::ErrorKind::InvalidData.into());
69        }
70        let mut stale = Bool::NO;
71        let url = unsafe {
72            NSURL::URLByResolvingBookmarkData_options_relativeToURL_bookmarkDataIsStale_error(
73                &NSData::with_bytes(bytes),
74                Resolution::WithSecurityScope | Resolution::WithoutUI,
75                None,
76                &mut stale,
77            )
78        }
79        .map_err(|e| io::Error::other(e.to_string()))?;
80        if !url.isFileURL() {
81            return Err(io::ErrorKind::InvalidData.into());
82        }
83        let active = unsafe { url.startAccessingSecurityScopedResource() };
84        let access = Access { url, active };
85        let path = access
86            .url
87            .path()
88            .ok_or(io::ErrorKind::InvalidData)?
89            .to_string();
90        Ok(FileAccess {
91            file: FileUrl::new(path),
92            stale: stale.as_bool(),
93            _access: access,
94        })
95    }
96}
97#[cfg(target_os = "macos")]
98pub(crate) use apple::{bookmark, resolve};
99
100#[cfg(not(target_os = "macos"))]
101pub(crate) fn bookmark(_: &FileUrl, _: bool) -> io::Result<Vec<u8>> {
102    Err(io::ErrorKind::Unsupported.into())
103}
104#[cfg(not(target_os = "macos"))]
105pub(crate) fn resolve(_: &[u8]) -> io::Result<FileAccess> {
106    Err(io::ErrorKind::Unsupported.into())
107}
108
109#[cfg(any(target_os = "macos", target_os = "ios"))]
110pub(crate) struct ScopedRead {
111    url: objc2::rc::Retained<objc2_foundation::NSURL>,
112    active: bool,
113}
114#[cfg(any(target_os = "macos", target_os = "ios"))]
115impl Drop for ScopedRead {
116    fn drop(&mut self) {
117        if self.active {
118            unsafe { self.url.stopAccessingSecurityScopedResource() };
119        }
120    }
121}
122#[cfg(any(target_os = "macos", target_os = "ios"))]
123pub(crate) fn scoped_read(path: &std::path::Path) -> io::Result<ScopedRead> {
124    let path = path.to_str().ok_or(io::ErrorKind::InvalidInput)?;
125    let url = objc2_foundation::NSURL::fileURLWithPath(&objc2_foundation::NSString::from_str(path));
126    // False is normal for app-private files and unsandboxed desktop apps.
127    let active = unsafe { url.startAccessingSecurityScopedResource() };
128    Ok(ScopedRead { url, active })
129}
130
131#[cfg(test)]
132mod tests {
133    use super::*;
134    #[test]
135    fn file_urls_decode_unicode_and_spaces_and_reject_remote_authorities() {
136        assert_eq!(
137            FileUrl::new("file:///tmp/a%20b%23%E2%98%80.txt")
138                .local_path()
139                .unwrap(),
140            std::path::PathBuf::from("/tmp/a b#☀.txt")
141        );
142        assert!(
143            FileUrl::new("file://remote/tmp/a.txt")
144                .local_path()
145                .is_none()
146        );
147        assert!(FileUrl::new("file:///tmp/%ZZ").local_path().is_none());
148    }
149    #[cfg(target_os = "macos")]
150    #[test]
151    fn native_bookmark_round_trip_preserves_file_contents() {
152        let dir = std::env::temp_dir().join(format!(
153            "day-bookmark-{}-{}",
154            std::process::id(),
155            std::time::SystemTime::now()
156                .duration_since(std::time::UNIX_EPOCH)
157                .unwrap()
158                .as_nanos()
159        ));
160        std::fs::create_dir(&dir).unwrap();
161        let path = dir.join("file café #1.txt");
162        std::fs::write(&path, b"bookmark contents").unwrap();
163        let file = FileUrl::new(path.to_str().unwrap());
164        let bytes = file.bookmark(true).unwrap();
165        {
166            let access = FileUrl::resolve_bookmark(&bytes).unwrap();
167            assert_eq!(access.file().read().unwrap(), b"bookmark contents");
168        }
169        // Repeated resolution exercises balanced scoped access lifetimes.
170        let access = FileUrl::resolve_bookmark(&bytes).unwrap();
171        assert_eq!(access.file().read().unwrap(), b"bookmark contents");
172        drop(access);
173        std::fs::remove_dir_all(dir).unwrap();
174    }
175
176    #[test]
177    fn invalid_bookmarks_do_not_create_access() {
178        assert!(FileUrl::resolve_bookmark(&[]).is_err());
179        assert!(FileUrl::resolve_bookmark(b"not a bookmark").is_err());
180    }
181}