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