Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions Sources/PermissionGuide/Permission.swift
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,9 @@ public enum Permission: Hashable, Sendable {
switch self {
case .fullDiskAccess:
// Opens files only Full Disk Access can (see PermissionGuideProbe.c). May keep
// failing until the app relaunches.
// failing until the app relaunches. With System Integrity Protection off those
// files open for every process, so the check says nothing.
if permissionguide_filesystem_protection_disabled() { return .unknown }
return permissionguide_full_disk_access() ? .granted : .notGranted
case .screenRecording:
// May keep reporting false until the app relaunches.
Expand Down Expand Up @@ -117,7 +119,8 @@ extension Permission: Identifiable {
public enum PermissionStatus: Sendable {
case granted
case notGranted
/// macOS offers no way to check this permission.
/// The permission can't be checked: macOS has no API for it, or (Full Disk Access)
/// System Integrity Protection is off.
case unknown
}

Expand Down
92 changes: 67 additions & 25 deletions Sources/PermissionGuide/PermissionManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,9 @@ public final class PermissionManager {

@ObservationIgnored private let guide = SettingsGuide()
@ObservationIgnored private var continuation: CheckedContinuation<PermissionResult, Never>?
@ObservationIgnored private var pendingCheck: (@MainActor () -> Bool)?
@ObservationIgnored private var pendingCheck: (@MainActor () async -> Bool)?
/// The `pendingCheck` call in flight, if any.
@ObservationIgnored private var pendingCheckTask: Task<Void, Never>?
@ObservationIgnored private var extensionQueries: Set<SystemExtension> = []
@ObservationIgnored private var lastExtensionQuery = Date.distantPast
/// Grants a fresh process has seen that this one can't until it relaunches.
Expand Down Expand Up @@ -105,9 +107,13 @@ public final class PermissionManager {
public func request(
_ permission: Permission,
dragging appURL: URL = Bundle.main.bundleURL,
named name: String? = nil,
icon: NSImage? = nil,
alreadyListed: Bool = false,
tint: NSColor = .controlAccentColor,
isGranted: (@MainActor () -> Bool)? = nil
isGranted: (@MainActor () async -> Bool)? = nil
) async -> PermissionResult {
let subject = SettingsGuide.Subject(url: appURL, name: name, icon: icon)
if case .backgroundItem(let plist) = permission {
let service = SMAppService.daemon(plistName: plist)
if service.status == .notRegistered || service.status == .notFound {
Expand All @@ -116,10 +122,10 @@ public final class PermissionManager {
if service.status != .requiresApproval { return .failed(error) }
}
}
return await guide(to: permission, dragging: appURL, tint: tint, isGranted: isGranted)
return await guide(to: permission, dragging: appURL, named: name, icon: icon, alreadyListed: alreadyListed, tint: tint, isGranted: isGranted)
}
guard case .systemExtension(let ext) = permission else {
return await guide(to: permission, dragging: appURL, tint: tint, isGranted: isGranted)
return await guide(to: permission, dragging: appURL, named: name, icon: icon, alreadyListed: alreadyListed, tint: tint, isGranted: isGranted)
}
if status(of: permission) == .granted { return .granted }

Expand All @@ -128,7 +134,7 @@ public final class PermissionManager {
guard let self, self.pending == permission else { return }
switch event {
case .needsUserApproval:
self.showGuide(for: permission, appURL: appURL, tint: tint, isGranted: isGranted)
self.showGuide(for: permission, subject: subject, alreadyListed: alreadyListed, tint: tint, canCheck: isGranted != nil)
case .activated:
self.set(.granted, for: permission)
self.finish(.granted)
Expand All @@ -144,26 +150,39 @@ public final class PermissionManager {
/// Opens System Settings at the permission's pane and walks the user through it,
/// without requesting anything from macOS.
///
/// For a privacy pane, the user drags `appURL` into the highlighted list. For a system
/// extension, the user turns on its switch; use this when your app submits its own
/// For a privacy pane, the user drags `appURL` into the highlighted list, or turns on
/// its switch there when `alreadyListed`. For a system extension, the user turns on
/// its switch; use this when your app submits its own
/// `OSSystemExtensionRequest` and gets `requestNeedsUserApproval`.
///
/// - Parameters:
/// - appURL: The bundle the user drags into System Settings. Pass a helper's URL when
/// a helper, not the main app, is the process that needs the permission.
/// - name: What the guide calls that bundle. Defaults to its name in Finder, which
/// for a system extension is its file name.
/// - icon: The icon the guide shows for it. Defaults to the bundle's own, which is a
/// generic one for a helper that ships without an icon.
/// - alreadyListed: Whether the privacy pane's list already holds the bundle,
/// switched off, so the user turns on its switch instead of dragging it in. macOS
/// lists some helpers itself once they ask for access, such as an Endpoint
/// Security extension in Full Disk Access.
/// - tint: Color of the highlight and sidecar border.
/// - isGranted: How to tell the permission was granted, for when the default check
/// can't see it (such as a helper's permissions). When neither this nor macOS can
/// report status, the sidecar shows a Done button instead.
/// can't see it (such as a helper's permissions). It can be `async`, to ask the
/// helper over IPC, and is called again once the last call has returned. When
/// neither this nor macOS can report status, the sidecar shows a Done button instead.
/// - Returns: How the guide ended. See `PermissionResult`.
@discardableResult
public func guide(
to permission: Permission,
dragging appURL: URL = Bundle.main.bundleURL,
named name: String? = nil,
icon: NSImage? = nil,
alreadyListed: Bool = false,
tint: NSColor = .controlAccentColor,
isGranted: (@MainActor () -> Bool)? = nil
isGranted: (@MainActor () async -> Bool)? = nil
) async -> PermissionResult {
if let isGranted, isGranted() { return .granted }
if let isGranted, await isGranted() { return .granted }
let isOwnApp = isGranted == nil && appURL == Bundle.main.bundleURL
if isOwnApp, status(of: permission) == .granted { return .granted }
// Granted earlier, but this process can't see it until it relaunches.
Expand All @@ -173,7 +192,8 @@ public final class PermissionManager {
}

begin(permission, isGranted: isGranted)
showGuide(for: permission, appURL: appURL, tint: tint, isGranted: isGranted)
let subject = SettingsGuide.Subject(url: appURL, name: name, icon: icon)
showGuide(for: permission, subject: subject, alreadyListed: alreadyListed, tint: tint, canCheck: isGranted != nil)
return await waitForGrant()
}

Expand All @@ -182,21 +202,18 @@ public final class PermissionManager {
finish(.cancelled)
}

private func begin(_ permission: Permission, isGranted: (@MainActor () -> Bool)?) {
private func begin(_ permission: Permission, isGranted: (@MainActor () async -> Bool)?) {
finish(.cancelled, activate: false)
pending = permission
pendingCheck = isGranted
}

private func showGuide(for permission: Permission, appURL: URL, tint: NSColor, isGranted: (@MainActor () -> Bool)?) {
let isOwnApp = appURL == Bundle.main.bundleURL
let canVerify = isGranted != nil || (isOwnApp && status(of: permission) != .unknown)
let mode: SettingsGuide.Mode = switch permission {
case .systemExtension, .backgroundItem: .toggle(permission, confirmManually: !canVerify)
default: .drag(permission, confirmManually: !canVerify)
}
private func showGuide(for permission: Permission, subject: SettingsGuide.Subject, alreadyListed: Bool, tint: NSColor, canCheck: Bool) {
let isOwnApp = subject.url == Bundle.main.bundleURL
let canVerify = canCheck || (isOwnApp && status(of: permission) != .unknown)
let mode = SettingsGuide.Mode(permission, alreadyListed: alreadyListed, confirmManually: !canVerify)
SystemSettings.open(permission.settingsURL)
guide.start(mode, appURL: appURL, tint: tint, relaunch: relaunchChoice)
guide.start(mode, subject: subject, tint: tint, relaunch: relaunchChoice)
}

private func waitForGrant() async -> PermissionResult {
Expand All @@ -211,15 +228,36 @@ public final class PermissionManager {
if statuses[permission] != status { statuses[permission] = status }
}

private func isPendingGranted(_ permission: Permission) -> Bool {
pendingCheck?() ?? (status(of: permission) == .granted)
private func isPendingGranted(_ permission: Permission) async -> Bool {
if let pendingCheck { return await pendingCheck() }
return status(of: permission) == .granted
}

/// Finishes the request once its permission is granted, unless System Settings'
/// "Quit & Reopen" alert is up (or likely about to be): the guide stays to walk the
/// user through it, and finishes when it closes (`relaunchDeferred`).
private func checkPending() {
guard let pending, isPendingGranted(pending) else {
guard let pending else {
probedGrantSince = nil
return
}
guard let pendingCheck else {
pendingChecked(pending, granted: status(of: pending) == .granted)
return
}
// One call at a time: an IPC round trip can outlast a poll.
guard pendingCheckTask == nil else { return }
pendingCheckTask = Task {
let granted = await pendingCheck()
// Cancelled when the request it was checking for finished.
guard !Task.isCancelled else { return }
pendingCheckTask = nil
pendingChecked(pending, granted: granted)
}
}

private func pendingChecked(_ pending: Permission, granted: Bool) {
guard granted else {
probedGrantSince = nil
return
}
Expand All @@ -243,7 +281,9 @@ public final class PermissionManager {
guard pending == permission, !isTerminating else { return }
await probe(force: true)?.value
guard pending == permission, !isTerminating else { return }
if isPendingGranted(permission) {
let granted = await isPendingGranted(permission)
guard pending == permission, !isTerminating else { return }
if granted {
finish(.granted)
} else if pendingCheck != nil || status(of: permission) != .unknown {
// It didn't go through after all (the user switched it back off), so
Expand Down Expand Up @@ -315,6 +355,8 @@ public final class PermissionManager {
guide.stop()
pending = nil
pendingCheck = nil
pendingCheckTask?.cancel()
pendingCheckTask = nil
probedGrantSince = nil
continuation?.resume(returning: result)
continuation = nil
Expand Down
84 changes: 57 additions & 27 deletions Sources/PermissionGuide/SettingsGuide.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,19 @@ final class SettingsGuide {
/// Drag the app into a privacy pane's list. `confirmManually` adds a Done button
/// for when the grant can't be detected.
case drag(Permission, confirmManually: Bool)
/// Switch on a system extension.
/// Turn on a switch: a system extension's, a background item's, or the one beside
/// an app a privacy pane already lists.
case toggle(Permission, confirmManually: Bool)

init(_ permission: Permission, alreadyListed: Bool, confirmManually: Bool) {
self = switch permission {
case .systemExtension, .backgroundItem: .toggle(permission, confirmManually: confirmManually)
default: alreadyListed
? .toggle(permission, confirmManually: confirmManually)
: .drag(permission, confirmManually: confirmManually)
}
}

var permission: Permission {
switch self {
case .drag(let p, _), .toggle(let p, _): p
Expand All @@ -21,6 +31,42 @@ final class SettingsGuide {
case .drag(_, let c), .toggle(_, let c): c
}
}

/// Whether the switch is in a sheet over the pane rather than in the pane's list.
var targetIsInSheet: Bool {
switch self {
case .toggle(.systemExtension, _), .toggle(.backgroundItem, _): true
case .drag, .toggle: false
}
}

/// The sidecar's instructions, where `subject` is what the guide calls the bundle.
func instructions(subject: String) -> (title: String, message: String) {
let name = permission.displayName
return switch self {
case .drag:
("Grant \(name)", "Drag this icon into the highlighted list in System Settings.")
case .toggle(.backgroundItem, _):
("Allow in the Background", "Turn on the switch next to \(subject) under Allow in the Background.")
case .toggle(.systemExtension(let ext), _):
("Allow \(ext.category.displayName)", "Turn on the switch next to \(name) in System Settings.")
case .toggle:
("Grant \(name)", "Turn on the switch next to \(subject) in the highlighted list in System Settings.")
}
}
}

/// The bundle being granted, and what the guide calls and draws it as.
struct Subject {
var url: URL
var name: String?
var icon: NSImage?

var displayName: String {
name ?? FileManager.default.displayName(atPath: url.path).replacingOccurrences(of: ".app", with: "")
}

var displayIcon: NSImage { icon ?? NSWorkspace.shared.icon(forFile: url.path) }
}

var onCancel: (() -> Void)?
Expand Down Expand Up @@ -53,34 +99,18 @@ final class SettingsGuide {
prompts.resume()
}

func start(_ mode: Mode, appURL: URL, tint: NSColor, relaunch: RelaunchChoice) {
func start(_ mode: Mode, subject: Subject, tint: NSColor, relaunch: RelaunchChoice) {
stop()
self.mode = mode
self.relaunch = relaunch
appName = FileManager.default.displayName(atPath: appURL.path).replacingOccurrences(of: ".app", with: "")
let icon = NSWorkspace.shared.icon(forFile: appURL.path)
let name = mode.permission.displayName

let sidecar: SidecarPanel
switch mode {
case .drag(_, let confirmManually):
sidecar = SidecarPanel(
title: "Grant \(name)",
message: "Drag this icon into the highlighted list in System Settings.",
icon: icon, dragURL: appURL, showsDone: confirmManually, tint: tint)
case .toggle(.backgroundItem, let confirmManually):
sidecar = SidecarPanel(
title: "Allow in the Background",
message: "Turn on the switch next to \(appName) under Allow in the Background.",
icon: icon, dragURL: nil, showsDone: confirmManually, tint: tint)
case .toggle(let permission, let confirmManually):
let kind = if case .systemExtension(let ext) = permission { ext.category.displayName } else { name }
sidecar = SidecarPanel(
title: "Allow \(kind)",
message: "Turn on the switch next to \(name) in System Settings.",
icon: icon, dragURL: nil, showsDone: confirmManually, tint: tint)
}
instructions = (sidecar.instructionTitle, sidecar.instructionMessage)
appName = subject.displayName
let appURL = subject.url
let icon = subject.displayIcon
instructions = mode.instructions(subject: appName)
let dragURL: URL? = if case .drag = mode { appURL } else { nil }
let sidecar = SidecarPanel(
title: instructions.title, message: instructions.message,
icon: icon, dragURL: dragURL, showsDone: mode.confirmManually, tint: tint)
sidecar.onCancel = { [weak self] in self?.onCancel?() }
sidecar.onDone = { [weak self] in self?.onDone?() }
sidecar.iconView.onDragChanged = { [weak self] dragging in
Expand Down Expand Up @@ -152,7 +182,7 @@ final class SettingsGuide {
let showsHighlight = switch phase {
case .prompt: true
case .afterAuthentication, .granted: false
case .instructions: if case .toggle = mode { sheet != nil } else { sheet == nil }
case .instructions: mode.targetIsInSheet ? sheet != nil : sheet == nil
}
let showsGhost = showsHighlight && prompt == nil && !isDragging
// Right after authenticating, keep the last text until the next prompt shows.
Expand Down
3 changes: 0 additions & 3 deletions Sources/PermissionGuide/SidecarPanel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -84,9 +84,6 @@ final class SidecarPanel: NSPanel {
setContentSize(size)
}

var instructionTitle: String { titleLabel.stringValue }
var instructionMessage: String { hint.stringValue }

/// Replaces the instructions, keeping the panel's top edge in place.
func show(title: String, message: String) {
titleLabel.stringValue = title
Expand Down
9 changes: 9 additions & 0 deletions Sources/PermissionGuideProbe/PermissionGuideProbe.c
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
#include <CoreGraphics/CoreGraphics.h>
#include <errno.h>
#include <signal.h>
#include <stdint.h>
#include <spawn.h>
#include <sys/wait.h>
#include <time.h>
Expand All @@ -20,6 +21,10 @@ extern char **environ;
// process, so TCC checks the app's grants afresh instead of inheriting the parent's.
int responsibility_spawnattrs_setdisclaim(posix_spawnattr_t *attrs, int disclaim) __attribute__((weak_import));

// libSystem SPI: 0 when the running system allows what `mask` names.
int csr_check(uint32_t mask) __attribute__((weak_import));
#define PK_CSR_ALLOW_UNRESTRICTED_FS (1 << 1)

static bool pk_probe_ran = false;

bool permissionguide_probe_linked(void) { return pk_probe_ran; }
Expand Down Expand Up @@ -47,6 +52,10 @@ bool permissionguide_full_disk_access(void) {
return false;
}

bool permissionguide_filesystem_protection_disabled(void) {
return csr_check != NULL && csr_check(PK_CSR_ALLOW_UNRESTRICTED_FS) == 0;
}

static bool pk_granted(const char *name) {
if (strcmp(name, "fullDiskAccess") == 0) return permissionguide_full_disk_access();
if (strcmp(name, "screenRecording") == 0) return CGPreflightScreenCaptureAccess();
Expand Down
5 changes: 5 additions & 0 deletions Sources/PermissionGuideProbe/include/PermissionGuideProbe.h
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,11 @@ bool permissionguide_probe_linked(void);
/// Never prompts and is safe on any thread. May keep reading false until the app relaunches.
bool permissionguide_full_disk_access(void);

/// Whether System Integrity Protection's filesystem protection is off. The files
/// `permissionguide_full_disk_access` opens are then readable by every process, so it
/// reads true whether or not Full Disk Access was granted.
bool permissionguide_filesystem_protection_disabled(void);

/// Launches `executable` as a probe with `PERMISSIONGUIDE_PROBE_ENV` set to `value`, as its
/// own responsible process so TCC checks the app's grants as a fresh launch would. Blocks
/// until it exits; kills it after `timeout` seconds. The exit status, or -1 when it didn't
Expand Down
Loading
Loading