Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

30.8 KB
Raw Blame
//! OS permission checks -- `src-tauri/src/permissions.rs`, without Tauri.
//!
//! macOS is the only platform that gates onboarding on these. Windows and
//! Linux report [`OSPermissionStatus::NotNeeded`] for every row, matching
//! `do_permissions_check` over there.
//!
//! ## Detection, and why it is cheap
//!
//! Every check here is a preflight API: `CGPreflightScreenCaptureAccess` for
//! screen recording, `AXIsProcessTrusted` for accessibility, and
//! `AVCaptureDevice.authorizationStatus(for:)` for camera / microphone. None
//! of them prompt, and none of them materialise anything. `SCShareableContent`
//! must never be polled -- the Tauri app once polled it for permission state at
//! 250ms and leaked the whole window/app/display graph per call (~137KB, issue
//! #2023, the 82GB incident). It is only asked once a screen-recording
//! preflight passes, to confirm the grant is real, and a success is cached
//! (see [`screen_capture`]).
//!
//! ## Status model
//!
//! The AV authorization statuses are surfaced distinctly the way the Tauri
//! app surfaces them: `notDetermined` maps to [`OSPermissionStatus::NotDetermined`]
//! (the "Grant" button -- requesting will show the system prompt), while
//! `denied` and `restricted` both map to [`OSPermissionStatus::Denied`] (the
//! "Open Settings" button -- the system prompt will never appear again).
//! Screen recording and accessibility only expose a boolean, so an
//! un-granted one is `NotDetermined` until a request cycle for it has
//! actually failed -- the per-permission `attempted` flags in
//! [`classify`] are this module's version of Tauri's `initial_check`.

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OSPermission {
    ScreenRecording,
    Accessibility,
    Microphone,
    Camera,
}

impl OSPermission {
    pub const ALL: &'static [Self] = &[
        Self::ScreenRecording,
        Self::Accessibility,
        Self::Microphone,
        Self::Camera,
    ];

    pub fn label(self) -> &'static str {
        match self {
            Self::ScreenRecording => "Screen Recording",
            Self::Accessibility => "Accessibility",
            Self::Microphone => "Microphone",
            Self::Camera => "Camera",
        }
    }

    /// Screen recording and accessibility gate the app; mic and camera are
    /// optional. Same split as the Tauri app's `necessary_granted`.
    pub fn required(self) -> bool {
        matches!(self, Self::ScreenRecording | Self::Accessibility)
    }

    /// The exact System Settings pane, verbatim from
    /// `macos_permission_settings_url` in the Tauri app.
    #[cfg(any(target_os = "macos", test))]
    fn settings_url(self) -> &'static str {
        match self {
            Self::ScreenRecording => {
                "x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture"
            }
            Self::Accessibility => {
                "x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility"
            }
            Self::Microphone => {
                "x-apple.systempreferences:com.apple.preference.security?Privacy_Microphone"
            }
            Self::Camera => {
                "x-apple.systempreferences:com.apple.preference.security?Privacy_Camera"
            }
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OSPermissionStatus {
    /// This platform does not require this permission.
    NotNeeded,
    /// The user has neither granted nor denied it -- requesting will prompt.
    /// (Tauri calls this `Empty`.)
    NotDetermined,
    Granted,
    /// Denied or restricted -- the system prompt will not appear again, only
    /// System Settings can change it.
    Denied,
}

impl OSPermissionStatus {
    pub fn permitted(self) -> bool {
        matches!(self, Self::Granted | Self::NotNeeded)
    }
}

/// `AVAuthorizationStatus`, surfaced whole so `restricted` and `denied` stay
/// distinguishable up to the classification step.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MediaAuthorization {
    NotDetermined,
    Restricted,
    Denied,
    Authorized,
}

impl MediaAuthorization {
    /// The Tauri mapping: `notDetermined` -> prompt-able, `authorized` ->
    /// granted, `denied` / `restricted` -> Settings-only.
    pub fn status(self) -> OSPermissionStatus {
        match self {
            Self::Authorized => OSPermissionStatus::Granted,
            Self::NotDetermined => OSPermissionStatus::NotDetermined,
            Self::Denied | Self::Restricted => OSPermissionStatus::Denied,
        }
    }
}

/// One preflight sweep, before classification.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RawPermissions {
    pub screen_granted: bool,
    pub accessibility_granted: bool,
    pub microphone: MediaAuthorization,
    pub camera: MediaAuthorization,
}

/// Which boolean-API permissions have been through a failed request cycle,
/// flipping them from "Grant" to "Open Settings". Camera and microphone do
/// not need this: AV reports `notDetermined` vs `denied` directly.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct AttemptedFlags {
    pub screen: bool,
    pub accessibility: bool,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct OSPermissionsCheck {
    pub screen_recording: OSPermissionStatus,
    pub accessibility: OSPermissionStatus,
    pub microphone: OSPermissionStatus,
    pub camera: OSPermissionStatus,
}

impl OSPermissionsCheck {
    pub fn get(self, permission: OSPermission) -> OSPermissionStatus {
        match permission {
            OSPermission::ScreenRecording => self.screen_recording,
            OSPermission::Accessibility => self.accessibility,
            OSPermission::Microphone => self.microphone,
            OSPermission::Camera => self.camera,
        }
    }

    pub fn necessary_granted(self) -> bool {
        self.screen_recording.permitted() && self.accessibility.permitted()
    }

    pub fn all_permitted(self) -> bool {
        OSPermission::ALL
            .iter()
            .all(|&permission| self.get(permission).permitted())
    }
}

/// Pure classification -- the whole status state machine, unit-tested below.
/// `None` is a platform that needs nothing.
pub fn classify(raw: Option<RawPermissions>, attempted: AttemptedFlags) -> OSPermissionsCheck {
    let Some(raw) = raw else {
        return OSPermissionsCheck {
            screen_recording: OSPermissionStatus::NotNeeded,
            accessibility: OSPermissionStatus::NotNeeded,
            microphone: OSPermissionStatus::NotNeeded,
            camera: OSPermissionStatus::NotNeeded,
        };
    };
    OSPermissionsCheck {
        screen_recording: bool_status(raw.screen_granted, attempted.screen),
        accessibility: bool_status(raw.accessibility_granted, attempted.accessibility),
        microphone: raw.microphone.status(),
        camera: raw.camera.status(),
    }
}

fn bool_status(granted: bool, attempted: bool) -> OSPermissionStatus {
    if granted {
        OSPermissionStatus::Granted
    } else if attempted {
        OSPermissionStatus::Denied
    } else {
        OSPermissionStatus::NotDetermined
    }
}

/// The live preflight sweep. Thread-safe (`main.rs` runs the startup gate off
/// the main thread on the strength of this), never prompts, ~30ms of XPC on
/// a cold TCC cache.
pub fn check_raw() -> Option<RawPermissions> {
    #[cfg(target_os = "macos")]
    {
        Some(macos::check_raw())
    }
    #[cfg(not(target_os = "macos"))]
    {
        None
    }
}

/// [`check_raw`] without the ScreenCaptureKit confirmation of a screen
/// recording grant, for pollers that only need camera / microphone status or
/// watch for a grant to flip: it never queries `SCShareableContent`.
pub fn check_raw_preflight() -> Option<RawPermissions> {
    #[cfg(target_os = "macos")]
    {
        Some(macos::check_raw_preflight())
    }
    #[cfg(not(target_os = "macos"))]
    {
        None
    }
}

/// The startup / tray gate: screen recording + accessibility.
pub fn necessary_granted() -> bool {
    match check_raw() {
        Some(raw) => raw.screen_granted && raw.accessibility_granted,
        None => true,
    }
}

/// Show the system prompt. For screen recording and accessibility this only
/// ever works once per TCC reset -- callers own the "wait, then fall back to
/// System Settings" cycle (the onboarding window's verify task, mirroring
/// `request_permission` in the Tauri app). For camera / microphone the AV
/// request runs on its own thread and the system dialog outlives this call;
/// the caller's poll observes the answer.
pub fn request_permission(permission: OSPermission) {
    #[cfg(target_os = "macos")]
    macos::request(permission);
    #[cfg(not(target_os = "macos"))]
    let _ = permission;
}

#[cfg(any(target_os = "macos", test))]
type PendingMediaRequest =
    futures_util::future::Shared<futures_util::future::BoxFuture<'static, Result<bool, String>>>;

#[cfg(any(target_os = "macos", test))]
fn shared_media_request(
    slot: &std::sync::Mutex<Option<PendingMediaRequest>>,
    request: impl FnOnce() -> Result<PendingMediaRequest, String>,
) -> Result<PendingMediaRequest, String> {
    use futures_util::FutureExt as _;
    let mut slot = slot
        .lock()
        .map_err(|_| "Media permission request state is unavailable".to_string())?;
    if let Some(pending) = slot.as_ref()
        && pending.clone().now_or_never().is_none()
    {
        return Ok(pending.clone());
    }
    let pending = request()?;
    *slot = Some(pending.clone());
    Ok(pending)
}

#[cfg(any(target_os = "macos", test))]
async fn media_permission_result(
    permission: OSPermission,
    status: MediaAuthorization,
    request: impl std::future::Future<Output = Result<bool, String>>,
) -> Result<(), String> {
    match status {
        MediaAuthorization::Authorized => Ok(()),
        MediaAuthorization::NotDetermined if request.await? => Ok(()),
        MediaAuthorization::NotDetermined
        | MediaAuthorization::Denied
        | MediaAuthorization::Restricted => Err(format!(
            "{} access is unavailable. Allow Cap in System Settings > Privacy & Security > {}, then select the device again.",
            permission.label(),
            permission.label()
        )),
    }
}

#[cfg(target_os = "macos")]
pub async fn ensure_capture_media_permission(permission: OSPermission) -> Result<(), String> {
    macos::ensure_capture_media_permission(permission).await
}

pub fn media_request_pending() -> bool {
    #[cfg(target_os = "macos")]
    return macos::media_request_pending();
    #[cfg(not(target_os = "macos"))]
    false
}

pub fn open_permission_settings(permission: OSPermission) {
    #[cfg(target_os = "macos")]
    {
        crate::platform::set_activation_policy(true);
        if let Err(error) = std::process::Command::new("open")
            .arg(permission.settings_url())
            .spawn()
        {
            tracing::warn!("opening permission settings failed: {error}");
        }
    }
    #[cfg(not(target_os = "macos"))]
    let _ = permission;
}

/// Relaunch the app -- the Tauri onboarding offers this after sending the
/// user to System Settings, because a fresh screen-recording or accessibility
/// grant often only takes effect in a new process. The replacement must wait
/// for shutdown: Tauri otherwise sees this process alive and exits without
/// starting a replacement.
pub fn relaunch(cx: &mut gpui::App) {
    let Ok(exe) = std::env::current_exe() else {
        tracing::error!("relaunch: current_exe unavailable");
        return;
    };

    if let Err(error) = relaunch_executable(&exe, cx) {
        tracing::error!("relaunch failed to spawn: {error}");
    }
}

pub(crate) fn relaunch_executable(
    exe: &std::path::Path,
    cx: &mut gpui::App,
) -> std::io::Result<()> {
    static REQUESTED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);

    let mut command = relaunch_command(exe, std::process::id());
    spawn_relaunch(&mut command, &REQUESTED, || crate::menus::quit(cx)).map(drop)
}

fn relaunch_command(exe: &std::path::Path, pid: u32) -> std::process::Command {
    #[cfg(target_os = "macos")]
    let bundle = exe
        .ancestors()
        .find(|path| path.extension().is_some_and(|ext| ext == "app"));
    #[cfg(not(target_os = "macos"))]
    let bundle: Option<&std::path::Path> = None;

    let (script, target) = match bundle {
        Some(bundle) => (
            r#"while kill -0 "$1" 2>/dev/null; do sleep 0.1; done; exec /usr/bin/open -n "$2""#,
            bundle,
        ),
        None => (
            r#"while kill -0 "$1" 2>/dev/null; do sleep 0.1; done; exec "$2""#,
            exe,
        ),
    };
    let mut command = std::process::Command::new("/bin/sh");
    command
        .args(["-c", script, "cap-relaunch"])
        .arg(pid.to_string())
        .arg(target);
    command
}

fn spawn_relaunch(
    command: &mut std::process::Command,
    requested: &std::sync::atomic::AtomicBool,
    quit: impl FnOnce(),
) -> std::io::Result<Option<std::process::Child>> {
    use std::sync::atomic::Ordering;

    if requested.swap(true, Ordering::AcqRel) {
        return Ok(None);
    }
    match command.spawn() {
        Ok(child) => {
            quit();
            Ok(Some(child))
        }
        Err(error) => {
            requested.store(false, Ordering::Release);
            Err(error)
        }
    }
}

#[cfg(target_os = "macos")]
mod screen_capture;

#[cfg(target_os = "macos")]
mod macos {
    use super::{MediaAuthorization, OSPermission, RawPermissions};

    #[link(name = "ApplicationServices", kind = "framework")]
    unsafe extern "C" {
        fn AXIsProcessTrusted() -> bool;
        fn AXIsProcessTrustedWithOptions(
            options: core_foundation::dictionary::CFDictionaryRef,
        ) -> bool;
    }

    #[link(name = "CoreGraphics", kind = "framework")]
    unsafe extern "C" {
        fn CGPreflightScreenCaptureAccess() -> bool;
        fn CGRequestScreenCaptureAccess() -> bool;
    }

    /// Preflight-only, wrapped in an autoreleasepool: the poll runs this on
    /// gpui's background threads, which have no ambient NSAutoreleasePool,
    /// and AVFoundation's status query autoreleases temporaries (the same
    /// leak class `do_permissions_check` in the Tauri app plugs the same way).
    pub fn check_raw() -> RawPermissions {
        let raw = check_raw_preflight();
        RawPermissions {
            screen_granted: super::screen_capture::available(raw.screen_granted),
            ..raw
        }
    }

    pub fn check_raw_preflight() -> RawPermissions {
        objc2::rc::autoreleasepool(|_| RawPermissions {
            screen_granted: unsafe { CGPreflightScreenCaptureAccess() },
            accessibility_granted: unsafe { AXIsProcessTrusted() },
            microphone: media_authorization(false),
            camera: media_authorization(true),
        })
    }

    pub fn request(permission: OSPermission) {
        match permission {
            // Main-thread, synchronous: the Tauri app routes both of these
            // through `run_on_main_thread`. The calls return immediately;
            // the TCC prompt itself is posted by the OS out of process.
            OSPermission::ScreenRecording => unsafe {
                let _ = CGRequestScreenCaptureAccess();
            },
            OSPermission::Accessibility => prompt_accessibility(),
            OSPermission::Microphone => request_media(false),
            OSPermission::Camera => request_media(true),
        }
    }

    fn prompt_accessibility() {
        use core_foundation::base::TCFType;
        use core_foundation::boolean::CFBoolean;
        use core_foundation::dictionary::CFDictionary;
        use core_foundation::string::CFString;

        let prompt_key = CFString::new("AXTrustedCheckOptionPrompt");
        let prompt_value = CFBoolean::true_value();
        let options =
            CFDictionary::from_CFType_pairs(&[(prompt_key.as_CFType(), prompt_value.as_CFType())]);
        unsafe {
            AXIsProcessTrustedWithOptions(options.as_concrete_TypeRef());
        }
    }

    fn media_authorization(camera: bool) -> MediaAuthorization {
        use cidre::av;

        let media = if camera {
            av::MediaType::video()
        } else {
            av::MediaType::audio()
        };
        match av::CaptureDevice::authorization_status_for_media_type(media) {
            Ok(av::AuthorizationStatus::Authorized) => MediaAuthorization::Authorized,
            Ok(av::AuthorizationStatus::NotDetermined) => MediaAuthorization::NotDetermined,
            Ok(av::AuthorizationStatus::Restricted) => MediaAuthorization::Restricted,
            Ok(av::AuthorizationStatus::Denied) => MediaAuthorization::Denied,
            Err(error) => {
                tracing::error!("querying AV permission status failed: {error}");
                MediaAuthorization::Denied
            }
        }
    }

    static CAMERA_REQUEST: std::sync::Mutex<Option<super::PendingMediaRequest>> =
        std::sync::Mutex::new(None);
    static MICROPHONE_REQUEST: std::sync::Mutex<Option<super::PendingMediaRequest>> =
        std::sync::Mutex::new(None);

    pub fn media_request_pending() -> bool {
        use futures_util::FutureExt as _;
        [&CAMERA_REQUEST, &MICROPHONE_REQUEST]
            .into_iter()
            .any(|slot| {
                slot.lock().is_ok_and(|slot| {
                    slot.as_ref()
                        .is_some_and(|pending| pending.clone().now_or_never().is_none())
                })
            })
    }

    fn shared_media_request(camera: bool) -> Result<super::PendingMediaRequest, String> {
        use futures_util::FutureExt as _;
        let slot = if camera {
            &CAMERA_REQUEST
        } else {
            &MICROPHONE_REQUEST
        };
        super::shared_media_request(slot, || {
            let answer = objc2::rc::autoreleasepool(|_| {
                use cidre::av;
                let media = if camera {
                    av::MediaType::video()
                } else {
                    av::MediaType::audio()
                };
                let (answer, mut completion) = cidre::blocks::comp1();
                av::CaptureDevice::request_access_for_media_type_ch(media, &mut completion)
                    .map_err(|error| format!("Could not request media access: {error}"))?;
                Ok::<_, String>(answer)
            })?;
            Ok(async move { Ok(answer.await) }.boxed().shared())
        })
    }

    pub async fn ensure_capture_media_permission(permission: OSPermission) -> Result<(), String> {
        let camera = match permission {
            OSPermission::Camera => true,
            OSPermission::Microphone => false,
            _ => {
                return Err("Only camera and microphone permissions can configure a device".into());
            }
        };
        let status = objc2::rc::autoreleasepool(|_| media_authorization(camera));
        super::media_permission_result(permission, status, async move {
            let granted = shared_media_request(camera)?.await?;
            Ok(granted
                && objc2::rc::autoreleasepool(|_| {
                    media_authorization(camera) == MediaAuthorization::Authorized
                }))
        })
        .await
    }

    fn request_media(camera: bool) {
        if let Err(error) = shared_media_request(camera) {
            tracing::error!("Media permission request failed: {error}");
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn relaunch_requests_quit_once_after_spawn_and_allows_retry_after_failure() {
        use std::{
            cell::Cell,
            sync::atomic::{AtomicBool, Ordering},
        };

        let requested = AtomicBool::new(false);
        let quits = Cell::new(0);
        assert!(
            spawn_relaunch(&mut std::process::Command::new(""), &requested, || {
                quits.set(quits.get() + 1);
            })
            .is_err()
        );
        assert!(!requested.load(Ordering::Acquire));
        assert_eq!(quits.get(), 0);

        let mut command = std::process::Command::new(std::env::current_exe().unwrap());
        command.arg("--list").stdout(std::process::Stdio::null());
        let mut child = spawn_relaunch(&mut command, &requested, || quits.set(quits.get() + 1))
            .unwrap()
            .unwrap();
        assert!(child.wait().unwrap().success());
        assert!(
            spawn_relaunch(&mut command, &requested, || quits.set(quits.get() + 1))
                .unwrap()
                .is_none()
        );
        assert_eq!(quits.get(), 1);
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn bundled_relaunch_passes_the_bundle_as_a_literal_argument() {
        let bundle = std::path::Path::new("/Applications/Cap ' \" $ app.app");
        let command = relaunch_command(&bundle.join("Contents/MacOS/cap-gpui"), 123);
        let args = command.get_args().collect::<Vec<_>>();
        assert_eq!(command.get_program(), "/bin/sh");
        assert_eq!(args[3], "123");
        assert_eq!(args[4], bundle.as_os_str());
        assert!(
            args[1]
                .to_str()
                .unwrap()
                .ends_with(r#"exec /usr/bin/open -n "$2""#)
        );
    }

    #[cfg(unix)]
    #[test]
    fn relaunch_waits_for_the_previous_process_and_handles_literal_paths() {
        use std::os::unix::fs::PermissionsExt;

        let nonce = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos();
        let root =
            std::env::temp_dir().join(format!("cap-gpui-relaunch-{}-{nonce}", std::process::id()));
        std::fs::create_dir_all(&root).unwrap();
        let executable = root.join("replacement ' \" $ program");
        let output = root.join("relaunched");
        std::fs::write(
            &executable,
            b"#!/bin/sh\nprintf relaunched > \"$CAP_GPUI_RELAUNCH_TEST_OUTPUT\"\n",
        )
        .unwrap();
        std::fs::set_permissions(&executable, std::fs::Permissions::from_mode(0o700)).unwrap();

        let mut previous = std::process::Command::new("/bin/sh")
            .args(["-c", "read -r line"])
            .stdin(std::process::Stdio::piped())
            .spawn()
            .unwrap();
        let mut replacement = relaunch_command(&executable, previous.id())
            .env("CAP_GPUI_RELAUNCH_TEST_OUTPUT", &output)
            .spawn()
            .unwrap();
        std::thread::sleep(std::time::Duration::from_millis(400));
        assert!(replacement.try_wait().unwrap().is_none());
        assert!(!output.exists());
        drop(previous.stdin.take());
        previous.wait().unwrap();
        assert!(replacement.wait().unwrap().success());
        assert_eq!(std::fs::read(&output).unwrap(), b"relaunched");
        std::fs::remove_dir_all(root).unwrap();
    }

    fn raw(
        screen: bool,
        ax: bool,
        mic: MediaAuthorization,
        camera: MediaAuthorization,
    ) -> Option<RawPermissions> {
        Some(RawPermissions {
            screen_granted: screen,
            accessibility_granted: ax,
            microphone: mic,
            camera,
        })
    }

    #[test]
    fn permitted_matches_granted_states() {
        assert!(OSPermissionStatus::Granted.permitted());
        assert!(OSPermissionStatus::NotNeeded.permitted());
        assert!(!OSPermissionStatus::NotDetermined.permitted());
        assert!(!OSPermissionStatus::Denied.permitted());
    }

    #[test]
    fn platform_without_permissions_is_all_not_needed() {
        let check = classify(None, AttemptedFlags::default());
        for &permission in OSPermission::ALL {
            assert_eq!(check.get(permission), OSPermissionStatus::NotNeeded);
        }
        assert!(check.necessary_granted());
        assert!(check.all_permitted());
    }

    #[test]
    fn media_statuses_surface_distinctly() {
        // notDetermined must stay promptable -- never "Denied" -- regardless
        // of any attempted flag (the bug the old `initial` flag had).
        let check = classify(
            raw(
                true,
                true,
                MediaAuthorization::NotDetermined,
                MediaAuthorization::Restricted,
            ),
            AttemptedFlags {
                screen: true,
                accessibility: true,
            },
        );
        assert_eq!(check.microphone, OSPermissionStatus::NotDetermined);
        assert_eq!(check.camera, OSPermissionStatus::Denied);

        assert_eq!(
            MediaAuthorization::Authorized.status(),
            OSPermissionStatus::Granted
        );
        assert_eq!(
            MediaAuthorization::Denied.status(),
            OSPermissionStatus::Denied
        );
    }

    #[test]
    fn boolean_permissions_flip_to_denied_only_after_an_attempt() {
        let fresh = classify(
            raw(
                false,
                false,
                MediaAuthorization::NotDetermined,
                MediaAuthorization::NotDetermined,
            ),
            AttemptedFlags::default(),
        );
        assert_eq!(fresh.screen_recording, OSPermissionStatus::NotDetermined);
        assert_eq!(fresh.accessibility, OSPermissionStatus::NotDetermined);

        let attempted = classify(
            raw(
                false,
                false,
                MediaAuthorization::NotDetermined,
                MediaAuthorization::NotDetermined,
            ),
            AttemptedFlags {
                screen: true,
                accessibility: false,
            },
        );
        assert_eq!(attempted.screen_recording, OSPermissionStatus::Denied);
        assert_eq!(attempted.accessibility, OSPermissionStatus::NotDetermined);
    }

    #[test]
    fn granted_beats_attempted() {
        let check = classify(
            raw(
                true,
                true,
                MediaAuthorization::Authorized,
                MediaAuthorization::Authorized,
            ),
            AttemptedFlags {
                screen: true,
                accessibility: true,
            },
        );
        assert!(check.all_permitted());
        assert!(check.necessary_granted());
    }

    #[test]
    fn necessary_ignores_optional_permissions() {
        let check = classify(
            raw(
                true,
                true,
                MediaAuthorization::Denied,
                MediaAuthorization::NotDetermined,
            ),
            AttemptedFlags::default(),
        );
        assert!(check.necessary_granted());
        assert!(!check.all_permitted());
    }

    #[test]
    fn settings_urls_match_the_tauri_privacy_panes() {
        assert_eq!(
            OSPermission::ScreenRecording.settings_url(),
            "x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture"
        );
        assert_eq!(
            OSPermission::Accessibility.settings_url(),
            "x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility"
        );
        assert_eq!(
            OSPermission::Microphone.settings_url(),
            "x-apple.systempreferences:com.apple.preference.security?Privacy_Microphone"
        );
        assert_eq!(
            OSPermission::Camera.settings_url(),
            "x-apple.systempreferences:com.apple.preference.security?Privacy_Camera"
        );
    }
}

#[cfg(test)]
mod capture_consent_tests {
    #[tokio::test]
    async fn grant_clicks_and_device_selection_share_one_pending_native_request() {
        use futures_util::FutureExt as _;
        let slot = std::sync::Mutex::new(None);
        let (send, receive) = tokio::sync::oneshot::channel();
        let grant_click = shared_media_request(&slot, || {
            Ok(
                async move { receive.await.map_err(|error| error.to_string()) }
                    .boxed()
                    .shared(),
            )
        })
        .unwrap();
        drop(grant_click);
        for _ in 0..100 {
            drop(
                shared_media_request(&slot, || panic!("A pending OS request must be shared"))
                    .unwrap(),
            );
        }
        let selection =
            shared_media_request(&slot, || panic!("Selection must join Grant request")).unwrap();
        send.send(true).unwrap();
        assert!(selection.await.unwrap());
        let fresh =
            shared_media_request(&slot, || Ok(async { Ok(false) }.boxed().shared())).unwrap();
        assert!(!fresh.await.unwrap());
    }

    #[tokio::test]
    async fn completed_unpolled_grant_is_not_reused_after_a_new_preflight() {
        use futures_util::FutureExt as _;
        let slot = std::sync::Mutex::new(None);
        let (send, receive) = tokio::sync::oneshot::channel();
        drop(
            shared_media_request(&slot, || {
                Ok(
                    async move { receive.await.map_err(|error| error.to_string()) }
                        .boxed()
                        .shared(),
                )
            })
            .unwrap(),
        );
        send.send(true).unwrap();
        let fresh =
            shared_media_request(&slot, || Ok(async { Ok(false) }.boxed().shared())).unwrap();
        assert!(!fresh.await.unwrap());
    }

    use super::*;

    #[tokio::test]
    async fn granted_or_denied_media_never_waits_for_a_new_prompt() {
        for permission in [OSPermission::Camera, OSPermission::Microphone] {
            for status in [
                MediaAuthorization::Authorized,
                MediaAuthorization::Denied,
                MediaAuthorization::Restricted,
            ] {
                let result = media_permission_result(permission, status, async {
                    panic!("Resolved authorization must not request consent again");
                })
                .await;
                assert_eq!(result.is_ok(), status == MediaAuthorization::Authorized);
                if let Err(error) = result {
                    assert!(error.contains(permission.label()));
                    assert!(error.contains("System Settings"));
                }
            }
        }
    }

    #[tokio::test]
    async fn undetermined_media_waits_for_the_actual_answer() {
        for permission in [OSPermission::Camera, OSPermission::Microphone] {
            let (send, receive) = tokio::sync::oneshot::channel();
            let wait =
                media_permission_result(permission, MediaAuthorization::NotDetermined, async {
                    receive.await.map_err(|error| error.to_string())
                });
            tokio::pin!(wait);
            assert!(futures_util::poll!(&mut wait).is_pending());
            send.send(true).unwrap();
            assert!(wait.await.is_ok());
            let denied =
                media_permission_result(permission, MediaAuthorization::NotDetermined, async {
                    Ok(false)
                })
                .await;
            assert!(denied.unwrap_err().contains(permission.label()));
        }
    }

    #[tokio::test]
    async fn request_failure_is_reported_without_claiming_authorization() {
        let result = media_permission_result(
            OSPermission::Camera,
            MediaAuthorization::NotDetermined,
            async { Err("native request failed".into()) },
        )
        .await;
        assert_eq!(result.unwrap_err(), "native request failed");
    }
}