Skip to main content

fallow_types/
read_scope.rs

1//! The owner rule of the read scope base.
2//!
3//! The read scope base of a project (`fallow_config::project_scope_base`) can
4//! be a directory above the analysis root, such as the Git work tree of a
5//! package root. A directory above the root widens the scope only when other
6//! users cannot write to it and one of these users owns it:
7//!
8//! - the current user (the effective uid), or
9//! - the user that owns the analysis root.
10//!
11//! So a CI job that runs as root on a checkout of another user still reads
12//! the shared configs of that checkout. A `/tmp/.git` entry, or a workspace
13//! manifest in a shared directory, does not widen the scope of a project
14//! below it, because a different user owns it or all users can write to it.
15//!
16//! On Windows the rule compares owner SIDs: a directory above the root widens
17//! the scope only when its owner is the user of the current process or the
18//! owner of the analysis root. So a `.git` entry in `C:\Users\Public` does not
19//! widen the scope of a project below it. The Windows rule has no check of
20//! the write access of other users, because the default ACLs of a user folder
21//! often grant that access and the check would drop the monorepo scope for
22//! most Windows users.
23
24use std::path::Path;
25
26/// The mode bit that lets all users write to a directory.
27#[cfg(unix)]
28const WRITABLE_BY_ALL: u32 = 0o002;
29
30/// True when the directory `dir` above the analysis root `root` may widen
31/// the read scope: other users cannot write to `dir`, and the current user
32/// or the owner of `root` owns `dir`. A metadata error counts as false. On
33/// Windows the rule does not apply, and the result is true.
34#[cfg(unix)]
35#[must_use]
36pub fn may_widen_scope(dir: &Path, root: &Path) -> bool {
37    use std::os::unix::fs::MetadataExt;
38    let (Ok(dir_meta), Ok(root_meta)) = (std::fs::metadata(dir), std::fs::metadata(root)) else {
39        return false;
40    };
41    owner_rule_allows(
42        dir_meta.uid(),
43        dir_meta.mode(),
44        root_meta.uid(),
45        rustix::process::geteuid().as_raw(),
46    )
47}
48
49/// True when the directory `dir` above the analysis root `root` may widen
50/// the read scope: the user of the current process or the owner of `root`
51/// owns `dir`. An error of an owner lookup counts as false.
52#[cfg(windows)]
53#[must_use]
54pub fn may_widen_scope(dir: &Path, root: &Path) -> bool {
55    let (Some(dir_owner), Some(root_owner), Some(user)) = (
56        windows_owner::owner_sid(dir),
57        windows_owner::owner_sid(root),
58        windows_owner::process_user_sid(),
59    ) else {
60        return false;
61    };
62    sid_owner_rule_allows(&dir_owner, &root_owner, &user)
63}
64
65/// True when the directory `dir` above the analysis root `root` may widen
66/// the read scope. On a target without an owner model the rule does not
67/// apply, and the result is true.
68#[cfg(not(any(unix, windows)))]
69#[must_use]
70pub fn may_widen_scope(_dir: &Path, _root: &Path) -> bool {
71    true
72}
73
74/// The Windows owner rule over the binary owner SID `dir_owner` of a
75/// directory, the owner SID `root_owner` of the analysis root, and the SID
76/// `user` of the process user. Two valid SIDs are equal exactly when their
77/// bytes are equal, so a byte compare gives the result of `EqualSid`.
78#[cfg(any(windows, test))]
79fn sid_owner_rule_allows(dir_owner: &[u8], root_owner: &[u8], user: &[u8]) -> bool {
80    dir_owner == user || dir_owner == root_owner
81}
82
83/// The Win32 owner lookups of the Windows owner rule. Each lookup copies the
84/// binary SID out of the memory that Windows owns, and returns `None` on an
85/// error.
86#[cfg(windows)]
87#[expect(unsafe_code, reason = "the owner SID lookups require Win32 FFI calls")]
88mod windows_owner {
89    use std::os::windows::ffi::OsStrExt;
90    use std::path::Path;
91
92    use windows_sys::Win32::Foundation::{CloseHandle, ERROR_SUCCESS, HANDLE, LocalFree};
93    use windows_sys::Win32::Security::Authorization::{GetNamedSecurityInfoW, SE_FILE_OBJECT};
94    use windows_sys::Win32::Security::{
95        GetLengthSid, GetTokenInformation, IsValidSid, OWNER_SECURITY_INFORMATION,
96        PSECURITY_DESCRIPTOR, PSID, TOKEN_QUERY, TOKEN_USER, TokenUser,
97    };
98    use windows_sys::Win32::System::Threading::{GetCurrentProcess, OpenProcessToken};
99
100    /// The binary owner SID of the file or directory `path`.
101    pub(super) fn owner_sid(path: &Path) -> Option<Vec<u8>> {
102        let mut wide: Vec<u16> = path.as_os_str().encode_wide().collect();
103        if wide.contains(&0) {
104            return None;
105        }
106        wide.push(0);
107        let mut owner: PSID = std::ptr::null_mut();
108        let mut descriptor: PSECURITY_DESCRIPTOR = std::ptr::null_mut();
109        // SAFETY: `wide` is a NUL-terminated UTF-16 string that lives for the
110        // call. The out pointers point to live locals, and the call accepts a
111        // null pointer for the group, the DACL and the SACL.
112        let status = unsafe {
113            GetNamedSecurityInfoW(
114                wide.as_ptr(),
115                SE_FILE_OBJECT,
116                OWNER_SECURITY_INFORMATION,
117                &raw mut owner,
118                std::ptr::null_mut(),
119                std::ptr::null_mut(),
120                std::ptr::null_mut(),
121                &raw mut descriptor,
122            )
123        };
124        if status != ERROR_SUCCESS {
125            return None;
126        }
127        let sid = copy_sid(owner);
128        // SAFETY: `descriptor` is the buffer that GetNamedSecurityInfoW
129        // allocated for this call. `owner` points into it, and `copy_sid`
130        // does not keep that pointer, so nothing reads it after the free.
131        unsafe { LocalFree(descriptor) };
132        sid
133    }
134
135    /// The binary SID of the user of the current process token.
136    pub(super) fn process_user_sid() -> Option<Vec<u8>> {
137        let mut token: HANDLE = std::ptr::null_mut();
138        // SAFETY: GetCurrentProcess returns a pseudo handle that needs no
139        // close.
140        let process = unsafe { GetCurrentProcess() };
141        // SAFETY: `token` is a live local that receives the token handle.
142        if unsafe { OpenProcessToken(process, TOKEN_QUERY, &raw mut token) } == 0 {
143            return None;
144        }
145        let sid = token_user_sid(token);
146        // SAFETY: `token` is the handle that OpenProcessToken opened above,
147        // and this is its only close.
148        unsafe { CloseHandle(token) };
149        sid
150    }
151
152    /// The binary SID in the `TokenUser` information of the token `token`.
153    fn token_user_sid(token: HANDLE) -> Option<Vec<u8>> {
154        let mut len: u32 = 0;
155        // SAFETY: A size query with a null buffer and a zero length writes
156        // only the required length into `len`. The call fails by design, so
157        // the code reads only `len`.
158        unsafe { GetTokenInformation(token, TokenUser, std::ptr::null_mut(), 0, &raw mut len) };
159        let byte_len = usize::try_from(len).ok()?;
160        if byte_len < std::mem::size_of::<TOKEN_USER>() {
161            return None;
162        }
163        // A `u64` buffer gives the pointer alignment that TOKEN_USER needs.
164        let mut buffer = vec![0_u64; byte_len.div_ceil(8)];
165        // SAFETY: `buffer` holds at least `len` writable bytes and lives for
166        // the call.
167        let ok = unsafe {
168            GetTokenInformation(
169                token,
170                TokenUser,
171                buffer.as_mut_ptr().cast(),
172                len,
173                &raw mut len,
174            )
175        };
176        if ok == 0 {
177            return None;
178        }
179        // SAFETY: The call above filled `buffer` with a TOKEN_USER value, and
180        // the buffer is aligned for it and at least as large as it.
181        let user = unsafe { &*buffer.as_ptr().cast::<TOKEN_USER>() };
182        copy_sid(user.User.Sid)
183    }
184
185    /// A copy of the bytes of the SID at `sid`, or `None` when the SID is
186    /// null or not valid.
187    fn copy_sid(sid: PSID) -> Option<Vec<u8>> {
188        if sid.is_null() {
189            return None;
190        }
191        // SAFETY: `sid` is a non-null SID pointer from a Win32 call, and its
192        // owner buffer is live for this function.
193        if unsafe { IsValidSid(sid) } == 0 {
194            return None;
195        }
196        // SAFETY: IsValidSid accepted `sid` above.
197        let len = usize::try_from(unsafe { GetLengthSid(sid) }).ok()?;
198        // SAFETY: A valid SID spans `len` readable bytes, as GetLengthSid
199        // reports.
200        let bytes = unsafe { std::slice::from_raw_parts(sid.cast::<u8>(), len) };
201        Some(bytes.to_vec())
202    }
203}
204
205/// The owner rule over the owner `dir_uid` and the mode `dir_mode` of a
206/// directory, the owner `root_uid` of the analysis root, and the effective
207/// uid `euid`.
208#[cfg(unix)]
209const fn owner_rule_allows(dir_uid: u32, dir_mode: u32, root_uid: u32, euid: u32) -> bool {
210    dir_mode & WRITABLE_BY_ALL == 0 && (dir_uid == euid || dir_uid == root_uid)
211}
212
213#[cfg(all(test, unix))]
214mod tests {
215    use super::*;
216
217    const PRIVATE_DIR: u32 = 0o040_755;
218    const SHARED_DIR: u32 = 0o041_777;
219
220    #[test]
221    fn a_directory_of_the_current_user_widens_the_scope() {
222        assert!(owner_rule_allows(501, PRIVATE_DIR, 1001, 501));
223    }
224
225    #[test]
226    fn a_directory_of_the_root_owner_widens_the_scope_for_another_user() {
227        assert!(owner_rule_allows(1001, PRIVATE_DIR, 1001, 0));
228    }
229
230    #[test]
231    fn a_directory_of_a_third_user_does_not_widen_the_scope() {
232        assert!(!owner_rule_allows(2002, PRIVATE_DIR, 1001, 0));
233    }
234
235    #[test]
236    fn a_directory_that_all_users_can_write_never_widens_the_scope() {
237        assert!(!owner_rule_allows(501, SHARED_DIR, 501, 501));
238        assert!(!owner_rule_allows(1001, SHARED_DIR, 1001, 0));
239    }
240
241    #[test]
242    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
243    fn a_directory_that_all_users_can_write_does_not_widen_the_scope() {
244        use std::os::unix::fs::PermissionsExt;
245        let dir = tempfile::tempdir().expect("temp dir");
246        let root = dir.path().join("root");
247        std::fs::create_dir(&root).expect("root dir");
248        assert!(may_widen_scope(dir.path(), &root));
249        std::fs::set_permissions(dir.path(), std::fs::Permissions::from_mode(0o777))
250            .expect("chmod");
251        assert!(!may_widen_scope(dir.path(), &root));
252        std::fs::set_permissions(dir.path(), std::fs::Permissions::from_mode(0o700))
253            .expect("chmod");
254    }
255
256    /// `/usr` belongs to the system user on each Unix host.
257    #[test]
258    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
259    fn a_directory_that_another_user_owns_does_not_widen_the_scope() {
260        if rustix::process::geteuid().is_root() {
261            return;
262        }
263        let root = tempfile::tempdir().expect("temp dir");
264        assert!(!may_widen_scope(Path::new("/usr"), root.path()));
265    }
266}
267
268#[cfg(test)]
269mod sid_tests {
270    use super::sid_owner_rule_allows;
271
272    /// The binary SIDs `S-1-5-21-1-2-3-1001`, `-1002` and `-1003`.
273    const fn user_sid(rid: u8) -> [u8; 28] {
274        [
275            1, 5, 0, 0, 0, 0, 0, 5, 21, 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, rid, 3, 0, 0,
276        ]
277    }
278
279    #[test]
280    fn a_directory_of_the_process_user_widens_the_scope() {
281        assert!(sid_owner_rule_allows(
282            &user_sid(1),
283            &user_sid(2),
284            &user_sid(1)
285        ));
286    }
287
288    #[test]
289    fn a_directory_of_the_root_owner_widens_the_scope_for_another_user() {
290        assert!(sid_owner_rule_allows(
291            &user_sid(2),
292            &user_sid(2),
293            &user_sid(1)
294        ));
295    }
296
297    #[test]
298    fn a_directory_of_a_third_user_does_not_widen_the_scope() {
299        assert!(!sid_owner_rule_allows(
300            &user_sid(3),
301            &user_sid(2),
302            &user_sid(1)
303        ));
304    }
305}
306
307#[cfg(all(test, windows))]
308mod windows_tests {
309    use super::may_widen_scope;
310
311    #[test]
312    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
313    fn a_directory_of_the_current_user_widens_the_scope_of_a_root_below_it() {
314        let dir = tempfile::tempdir().expect("temp dir");
315        let root = dir.path().join("root");
316        std::fs::create_dir(&root).expect("root dir");
317        assert!(may_widen_scope(dir.path(), &root));
318    }
319
320    #[test]
321    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
322    fn a_path_without_an_owner_does_not_widen_the_scope() {
323        let dir = tempfile::tempdir().expect("temp dir");
324        let missing = dir.path().join("missing");
325        assert!(!may_widen_scope(&missing, dir.path()));
326    }
327}