Skip to main content

codewhale_runtime/
external_credentials.rs

1//! Capability-gated I/O for credentials owned by another CLI.
2//!
3//! Every external open/read stays behind an opaque grant. Consumption opens
4//! one absolute regular file through a no-follow traversal, validates that
5//! same handle, and reads a bounded payload from it. This prevents a consented
6//! path from being redirected through a leaf or parent symlink/reparse point
7//! and avoids the old exists-then-read race.
8
9use std::fs::File;
10use std::io::{self, Read};
11use std::path::Path;
12
13use anyhow::{Context, Result, bail};
14use codewhale_config::ExternalCredentialReadGrant;
15
16/// Credential JSON is expected to be tiny. Bound reads so a replaced regular
17/// file cannot turn read-only consent into unbounded memory consumption.
18const MAX_EXTERNAL_CREDENTIAL_BYTES: u64 = 1024 * 1024;
19
20#[cfg(all(test, unix))]
21thread_local! {
22    static BEFORE_LEAF_OPEN_HOOK: std::cell::RefCell<Option<Box<dyn FnOnce()>>> =
23        std::cell::RefCell::new(None);
24}
25
26#[cfg(any(test, feature = "test-support"))]
27thread_local! {
28    /// Per-test-thread real sink counters. Keeping the trap thread-local makes
29    /// parallel tests unable to contaminate one another while still counting
30    /// the exact production functions reached by the code under test.
31    static SIDE_EFFECT_TRAP: std::cell::Cell<[usize; 5]> = const {
32        std::cell::Cell::new([0; 5])
33    };
34}
35
36#[cfg(any(test, feature = "test-support"))]
37fn increment_side_effect(index: usize) {
38    SIDE_EFFECT_TRAP.with(|trap| {
39        let mut counts = trap.get();
40        counts[index] += 1;
41        trap.set(counts);
42    });
43}
44
45/// Open and read the exact granted file once. Missing files are reported as
46/// `Ok(None)`; every other unsafe or malformed filesystem shape fails closed.
47pub fn read_to_string(grant: &ExternalCredentialReadGrant) -> Result<Option<String>> {
48    #[cfg(any(test, feature = "test-support"))]
49    increment_side_effect(0);
50
51    let mut file = match open_secure_regular_file(grant.path(), false) {
52        Ok(file) => file,
53        Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None),
54        Err(error) => {
55            return Err(error).with_context(|| {
56                format!(
57                    "securely opening external {} credential file {}",
58                    grant.source().as_str(),
59                    codewhale_config::quote_os_path(grant.path())
60                )
61            });
62        }
63    };
64
65    #[cfg(any(test, feature = "test-support"))]
66    increment_side_effect(1);
67
68    let mut bytes = Vec::new();
69    file.by_ref()
70        .take(MAX_EXTERNAL_CREDENTIAL_BYTES + 1)
71        .read_to_end(&mut bytes)
72        .with_context(|| {
73            format!(
74                "reading external {} credential file {}",
75                grant.source().as_str(),
76                codewhale_config::quote_os_path(grant.path())
77            )
78        })?;
79    if bytes.len() as u64 > MAX_EXTERNAL_CREDENTIAL_BYTES {
80        bail!(
81            "external {} credential file {} exceeds the {} byte safety limit",
82            grant.source().as_str(),
83            codewhale_config::quote_os_path(grant.path()),
84            MAX_EXTERNAL_CREDENTIAL_BYTES
85        );
86    }
87    let contents = String::from_utf8(bytes).with_context(|| {
88        format!(
89            "external {} credential file {} is not valid UTF-8",
90            grant.source().as_str(),
91            codewhale_config::quote_os_path(grant.path())
92        )
93    })?;
94    Ok(Some(contents))
95}
96
97/// Read one Codewhale-owned credential file through the same no-follow,
98/// bounded I/O boundary used for external grants. On Unix the opened handle
99/// must belong to the effective user and have no group/other permission bits.
100/// The caller is responsible for constraining `path` to a validated basename
101/// below Codewhale's credentials directory before invoking this function.
102pub fn read_codewhale_owned_to_string(path: &Path) -> Result<Option<String>> {
103    let mut file = match open_secure_regular_file(path, true) {
104        Ok(file) => file,
105        Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None),
106        Err(error) => {
107            return Err(error).with_context(|| {
108                format!(
109                    "securely opening Codewhale-owned credential file {}",
110                    codewhale_config::quote_os_path(path)
111                )
112            });
113        }
114    };
115    let mut bytes = Vec::new();
116    file.by_ref()
117        .take(MAX_EXTERNAL_CREDENTIAL_BYTES + 1)
118        .read_to_end(&mut bytes)
119        .with_context(|| {
120            format!(
121                "reading Codewhale-owned credential file {}",
122                codewhale_config::quote_os_path(path)
123            )
124        })?;
125    if bytes.len() as u64 > MAX_EXTERNAL_CREDENTIAL_BYTES {
126        bail!(
127            "Codewhale-owned credential file {} exceeds the {} byte safety limit",
128            codewhale_config::quote_os_path(path),
129            MAX_EXTERNAL_CREDENTIAL_BYTES
130        );
131    }
132    String::from_utf8(bytes).map(Some).with_context(|| {
133        format!(
134            "Codewhale-owned credential file {} is not valid UTF-8",
135            codewhale_config::quote_os_path(path)
136        )
137    })
138}
139
140#[cfg(unix)]
141fn open_secure_regular_file(path: &Path, require_owner_only: bool) -> io::Result<File> {
142    use std::ffi::CString;
143    use std::os::fd::FromRawFd;
144    use std::os::unix::ffi::OsStrExt;
145    use std::path::Component;
146
147    if !path.is_absolute() {
148        return Err(io::Error::new(
149            io::ErrorKind::InvalidInput,
150            "external credential path must be absolute",
151        ));
152    }
153
154    let root = CString::new("/").expect("static root contains no NUL");
155    // SAFETY: `root` is a valid C string and flags require no variadic mode.
156    let root_fd = unsafe {
157        libc::open(
158            root.as_ptr(),
159            libc::O_RDONLY | libc::O_DIRECTORY | libc::O_CLOEXEC,
160        )
161    };
162    if root_fd < 0 {
163        return Err(io::Error::last_os_error());
164    }
165    // SAFETY: `root_fd` is newly owned after the successful `open`.
166    let mut current = unsafe { File::from_raw_fd(root_fd) };
167    let mut normals = path
168        .components()
169        .filter_map(|component| match component {
170            Component::Normal(part) => Some(Ok(part)),
171            Component::RootDir => None,
172            Component::Prefix(_) | Component::CurDir | Component::ParentDir => {
173                Some(Err(io::Error::new(
174                    io::ErrorKind::InvalidInput,
175                    "external credential path must be lexically normalized",
176                )))
177            }
178        })
179        .peekable();
180
181    let mut opened_leaf = false;
182    while let Some(component) = normals.next() {
183        let component = component?;
184        let component = CString::new(component.as_bytes()).map_err(|_| {
185            io::Error::new(
186                io::ErrorKind::InvalidInput,
187                "external credential path contains a NUL byte",
188            )
189        })?;
190        let leaf = normals.peek().is_none();
191        #[cfg(test)]
192        if leaf {
193            BEFORE_LEAF_OPEN_HOOK.with(|hook| {
194                if let Some(hook) = hook.borrow_mut().take() {
195                    hook();
196                }
197            });
198        }
199        let flags = if leaf {
200            libc::O_RDONLY | libc::O_CLOEXEC | libc::O_NOFOLLOW | libc::O_NONBLOCK
201        } else {
202            libc::O_RDONLY | libc::O_CLOEXEC | libc::O_NOFOLLOW | libc::O_DIRECTORY
203        };
204        use std::os::fd::AsRawFd;
205        // SAFETY: the directory fd and component C string are valid for this
206        // call and flags require no variadic mode.
207        let fd = unsafe { libc::openat(current.as_raw_fd(), component.as_ptr(), flags) };
208        if fd < 0 {
209            return Err(io::Error::last_os_error());
210        }
211        // SAFETY: `fd` is newly owned after the successful `openat`.
212        current = unsafe { File::from_raw_fd(fd) };
213        opened_leaf = leaf;
214    }
215
216    if !opened_leaf {
217        return Err(io::Error::new(
218            io::ErrorKind::InvalidInput,
219            "external credential path must name a file",
220        ));
221    }
222    let metadata = current.metadata()?;
223    if !metadata.file_type().is_file() {
224        return Err(io::Error::new(
225            io::ErrorKind::InvalidInput,
226            "external credential path must name a regular file",
227        ));
228    }
229    if require_owner_only {
230        use std::os::unix::fs::MetadataExt as _;
231        // SAFETY: geteuid(2) dereferences no pointers.
232        let public = metadata.uid() != unsafe { libc::geteuid() } || metadata.mode() & 0o077 != 0;
233        // A mount that reports ownership of its own (HarmonyOS hmdfs) makes
234        // both the owner and the mode meaningless as evidence, so a real
235        // disagreement is only a refusal when the mount can express the fields
236        // it is being judged on. Asking costs a probe, so it is asked only
237        // here — after the cheap comparison has already failed — and the
238        // single-link requirement, which the mount does store, always holds.
239        let ownership_unproven = public && !mount_cannot_express_ownership(path);
240        if ownership_unproven || metadata.nlink() != 1 {
241            return Err(io::Error::new(
242                io::ErrorKind::PermissionDenied,
243                "Codewhale-owned credential file must be singly linked, owned by this user, and mode 0600 or stricter",
244            ));
245        }
246    }
247    Ok(current)
248}
249
250/// Whether this path's filesystem reports an owner and mode of its own for
251/// every object, so neither can serve as evidence of who may read it.
252///
253/// HarmonyOS hmdfs (the 2in1 user directory) is that case: it reports the
254/// logged-in user's uid and a group-writable mode for objects the app creates,
255/// and `chmod` answers `EPERM` because that owner is not the caller. The guard
256/// is unprovable there for *every* caller, so
257/// refusing would make the feature unusable on the platform; what remains is
258/// the mount's own access control plus the single-link check.
259#[cfg(unix)]
260fn mount_cannot_express_ownership(path: &std::path::Path) -> bool {
261    let directory = path.parent().unwrap_or(path);
262    matches!(
263        codewhale_config::private_directory::mount_footing(directory),
264        codewhale_config::private_directory::PrivateFooting::Synthesised { .. }
265    )
266}
267
268#[cfg(windows)]
269fn open_secure_regular_file(path: &Path, require_owner_only: bool) -> io::Result<File> {
270    use std::ffi::OsString;
271    use std::os::windows::ffi::OsStringExt;
272    use std::os::windows::fs::{MetadataExt, OpenOptionsExt};
273    use std::os::windows::io::AsRawHandle;
274    use std::path::Component;
275    use windows_sys::Win32::Storage::FileSystem::{
276        FILE_ATTRIBUTE_REPARSE_POINT, FILE_FLAG_OPEN_REPARSE_POINT, FILE_NAME_OPENED,
277        GetFinalPathNameByHandleW, VOLUME_NAME_DOS,
278    };
279
280    if !path.is_absolute()
281        || path
282            .components()
283            .any(|component| matches!(component, Component::CurDir | Component::ParentDir))
284    {
285        return Err(io::Error::new(
286            io::ErrorKind::InvalidInput,
287            "external credential path must be absolute and lexically normalized",
288        ));
289    }
290
291    // Reject every reparse-point component before the final open. The final
292    // handle is opened as the reparse point itself, checked again, and its
293    // kernel-resolved path is compared below. A second component pass catches
294    // replacement during the open window.
295    reject_windows_reparse_components(path)?;
296    let file = std::fs::OpenOptions::new()
297        .read(true)
298        .custom_flags(FILE_FLAG_OPEN_REPARSE_POINT)
299        .open(path)?;
300    let metadata = file.metadata()?;
301    if metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0
302        || !metadata.file_type().is_file()
303    {
304        return Err(io::Error::new(
305            io::ErrorKind::InvalidInput,
306            "external credential path must name a non-reparse regular file",
307        ));
308    }
309    reject_windows_reparse_components(path)?;
310
311    let handle = file.as_raw_handle();
312    // Compare the spelling Windows actually opened rather than asking it to
313    // expand the path into its normalized long form. A valid caller path can
314    // contain an 8.3 component such as `RUNNER~1`; normalizing only the handle
315    // side would make that exact path look redirected. FILE_NAME_OPENED keeps
316    // the comparison handle-relative while the pre/post component checks above
317    // continue to reject reparse points and swaps.
318    let flags = FILE_NAME_OPENED | VOLUME_NAME_DOS;
319    // SAFETY: the handle remains owned by `file`; null output asks Windows for
320    // the required UTF-16 buffer length.
321    let needed = unsafe { GetFinalPathNameByHandleW(handle, std::ptr::null_mut(), 0, flags) };
322    if needed == 0 {
323        return Err(io::Error::last_os_error());
324    }
325    let mut buffer = vec![0u16; needed as usize + 1];
326    // SAFETY: `buffer` is writable for its declared length and `handle` is
327    // valid for the duration of the call.
328    let written = unsafe {
329        GetFinalPathNameByHandleW(handle, buffer.as_mut_ptr(), buffer.len() as u32, flags)
330    };
331    if written == 0 || written as usize >= buffer.len() {
332        return Err(io::Error::last_os_error());
333    }
334    let final_path = OsString::from_wide(&buffer[..written as usize]);
335    let actual = normalize_windows_path_for_comparison(Path::new(&final_path))?;
336    let expected = normalize_windows_path_for_comparison(path)?;
337    if actual != expected {
338        return Err(io::Error::new(
339            io::ErrorKind::PermissionDenied,
340            "external credential path was redirected while opening",
341        ));
342    }
343    if require_owner_only {
344        use windows_sys::Win32::Storage::FileSystem::{
345            BY_HANDLE_FILE_INFORMATION, GetFileInformationByHandle,
346        };
347        let mut information = BY_HANDLE_FILE_INFORMATION::default();
348        // SAFETY: the opened credential handle and output pointer remain valid
349        // for the duration of the call.
350        if unsafe { GetFileInformationByHandle(handle, &mut information) } == 0 {
351            return Err(io::Error::last_os_error());
352        }
353        if information.nNumberOfLinks != 1 {
354            return Err(io::Error::new(
355                io::ErrorKind::PermissionDenied,
356                "Codewhale-owned credential file must be singly linked",
357            ));
358        }
359        verify_windows_owner_only_handle(handle)?;
360    }
361    Ok(file)
362}
363
364/// Normalize a Windows path without replacement characters. Unpaired UTF-16
365/// is rejected so two distinct paths can never compare equal after a lossy
366/// conversion. This is intentionally stricter than filesystem display.
367#[cfg(windows)]
368fn normalize_windows_path_for_comparison(path: &Path) -> io::Result<String> {
369    let text = path.to_str().ok_or_else(|| {
370        io::Error::new(
371            io::ErrorKind::PermissionDenied,
372            "credential path contains invalid Unicode and cannot be compared safely",
373        )
374    })?;
375    let without_device_prefix = text.strip_prefix(r"\\?\").unwrap_or(text);
376    let normalized_prefix = without_device_prefix.strip_prefix("UNC\\").map_or_else(
377        || without_device_prefix.to_string(),
378        |rest| format!(r"\\{rest}"),
379    );
380    Ok(normalized_prefix
381        .replace('/', "\\")
382        .trim_end_matches('\\')
383        .to_lowercase())
384}
385
386/// Apply a protected DACL granting only the current Windows user full access.
387/// Directories propagate that owner-only policy to newly staged generations.
388#[cfg(all(windows, any(test, feature = "test-support")))]
389pub fn secure_codewhale_owned_windows_path(
390    path: &Path,
391    inherit_to_children: bool,
392) -> io::Result<()> {
393    use std::os::windows::ffi::OsStrExt as _;
394    use windows_sys::Win32::Foundation::ERROR_SUCCESS;
395    use windows_sys::Win32::Security::Authorization::{
396        EXPLICIT_ACCESS_W, SE_FILE_OBJECT, SET_ACCESS, SetEntriesInAclW, SetNamedSecurityInfoW,
397        TRUSTEE_IS_SID, TRUSTEE_IS_USER, TRUSTEE_W,
398    };
399    use windows_sys::Win32::Security::{
400        DACL_SECURITY_INFORMATION, NO_INHERITANCE, OWNER_SECURITY_INFORMATION,
401        PROTECTED_DACL_SECURITY_INFORMATION, SUB_CONTAINERS_AND_OBJECTS_INHERIT,
402    };
403    use windows_sys::Win32::Storage::FileSystem::FILE_ALL_ACCESS;
404
405    let user = CurrentWindowsUser::open()?;
406    let entry = EXPLICIT_ACCESS_W {
407        grfAccessPermissions: FILE_ALL_ACCESS,
408        grfAccessMode: SET_ACCESS,
409        grfInheritance: if inherit_to_children {
410            SUB_CONTAINERS_AND_OBJECTS_INHERIT
411        } else {
412            NO_INHERITANCE
413        },
414        Trustee: TRUSTEE_W {
415            pMultipleTrustee: std::ptr::null_mut(),
416            MultipleTrusteeOperation: 0,
417            TrusteeForm: TRUSTEE_IS_SID,
418            TrusteeType: TRUSTEE_IS_USER,
419            ptstrName: user.sid().cast::<u16>(),
420        },
421    };
422    let mut acl = std::ptr::null_mut();
423    // SAFETY: `entry` and the returned ACL stay live through the security-info
424    // update; the ACL is released with LocalFree below.
425    let result = unsafe { SetEntriesInAclW(1, &entry, std::ptr::null(), &mut acl) };
426    if result != ERROR_SUCCESS {
427        return Err(io::Error::from_raw_os_error(result as i32));
428    }
429    let _acl = WindowsLocalAllocation(acl.cast());
430    let wide: Vec<u16> = path.as_os_str().encode_wide().chain([0]).collect();
431    // SAFETY: `wide` is NUL terminated and `acl` remains allocated for the
432    // duration of this call. Owner and DACL are applied together to match the
433    // production current-user-only verifier.
434    let result = unsafe {
435        SetNamedSecurityInfoW(
436            wide.as_ptr(),
437            SE_FILE_OBJECT,
438            OWNER_SECURITY_INFORMATION
439                | DACL_SECURITY_INFORMATION
440                | PROTECTED_DACL_SECURITY_INFORMATION,
441            user.sid(),
442            std::ptr::null_mut(),
443            acl,
444            std::ptr::null(),
445        )
446    };
447    if result != ERROR_SUCCESS {
448        return Err(io::Error::from_raw_os_error(result as i32));
449    }
450    Ok(())
451}
452
453#[cfg(windows)]
454fn verify_windows_owner_only_handle(
455    handle: windows_sys::Win32::Foundation::HANDLE,
456) -> io::Result<()> {
457    use windows_sys::Win32::Foundation::ERROR_SUCCESS;
458    use windows_sys::Win32::Security::Authorization::{
459        EXPLICIT_ACCESS_W, GRANT_ACCESS, GetExplicitEntriesFromAclW, GetSecurityInfo,
460        SE_FILE_OBJECT, SET_ACCESS, TRUSTEE_IS_SID,
461    };
462    use windows_sys::Win32::Security::{
463        ACL, DACL_SECURITY_INFORMATION, EqualSid, OWNER_SECURITY_INFORMATION, PSECURITY_DESCRIPTOR,
464        PSID,
465    };
466    use windows_sys::Win32::Storage::FileSystem::FILE_ALL_ACCESS;
467
468    let user = CurrentWindowsUser::open()?;
469    let mut owner: PSID = std::ptr::null_mut();
470    let mut dacl: *mut ACL = std::ptr::null_mut();
471    let mut descriptor: PSECURITY_DESCRIPTOR = std::ptr::null_mut();
472    // SAFETY: the opened file handle remains valid and all output pointers are
473    // writable. Windows allocates `descriptor`, released below.
474    let result = unsafe {
475        GetSecurityInfo(
476            handle,
477            SE_FILE_OBJECT,
478            OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
479            &mut owner,
480            std::ptr::null_mut(),
481            &mut dacl,
482            std::ptr::null_mut(),
483            &mut descriptor,
484        )
485    };
486    if result != ERROR_SUCCESS {
487        return Err(io::Error::from_raw_os_error(result as i32));
488    }
489    let _descriptor = WindowsLocalAllocation(descriptor.cast());
490    // SAFETY: `owner` is non-null; `user.sid()` is owned by `user`.
491    if owner.is_null() || unsafe { EqualSid(owner, user.sid()) } == 0 {
492        return Err(io::Error::new(
493            io::ErrorKind::PermissionDenied,
494            "Codewhale-owned credential file owner is not the current user",
495        ));
496    }
497    if dacl.is_null() {
498        return Err(io::Error::new(
499            io::ErrorKind::PermissionDenied,
500            "Codewhale-owned credential file must have an owner-only DACL",
501        ));
502    }
503    let mut count = 0;
504    let mut entries: *mut EXPLICIT_ACCESS_W = std::ptr::null_mut();
505    // SAFETY: `dacl` is owned by the live security descriptor; Windows
506    // allocates the returned entries, released below.
507    let result = unsafe { GetExplicitEntriesFromAclW(dacl, &mut count, &mut entries) };
508    if result != ERROR_SUCCESS {
509        return Err(io::Error::from_raw_os_error(result as i32));
510    }
511    let _entries = WindowsLocalAllocation(entries.cast());
512    if count != 1 || entries.is_null() {
513        return Err(io::Error::new(
514            io::ErrorKind::PermissionDenied,
515            "Codewhale-owned credential file DACL must grant only one user",
516        ));
517    }
518    // SAFETY: `count == 1` proves the first returned entry is initialized.
519    let entry = unsafe { &*entries };
520    let trustee_sid: PSID = entry.Trustee.ptstrName.cast();
521    // SAFETY: form and null checked in this expression; sid owned by `user`.
522    let current_user_only = entry.Trustee.TrusteeForm == TRUSTEE_IS_SID
523        && !trustee_sid.is_null()
524        && unsafe { EqualSid(trustee_sid, user.sid()) } != 0
525        && matches!(entry.grfAccessMode, SET_ACCESS | GRANT_ACCESS)
526        && entry.grfAccessPermissions == FILE_ALL_ACCESS;
527    if !current_user_only {
528        return Err(io::Error::new(
529            io::ErrorKind::PermissionDenied,
530            "Codewhale-owned credential file DACL is not current-user-only",
531        ));
532    }
533    Ok(())
534}
535
536#[cfg(windows)]
537struct CurrentWindowsUser {
538    token: windows_sys::Win32::Foundation::HANDLE,
539    token_info: Vec<usize>,
540}
541
542#[cfg(windows)]
543impl CurrentWindowsUser {
544    fn open() -> io::Result<Self> {
545        use windows_sys::Win32::Foundation::{GetLastError, HANDLE};
546        use windows_sys::Win32::Security::{
547            GetTokenInformation, TOKEN_QUERY, TOKEN_USER, TokenUser,
548        };
549        use windows_sys::Win32::System::Threading::{GetCurrentProcess, OpenProcessToken};
550
551        let mut token: HANDLE = std::ptr::null_mut();
552        // SAFETY: the pseudo-process handle is valid and `token` is writable.
553        if unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token) } == 0 {
554            return Err(io::Error::last_os_error());
555        }
556        let mut needed = 0;
557        // SAFETY: the null buffer/zero length call obtains the required size.
558        let _ =
559            unsafe { GetTokenInformation(token, TokenUser, std::ptr::null_mut(), 0, &mut needed) };
560        if needed == 0 {
561            // SAFETY: reads thread-local error state only.
562            let error = io::Error::from_raw_os_error(unsafe { GetLastError() } as i32);
563            // SAFETY: `token` is owned here and not stored on this path.
564            unsafe { windows_sys::Win32::Foundation::CloseHandle(token) };
565            return Err(error);
566        }
567        let words = (needed as usize).div_ceil(std::mem::size_of::<usize>());
568        let mut token_info = vec![0usize; words];
569        // SAFETY: the word buffer is aligned and contains at least `needed`
570        // writable bytes; `token` remains open.
571        if unsafe {
572            GetTokenInformation(
573                token,
574                TokenUser,
575                token_info.as_mut_ptr().cast(),
576                needed,
577                &mut needed,
578            )
579        } == 0
580        {
581            let error = io::Error::last_os_error();
582            // SAFETY: `token` is owned here and not stored on this path.
583            unsafe { windows_sys::Win32::Foundation::CloseHandle(token) };
584            return Err(error);
585        }
586        // SAFETY: initialized by GetTokenInformation; buffer outlives use.
587        let user = unsafe { &*token_info.as_ptr().cast::<TOKEN_USER>() };
588        if user.User.Sid.is_null() {
589            // SAFETY: `token` is owned here and not stored on this path.
590            unsafe { windows_sys::Win32::Foundation::CloseHandle(token) };
591            return Err(io::Error::new(
592                io::ErrorKind::InvalidData,
593                "current Windows user token has no SID",
594            ));
595        }
596        Ok(Self { token, token_info })
597    }
598
599    fn sid(&self) -> windows_sys::Win32::Security::PSID {
600        use windows_sys::Win32::Security::TOKEN_USER;
601        // SAFETY: `token_info` is aligned, initialized by GetTokenInformation,
602        // and remains owned by `self` while the returned SID is used.
603        unsafe { (*self.token_info.as_ptr().cast::<TOKEN_USER>()).User.Sid }
604    }
605}
606
607#[cfg(windows)]
608impl Drop for CurrentWindowsUser {
609    fn drop(&mut self) {
610        // SAFETY: `token` is owned by this guard and closed exactly once.
611        unsafe { windows_sys::Win32::Foundation::CloseHandle(self.token) };
612    }
613}
614
615#[cfg(windows)]
616struct WindowsLocalAllocation(*mut core::ffi::c_void);
617
618#[cfg(windows)]
619impl Drop for WindowsLocalAllocation {
620    fn drop(&mut self) {
621        if !self.0.is_null() {
622            // SAFETY: Windows returned this allocation to a caller documented
623            // to release it with LocalFree; the guard frees it exactly once.
624            unsafe { windows_sys::Win32::Foundation::LocalFree(self.0) };
625        }
626    }
627}
628
629#[cfg(windows)]
630fn reject_windows_reparse_components(path: &Path) -> io::Result<()> {
631    use std::os::windows::fs::MetadataExt;
632    use windows_sys::Win32::Storage::FileSystem::FILE_ATTRIBUTE_REPARSE_POINT;
633
634    let mut current = std::path::PathBuf::new();
635    for component in path.components() {
636        current.push(component.as_os_str());
637        if matches!(
638            component,
639            std::path::Component::Prefix(_) | std::path::Component::RootDir
640        ) {
641            continue;
642        }
643        let metadata = std::fs::symlink_metadata(&current)?;
644        if metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0 {
645            return Err(io::Error::new(
646                io::ErrorKind::PermissionDenied,
647                format!(
648                    "external credential path contains reparse point {}",
649                    codewhale_config::quote_os_path(&current)
650                ),
651            ));
652        }
653    }
654    Ok(())
655}
656
657#[cfg(not(any(unix, windows)))]
658fn open_secure_regular_file(_path: &Path, _require_owner_only: bool) -> io::Result<File> {
659    Err(io::Error::new(
660        io::ErrorKind::Unsupported,
661        "secure external credential reads are unsupported on this platform",
662    ))
663}
664
665#[cfg(any(test, feature = "test-support"))]
666pub fn reset_side_effect_trap() {
667    SIDE_EFFECT_TRAP.with(|trap| trap.set([0; 5]));
668}
669
670#[cfg(any(test, feature = "test-support"))]
671#[must_use]
672pub fn side_effect_trap_counts() -> (usize, usize) {
673    SIDE_EFFECT_TRAP.with(|trap| {
674        let counts = trap.get();
675        (counts[0], counts[1])
676    })
677}
678
679#[cfg(any(test, feature = "test-support"))]
680#[must_use]
681pub fn complete_side_effect_trap_counts() -> (usize, usize, usize, usize, usize) {
682    SIDE_EFFECT_TRAP.with(|trap| {
683        let counts = trap.get();
684        (counts[0], counts[1], counts[2], counts[3], counts[4])
685    })
686}
687
688#[cfg(any(test, feature = "test-support"))]
689pub fn record_owned_credential_write() {
690    increment_side_effect(2);
691}
692
693#[cfg(any(test, feature = "test-support"))]
694pub fn record_oauth_refresh() {
695    increment_side_effect(3);
696}
697
698#[cfg(any(test, feature = "test-support"))]
699pub fn record_oauth_network() {
700    increment_side_effect(4);
701}
702
703#[cfg(test)]
704mod tests {
705    use super::*;
706    use codewhale_config::{ExternalCredentialConsentToml, ExternalCredentialSource, ProviderKind};
707
708    fn grant(path: &Path) -> ExternalCredentialReadGrant {
709        ExternalCredentialConsentToml::read_only(
710            ProviderKind::OpenaiCodex,
711            ExternalCredentialSource::CodexCli,
712            path.to_path_buf(),
713        )
714        .read_grant(
715            ProviderKind::OpenaiCodex,
716            ExternalCredentialSource::CodexCli,
717            path,
718        )
719        .expect("test grant")
720    }
721
722    #[test]
723    fn secure_read_accepts_one_bounded_regular_file() {
724        let _env = crate::test_support::lock_test_env();
725        let dir = tempfile::tempdir().expect("tempdir");
726        let path = dir
727            .path()
728            .canonicalize()
729            .expect("canonical temp root")
730            .join("auth.json");
731        std::fs::write(&path, "{\"token\":\"ok\"}").expect("fixture");
732        assert_eq!(
733            read_to_string(&grant(&path))
734                .expect("secure read")
735                .as_deref(),
736            Some("{\"token\":\"ok\"}")
737        );
738    }
739
740    #[cfg(unix)]
741    #[test]
742    fn secure_read_rejects_leaf_and_parent_symlinks_and_non_regular_files() {
743        let _env = crate::test_support::lock_test_env();
744        use std::os::unix::fs::symlink;
745
746        let dir = tempfile::tempdir().expect("tempdir");
747        let root = dir.path().canonicalize().expect("canonical temp root");
748        let real_dir = root.join("real");
749        std::fs::create_dir(&real_dir).expect("real dir");
750        let real = real_dir.join("auth.json");
751        std::fs::write(&real, "secret").expect("fixture");
752
753        let leaf = root.join("leaf.json");
754        symlink(&real, &leaf).expect("leaf symlink");
755        assert!(read_to_string(&grant(&leaf)).is_err());
756
757        let parent = root.join("linked-parent");
758        symlink(&real_dir, &parent).expect("parent symlink");
759        assert!(read_to_string(&grant(&parent.join("auth.json"))).is_err());
760
761        assert!(read_to_string(&grant(&real_dir)).is_err());
762    }
763
764    #[cfg(unix)]
765    #[test]
766    fn secure_read_rejects_a_leaf_swapped_after_grant_before_open() {
767        let _env = crate::test_support::lock_test_env();
768        use std::os::unix::fs::symlink;
769
770        let dir = tempfile::tempdir().expect("tempdir");
771        let root = dir.path().canonicalize().expect("canonical temp root");
772        let path = root.join("auth.json");
773        let moved = root.join("auth-before-swap.json");
774        let attacker = root.join("attacker.json");
775        std::fs::write(&path, "owner-a").expect("owner fixture");
776        std::fs::write(&attacker, "attacker").expect("attacker fixture");
777        let grant = grant(&path);
778        let hook_path = path.clone();
779        BEFORE_LEAF_OPEN_HOOK.with(|hook| {
780            *hook.borrow_mut() = Some(Box::new(move || {
781                std::fs::rename(&hook_path, &moved).expect("move original");
782                symlink(&attacker, &hook_path).expect("swap leaf to symlink");
783            }));
784        });
785        assert!(
786            read_to_string(&grant).is_err(),
787            "a swap to a symlink must fail before any bytes are read"
788        );
789    }
790
791    #[test]
792    fn secure_read_rejects_oversized_regular_file() {
793        let _env = crate::test_support::lock_test_env();
794        let dir = tempfile::tempdir().expect("tempdir");
795        let path = dir
796            .path()
797            .canonicalize()
798            .expect("canonical temp root")
799            .join("oversized.json");
800        let file = File::create(&path).expect("fixture");
801        file.set_len(MAX_EXTERNAL_CREDENTIAL_BYTES + 1)
802            .expect("oversize fixture");
803        let error = read_to_string(&grant(&path)).expect_err("oversized file");
804        assert!(error.to_string().contains("safety limit"), "{error:#}");
805    }
806
807    #[cfg(unix)]
808    #[test]
809    fn owned_read_requires_owner_only_regular_file_and_never_follows_symlinks() {
810        use std::os::unix::fs::{PermissionsExt as _, symlink};
811
812        let _env = crate::test_support::lock_test_env();
813        let dir = tempfile::tempdir().expect("tempdir");
814        let root = dir.path().canonicalize().expect("canonical temp root");
815        let path = root.join("owned.json");
816        std::fs::write(&path, "owned-secret").expect("fixture");
817        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644))
818            .expect("loose mode");
819        assert!(
820            read_codewhale_owned_to_string(&path).is_err(),
821            "group/other-readable owned credentials must fail closed"
822        );
823
824        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600))
825            .expect("owner-only mode");
826        assert_eq!(
827            read_codewhale_owned_to_string(&path)
828                .expect("secure owned read")
829                .as_deref(),
830            Some("owned-secret")
831        );
832
833        let hardlink = root.join("owned-hardlink.json");
834        std::fs::hard_link(&path, &hardlink).expect("hardlink fixture");
835        assert!(
836            read_codewhale_owned_to_string(&path).is_err(),
837            "owned reads must reject multiply-linked files"
838        );
839        std::fs::remove_file(hardlink).expect("remove hardlink fixture");
840
841        let link = root.join("owned-link.json");
842        symlink(&path, &link).expect("symlink");
843        assert!(read_codewhale_owned_to_string(&link).is_err());
844    }
845
846    #[cfg(unix)]
847    #[test]
848    fn owned_read_is_bounded() {
849        use std::os::unix::fs::PermissionsExt as _;
850
851        let _env = crate::test_support::lock_test_env();
852        let dir = tempfile::tempdir().expect("tempdir");
853        let path = dir
854            .path()
855            .canonicalize()
856            .unwrap()
857            .join("oversized-owned.json");
858        let file = File::create(&path).expect("fixture");
859        file.set_len(MAX_EXTERNAL_CREDENTIAL_BYTES + 1).unwrap();
860        file.set_permissions(std::fs::Permissions::from_mode(0o600))
861            .unwrap();
862        let error = read_codewhale_owned_to_string(&path).expect_err("oversized owned file");
863        assert!(error.to_string().contains("safety limit"), "{error:#}");
864    }
865
866    #[cfg(windows)]
867    fn secured_owned_windows_fixture(contents: &[u8]) -> (tempfile::TempDir, std::path::PathBuf) {
868        let dir = tempfile::tempdir().expect("tempdir");
869        secure_codewhale_owned_windows_path(dir.path(), true).expect("owner-only directory");
870        let path = dir.path().join("owned.json");
871        std::fs::write(&path, contents).expect("fixture");
872        secure_codewhale_owned_windows_path(&path, false).expect("owner-only file");
873        (dir, path)
874    }
875
876    #[cfg(windows)]
877    #[test]
878    fn owned_read_accepts_current_user_only_dacl_with_opened_path_spelling() {
879        let _env = crate::test_support::lock_test_env();
880        let (_dir, path) = secured_owned_windows_fixture(b"owned-secret");
881        assert_eq!(
882            read_codewhale_owned_to_string(&path)
883                .expect("secure owned read")
884                .as_deref(),
885            Some("owned-secret")
886        );
887    }
888
889    #[cfg(windows)]
890    #[test]
891    fn owned_read_rejects_hardlinks_on_windows() {
892        let _env = crate::test_support::lock_test_env();
893        let (dir, path) = secured_owned_windows_fixture(b"owned-secret");
894        let hardlink = dir.path().join("owned-hardlink.json");
895        std::fs::hard_link(&path, &hardlink).expect("hardlink fixture");
896        assert!(
897            read_codewhale_owned_to_string(&path).is_err(),
898            "owned reads must reject multiply-linked files"
899        );
900        std::fs::remove_file(hardlink).expect("remove hardlink fixture");
901    }
902
903    #[cfg(windows)]
904    #[test]
905    fn owned_read_is_bounded_on_windows() {
906        let _env = crate::test_support::lock_test_env();
907        let (_dir, path) = secured_owned_windows_fixture(b"owned-secret");
908        let file = File::options()
909            .write(true)
910            .open(&path)
911            .expect("reopen fixture");
912        file.set_len(MAX_EXTERNAL_CREDENTIAL_BYTES + 1)
913            .expect("oversize fixture");
914        let error = read_codewhale_owned_to_string(&path).expect_err("oversized owned file");
915        assert!(error.to_string().contains("safety limit"), "{error:#}");
916    }
917
918    #[cfg(windows)]
919    #[test]
920    fn owned_read_rejects_leaf_reparse_points_on_windows() {
921        let _env = crate::test_support::lock_test_env();
922        let (dir, path) = secured_owned_windows_fixture(b"owned-secret");
923        let link = dir.path().join("owned-link.json");
924        if std::os::windows::fs::symlink_file(&path, &link).is_ok() {
925            assert!(
926                read_codewhale_owned_to_string(&link).is_err(),
927                "owned reads must reject leaf reparse points"
928            );
929        }
930    }
931
932    #[cfg(windows)]
933    #[test]
934    fn windows_handle_path_comparison_is_lossless_and_fails_closed() {
935        use std::ffi::OsString;
936        use std::os::windows::ffi::OsStringExt as _;
937        use std::path::PathBuf;
938
939        let expected = PathBuf::from(r"C:\Users\Alice\credential.json");
940        let kernel = PathBuf::from(r"\\?\C:\Users\Alice\credential.json");
941        assert_eq!(
942            normalize_windows_path_for_comparison(&expected).unwrap(),
943            normalize_windows_path_for_comparison(&kernel).unwrap()
944        );
945        assert_eq!(
946            normalize_windows_path_for_comparison(Path::new(r"C:\Users\Alice\A\credential.json"))
947                .unwrap(),
948            normalize_windows_path_for_comparison(Path::new(r"C:\Users\Alice\a\credential.json"))
949                .unwrap(),
950            "Windows credential path identity must compare case-insensitively"
951        );
952
953        let invalid = PathBuf::from(OsString::from_wide(&[
954            b'C' as u16,
955            b':' as u16,
956            b'\\' as u16,
957            0xd800,
958        ]));
959        assert!(normalize_windows_path_for_comparison(&invalid).is_err());
960    }
961}