Uninstall Mac apps with every file they leave behind, and see why each belongs. Free up space, fine-tune macOS, and set up Terminal.
Swift cache-cleanercleanerclideveloper-toolsdisk-cleanupdisk-spaceduplicate-finderhomebrewliquid-glassmac-cleanermacosmacos-appmacos-golden-gatemacos-tahoemacos-tweaksswiftswiftuiterminal-themesuninstalluninstaller
Check each item the helper moves in a folder only it can reach
Țugui Dragoș8ae4ccf55d60
diff --git a/Packages/PeelCore/Sources/PeelPrivileged/HelperInterface.swift b/Packages/PeelCore/Sources/PeelPrivileged/HelperInterface.swiftindex 72e38fdd..c0af3c44 100644--- a/Packages/PeelCore/Sources/PeelPrivileged/HelperInterface.swift+++ b/Packages/PeelCore/Sources/PeelPrivileged/HelperInterface.swift@@ -7,7 +7,7 @@ public enum HelperIdentity {public static let launchdPlistName = "com.tuguidragos.Peel.Helper.plist"/// Raise it whenever the helper changes, so Peel never works with a helper of another version. The helper/// refuses requests that carry any other version.- public static let protocolVersion = 20+ public static let protocolVersion = 21}/// The complete set of privileged operations. The helper validates every argument itself.diff --git a/Packages/PeelCore/Sources/PeelPrivileged/HelperLedger.swift b/Packages/PeelCore/Sources/PeelPrivileged/HelperLedger.swiftindex b6f5a5be..3a25b763 100644--- a/Packages/PeelCore/Sources/PeelPrivileged/HelperLedger.swift+++ b/Packages/PeelCore/Sources/PeelPrivileged/HelperLedger.swift@@ -43,11 +43,7 @@ public final class HelperLedger: Sendable {) {let folder = url.deletingLastPathComponent().path(percentEncoded: false)mkdir(folder, 0o700)- var info = stat()- guard- lstat(folder, &info) == 0, info.st_mode & S_IFMT == S_IFDIR,- info.st_uid == geteuid(), info.st_mode & 0o077 == 0- else { return nil }+ guard Self.isTheHelpersOwn(folder) else { return nil }self.url = urlself.maximumEntries = maximumEntriesself.flush = flush@@ -96,9 +92,11 @@ public final class HelperLedger: Sendable {_ folder: String,into trash: DirectoryHandle,givingTo user: uid_t,+ homeDirectory: (uid_t) -> String? = UserAuthorization.homeDirectory(of:),changingOwner: (_ folder: DirectoryHandle, _ entry: String?, _ owner: uid_t) -> Bool) -> Result<String?, POSIXError> {lock.withLock {+ recover(in: folder, homeDirectory: homeDirectory)switch OpenItem.at(folder) {case .failure(let error):return error.code == .ENOENT ? .success(nil) : .failure(error)@@ -117,7 +115,9 @@ public final class HelperLedger: Sendable {}}giveEntries(to: user)- let moved = TrashMover.move(item, into: trash)+ let names = TrashMover.finderNames(of: item.name)+ let moved = TrashMover.place(item.name, from: item.parent, in: trash, as: names)+ .map { (trash.path as NSString).appendingPathComponent($0) }switch moved {case .success: _ = inside.map { changingOwner($0, nil, user) }case .failure: giveEntries(to: geteuid())@@ -127,6 +127,45 @@ public final class HelperLedger: Sendable {}}+ /// Runs `body` with `Staging`, a folder inside the ledger's that only the helper can reach, under the ledger's+ /// lock, so Remove Peel never moves it while an item is on its way through. Nil when it can't be kept so.+ func whileStaging<T>(_ body: (DirectoryHandle) -> T) -> T? {+ Self.lock.withLock {+ let staging = url.deletingLastPathComponent().path(percentEncoded: false) + "/Staging"+ mkdir(staging, 0o700)+ guard Self.isTheHelpersOwn(staging), let handle = try? DirectoryHandle.at(staging).get() else { return nil }+ return body(handle)+ }+ }++ /// Moves what a move cut short left in `Staging` to the Trash of the account it was moving for.+ public static func recoverStaged(+ in folder: String = defaultFolder,+ homeDirectory: (uid_t) -> String? = UserAuthorization.homeDirectory(of:)+ ) {+ lock.withLock { recover(in: folder, homeDirectory: homeDirectory) }+ }++ private static func recover(in folder: String, homeDirectory: (uid_t) -> String?) {+ let staging = folder + "/Staging"+ guard isTheHelpersOwn(folder), isTheHelpersOwn(staging), let handle = try? DirectoryHandle.at(staging).get()+ else { return }+ for entry in (try? FileManager.default.contentsOfDirectory(atPath: staging)) ?? [] {+ let parts = entry.split(separator: ".", maxSplits: 2).map(String.init)+ guard+ parts.count == 3, let user = uid_t(parts[0]), let home = homeDirectory(user),+ let trash = PrivilegedPathPolicy(homeDirectory: home).openTrash(ownedBy: user)+ else { continue }+ _ = TrashMover.place(entry, from: handle, in: trash, as: TrashMover.finderNames(of: parts[2]))+ }+ }++ private static func isTheHelpersOwn(_ folder: String) -> Bool {+ var info = stat()+ return lstat(folder, &info) == 0 && info.st_mode & S_IFMT == S_IFDIR && info.st_uid == geteuid()+ && info.st_mode & 0o077 == 0+ }+public struct Unreadable: Error {}/// The place `item` was taken from, when this helper took it on behalf of `user`.diff --git a/Packages/PeelCore/Sources/PeelPrivileged/HelperPutBack.swift b/Packages/PeelCore/Sources/PeelPrivileged/HelperPutBack.swiftnew file mode 100644index 00000000..f60d224c--- /dev/null+++ b/Packages/PeelCore/Sources/PeelPrivileged/HelperPutBack.swift@@ -0,0 +1,63 @@+import Darwin+public import Foundation++public enum HelperPutBack {+ /// Nil once the item at `trashPath` is back at `destination`, otherwise why it isn't.+ public static func run(+ _ trashPath: String,+ to destination: String,+ for user: uid_t,+ policy: PrivilegedPathPolicy,+ ledger: () -> HelperLedger? = { HelperLedger() }+ ) -> String? {+ run(+ trashPath, to: destination, for: user, policy: policy, ledger: ledger,+ exclusively: TrashMover.renameExclusively+ )+ }++ static func run(+ _ trashPath: String,+ to destination: String,+ for user: uid_t,+ policy: PrivilegedPathPolicy,+ ledger: () -> HelperLedger?,+ exclusively: TrashMover.ExclusiveRename+ ) -> String? {+ guard+ let trash = policy.openTrash(ownedBy: user),+ let trashed = policy.openInTrash(trashPath, trash: trash)+ else { return HelperRefusal.notInTrash.rawValue }++ switch policy.openDestination(destination, for: trashed) {+ case .failure(let rejection):+ return rejection.explanation+ case .success(let target):+ // The request comes from History's record, which any process the user runs can rewrite. So the item+ // goes back only if the ledger shows the helper moved it, and only to the path recorded there.+ guard+ let ledger = ledger(),+ case .success(let origin) = Result(catching: { try ledger.origin(of: trashed, movedBy: user) })+ else {+ return HelperRefusal.cannotReadRecord.rawValue+ }+ guard origin == target.path else { return HelperRefusal.notInRecord.rawValue }+ let moved = ledger.whileStaging { staging in+ TrashMover.move(+ trashed, to: [target.name], in: target.parent, through: staging, for: user,+ refusing: { policy.refusal(ofPuttingBack: target.path, owner: $0.st_uid, mode: $0.st_mode) },+ exclusively: exclusively+ )+ }+ switch moved {+ case nil:+ return HelperRefusal.cannotReadRecord.rawValue+ case .success?:+ ledger.forget([trashed])+ return nil+ case .failure(let failure)?:+ return failure.explanation+ }+ }+ }+}diff --git a/Packages/PeelCore/Sources/PeelPrivileged/TrashMover.swift b/Packages/PeelCore/Sources/PeelPrivileged/TrashMover.swiftindex 52a92f00..fff30deb 100644--- a/Packages/PeelCore/Sources/PeelPrivileged/TrashMover.swift+++ b/Packages/PeelCore/Sources/PeelPrivileged/TrashMover.swift@@ -58,11 +58,7 @@ public enum TrashMover {in directory: DirectoryHandle,exclusively: ExclusiveRename) -> Result<Void, POSIXError> {- var info = stat()- guard item.name.withCString({ fstatat(item.parent.descriptor, $0, &info, AT_SYMLINK_NOFOLLOW) }) == 0 else {- return .failure(.last)- }- guard let identity = item.identity, ItemIdentity(info) == identity else { return .failure(POSIXError(.ENOENT)) }+ if case .failure(let error) = stillThere(item) { return .failure(error) }switch exclusively(item, name, directory) {case .failure(let error) where error.code == .ENOTSUP:return renameOntoPlaceholder(item, to: name, in: directory)@@ -137,7 +133,17 @@ public enum TrashMover {_ = name.withCString { unlinkat(directory.descriptor, $0, isFolder ? AT_REMOVEDIR : 0) }}- private static func renameExclusively(+ /// The identity `item` was opened with, while its name still leads to it.+ private static func stillThere(_ item: OpenItem) -> Result<ItemIdentity, POSIXError> {+ var info = stat()+ guard item.name.withCString({ fstatat(item.parent.descriptor, $0, &info, AT_SYMLINK_NOFOLLOW) }) == 0 else {+ return .failure(.last)+ }+ guard let identity = item.identity, ItemIdentity(info) == identity else { return .failure(POSIXError(.ENOENT)) }+ return .success(identity)+ }++ static func renameExclusively(_ item: OpenItem,to name: String,in directory: DirectoryHandle@@ -154,15 +160,25 @@ public enum TrashMover {extension TrashMover {/// Moves `items` into `trash` the way the helper does, and returns where each moved path went and why each other- /// failed, or nil when `ledger` could not record them (then nothing moves). Every item is recorded before any- /// moves, and only the items that stayed are forgotten again. One request can name an item twice (the same- /// path, or `/var/...` and `/private/var/...`): it moves once and answers for both paths, since the second try- /// would fail and forgetting it would also forget the record of the item that moved.+ /// failed, or nil when `ledger` could not record them or keep its staging folder (then nothing moves). Every item+ /// is recorded before any moves, and only the items that stayed are forgotten again. One request can name an item+ /// twice (the same path, or `/var/...` and `/private/var/...`): it moves once and answers for both paths, since+ /// the second try would fail and forgetting it would also forget the record of the item that moved.public static func moveRecorded(_ items: [(path: String, item: OpenItem)],into trash: DirectoryHandle,ledger: HelperLedger,movedBy user: uid_t+ ) -> (moved: [String: String], failed: [String: String])? {+ moveRecorded(items, into: trash, ledger: ledger, movedBy: user, exclusively: renameExclusively)+ }++ static func moveRecorded(+ _ items: [(path: String, item: OpenItem)],+ into trash: DirectoryHandle,+ ledger: HelperLedger,+ movedBy user: uid_t,+ exclusively: ExclusiveRename) -> (moved: [String: String], failed: [String: String])? {var firstPath: [ItemIdentity: String] = [:]var sameAs: [String: String] = [:]@@ -182,15 +198,22 @@ extension TrashMover {var moved: [String: String] = [:]var failed: [String: String] = [:]var stayed: [OpenItem] = []- for (path, item) in unique {- switch move(item, into: trash) {- case .success(let destination):- moved[path] = destination- case .failure(let error):- failed[path] = error.localizedDescription- stayed.append(item)+ let staged: Void? = ledger.whileStaging { staging in+ for (path, item) in unique {+ let names = finderNames(of: item.name)+ switch move(item, to: names, in: trash, through: staging, for: user, exclusively: exclusively) {+ case .success(let name):+ moved[path] = (trash.path as NSString).appendingPathComponent(name)+ case .failure(let failure):+ failed[path] = failure.explanation+ stayed.append(item)+ }}}+ guard staged != nil else {+ ledger.forget(unique.map(\.item))+ return nil+ }ledger.forget(stayed)for (path, first) in sameAs {if let destination = moved[first] {@@ -202,3 +225,77 @@ extension TrashMover {return (moved, failed)}}++extension TrashMover {+ enum StagedFailure: Error {+ case failed(POSIXError)+ case refused(PrivilegedPathPolicy.Rejection)++ var explanation: String {+ switch self {+ case .failed(let error): error.localizedDescription+ case .refused(let rejection): rejection.explanation+ }+ }+ }++ /// Moves `item` to the first of `names` free in `destination` by way of `staging`, which only the helper can+ /// reach. A rename goes by name, so what arrives is checked there, where nothing can take its place: anything but+ /// the item, or anything `refusing` refuses, goes back.+ static func move(+ _ item: OpenItem,+ to names: some Sequence<String>,+ in destination: DirectoryHandle,+ through staging: DirectoryHandle,+ for user: uid_t,+ refusing: (stat) -> PrivilegedPathPolicy.Rejection? = { _ in nil },+ exclusively: ExclusiveRename = renameExclusively+ ) -> Result<String, StagedFailure> {+ let identity: ItemIdentity+ switch stillThere(item) {+ case .success(let opened): identity = opened+ case .failure(let error): return .failure(.failed(error))+ }+ var staged = "\(user).\(UUID().uuidString).\(item.name)"+ while staged.utf8.count > Int(NAME_MAX) { staged.removeLast() }+ if case .failure(let error) = exclusively(item, staged, staging) { return .failure(.failed(error)) }++ let failure: StagedFailure+ if let arrived = staging.status(of: staged), ItemIdentity(arrived) == identity {+ if let rejection = refusing(arrived) {+ failure = .refused(rejection)+ } else {+ switch place(staged, from: staging, in: destination, as: names) {+ case .success(let name): return .success(name)+ case .failure(let error): failure = .failed(error)+ }+ }+ } else {+ failure = .failed(POSIXError(.ENOENT))+ }+ _ = place(staged, from: staging, in: item.parent, as: finderNames(of: item.name))+ return .failure(failure)+ }++ /// Renames `name`, in a folder only root can change, to the first of `names` free in `destination`.+ static func place(+ _ name: String,+ from folder: DirectoryHandle,+ in destination: DirectoryHandle,+ as names: some Sequence<String>+ ) -> Result<String, POSIXError> {+ let item = OpenItem(path: folder.path + "/" + name, name: name, parent: folder)+ for candidate in names {+ switch renameExclusively(item, to: candidate, in: destination) {+ case .success: return .success(candidate)+ case .failure(let error) where error.code == .EEXIST: continue+ case .failure(let error): return .failure(error)+ }+ }+ return .failure(POSIXError(.EEXIST))+ }++ static func finderNames(of name: String) -> some Sequence<String> {+ attempts.lazy.map { Self.name(name, attempt: $0) }+ }+}diff --git a/Packages/PeelCore/Tests/PeelCoreTests/AttackHelperPolicyTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/AttackHelperPolicyTests.swiftindex bbff9084..753f32ba 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/AttackHelperPolicyTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/AttackHelperPolicyTests.swift@@ -161,16 +161,208 @@ struct AttackHelperPolicyTests {}extension AttackHelperPolicyTests {- private func servingPolicy(_ directory: borrowing TemporaryDirectory) -> PrivilegedPathPolicy {+ private func servingPolicy(+ _ directory: borrowing TemporaryDirectory,+ trusting owner: uid_t = 0+ ) -> PrivilegedPathPolicy {let root = directory.url.path(percentEncoded: false)return PrivilegedPathPolicy(homeDirectory: root + "home",systemLocations: [root + "root/Applications", root + "root/Library/LaunchDaemons", root + "root/Library/Caches"],applicationLocations: [root + "root/Applications"],- restoreLocations: [root + "root/Applications", root + "root/Library/Caches"]+ restoreLocations: [root + "root/Applications", root + "root/Library/Caches"],+ trustedOwner: owner)}+ private func movedByTheHelper(+ _ relative: String,+ _ text: String,+ policy: PrivilegedPathPolicy,+ ledger: HelperLedger,+ in directory: borrowing TemporaryDirectory+ ) throws -> String {+ try Data(text.utf8).write(to: try directory.file(relative))+ let item = try policy.open(path(relative, in: directory)).get()+ #expect(ledger.record([item], movedBy: getuid()))+ return try TrashMover.move(item, into: try #require(policy.openTrash(ownedBy: getuid()))).get()+ }++ /// A process of the user swaps its own object into the item's name right before the helper renames it.+ private func swappingIn(_ payload: String) -> TrashMover.ExclusiveRename {+ { item, name, folder in+ _ = renameatx_np(item.parent.descriptor, item.name, item.parent.descriptor, payload, UInt32(RENAME_SWAP))+ return TrashMover.renameExclusively(item, to: name, in: folder)+ }+ }++ @Test func anObjectSwappedInDuringPutBackNeverReachesAFolderCodeIsLoadedFrom() throws {+ let directory = try TemporaryDirectory()+ try directory.directory("root/Library/LaunchDaemons")+ try directory.directory("home/.Trash")+ let policy = servingPolicy(directory, trusting: getuid())+ let ledger = try #require(HelperLedger(at: directory.url.appending(path: "private/moved.plist")))+ let original = path("root/Library/LaunchDaemons/org.example.daemon.plist", in: directory)+ let trashed = try movedByTheHelper(+ "root/Library/LaunchDaemons/org.example.daemon.plist", "the daemon's", policy: policy, ledger: ledger,+ in: directory+ )+ try Data("the user's".utf8).write(to: URL(filePath: path("home/.Trash/payload", in: directory)))++ let refusal = HelperPutBack.run(+ trashed, to: original, for: getuid(), policy: policy, ledger: { ledger }, exclusively: swappingIn("payload")+ )++ #expect(refusal != nil, "ATTACK SUCCEEDED: root put the user's own object back where launchd reads daemons")+ #expect(!FileManager.default.fileExists(atPath: original))+ let inTheTrash = Set(try FileManager.default.contentsOfDirectory(atPath: path("home/.Trash", in: directory)))+ #expect(inTheTrash.count == 2, "both objects stay in the Trash")+ }++ @Test func anItemChangedInTheTrashAfterTheLookNeverGoesBackWhereCodeIsLoaded() throws {+ let directory = try TemporaryDirectory()+ try directory.directory("root/Library/LaunchDaemons")+ try directory.directory("home/.Trash")+ let policy = servingPolicy(directory, trusting: getuid())+ let ledger = try #require(HelperLedger(at: directory.url.appending(path: "private/moved.plist")))+ let original = path("root/Library/LaunchDaemons/org.example.daemon.plist", in: directory)+ let trashed = try movedByTheHelper(+ "root/Library/LaunchDaemons/org.example.daemon.plist", "the daemon's", policy: policy, ledger: ledger,+ in: directory+ )+ let openedToEveryone: TrashMover.ExclusiveRename = { item, name, folder in+ _ = fchmodat(item.parent.descriptor, item.name, 0o666, AT_SYMLINK_NOFOLLOW)+ return TrashMover.renameExclusively(item, to: name, in: folder)+ }++ let refusal = HelperPutBack.run(+ trashed, to: original, for: getuid(), policy: policy, ledger: { ledger }, exclusively: openedToEveryone+ )++ #expect(refusal != nil, "ATTACK SUCCEEDED: a file anyone could rewrite went back where launchd reads daemons")+ #expect(!FileManager.default.fileExists(atPath: original))+ #expect(FileManager.default.fileExists(atPath: trashed))+ }++ @Test func anObjectSwappedInDuringPutBackNeverReachesAFolderThatTakesAnything() throws {+ let directory = try TemporaryDirectory()+ try directory.directory("root/Library/Caches")+ try directory.directory("home/.Trash")+ let policy = servingPolicy(directory)+ let ledger = try #require(HelperLedger(at: directory.url.appending(path: "private/moved.plist")))+ let original = path("root/Library/Caches/org.example.cache", in: directory)+ let trashed = try movedByTheHelper(+ "root/Library/Caches/org.example.cache", "the app's", policy: policy, ledger: ledger, in: directory+ )+ try Data("the user's".utf8).write(to: URL(filePath: path("home/.Trash/payload", in: directory)))++ let refusal = HelperPutBack.run(+ trashed, to: original, for: getuid(), policy: policy, ledger: { ledger }, exclusively: swappingIn("payload")+ )++ #expect(refusal != nil, "ATTACK SUCCEEDED: root put back an object the helper never moved")+ #expect(!FileManager.default.fileExists(atPath: original))+ }++ @Test func aMoveToTheTrashTakesOnlyTheItemThatWasOpened() throws {+ let directory = try TemporaryDirectory()+ try directory.directory("home/.Trash")+ try directory.file("root/Library/Caches/org.example.cache", contents: Data("the app's".utf8))+ try directory.file("root/Library/Caches/payload", contents: Data("the user's".utf8))+ let policy = servingPolicy(directory)+ let ledger = try #require(HelperLedger(at: directory.url.appending(path: "private/moved.plist")))+ let original = path("root/Library/Caches/org.example.cache", in: directory)+ let item = try policy.open(original).get()+ let trash = try #require(policy.openTrash(ownedBy: getuid()))++ let result = try #require(TrashMover.moveRecorded(+ [(original, item)], into: trash, ledger: ledger, movedBy: getuid(), exclusively: swappingIn("payload")+ ))++ #expect(result.moved.isEmpty, "ATTACK SUCCEEDED: root moved an object it never judged")+ #expect(try FileManager.default.contentsOfDirectory(atPath: path("home/.Trash", in: directory)).isEmpty)+ #expect(try String(contentsOfFile: original, encoding: .utf8) == "the user's")+ #expect(try ledger.origin(of: item, movedBy: getuid()) == nil)+ }++ @Test func theHelperMovesNothingWhereARenameCannotRefuseToReplace() throws {+ let directory = try TemporaryDirectory()+ try directory.directory("root/Library/Caches")+ try directory.directory("home/.Trash")+ let policy = servingPolicy(directory)+ let ledger = try #require(HelperLedger(at: directory.url.appending(path: "private/moved.plist")))+ let original = path("root/Library/Caches/org.example.cache", in: directory)+ let trashed = try movedByTheHelper(+ "root/Library/Caches/org.example.cache", "the app's", policy: policy, ledger: ledger, in: directory+ )+ let unsupported: TrashMover.ExclusiveRename = { _, _, _ in .failure(POSIXError(.ENOTSUP)) }+ try directory.file("root/Library/Caches/org.example.other")+ let other = path("root/Library/Caches/org.example.other", in: directory)+ let trash = try #require(policy.openTrash(ownedBy: getuid()))++ let refusal = HelperPutBack.run(+ trashed, to: original, for: getuid(), policy: policy, ledger: { ledger }, exclusively: unsupported+ )+ let result = try #require(TrashMover.moveRecorded(+ [(other, try policy.open(other).get())], into: trash, ledger: ledger, movedBy: getuid(),+ exclusively: unsupported+ ))++ #expect(refusal != nil)+ #expect(!FileManager.default.fileExists(atPath: original), "the helper replaced a placeholder by name")+ #expect(FileManager.default.fileExists(atPath: trashed))+ #expect(result.moved.isEmpty)+ #expect(FileManager.default.fileExists(atPath: other))+ }++ @Test func aNameTakenMeanwhileSendsTheItemBackToTheTrash() throws {+ let directory = try TemporaryDirectory()+ try directory.directory("root/Library/Caches")+ try directory.directory("home/.Trash")+ let policy = servingPolicy(directory)+ let ledger = try #require(HelperLedger(at: directory.url.appending(path: "private/moved.plist")))+ let original = path("root/Library/Caches/org.example.cache", in: directory)+ let trashed = try movedByTheHelper(+ "root/Library/Caches/org.example.cache", "the app's", policy: policy, ledger: ledger, in: directory+ )+ let takingTheName: TrashMover.ExclusiveRename = { item, name, folder in+ FileManager.default.createFile(atPath: original, contents: Data("another".utf8))+ return TrashMover.renameExclusively(item, to: name, in: folder)+ }++ let refusal = HelperPutBack.run(+ trashed, to: original, for: getuid(), policy: policy, ledger: { ledger }, exclusively: takingTheName+ )++ #expect(refusal != nil)+ #expect(try String(contentsOfFile: original, encoding: .utf8) == "another")+ #expect(try String(contentsOfFile: trashed, encoding: .utf8) == "the app's")+ let trash = try #require(policy.openTrash(ownedBy: getuid()))+ let back = try #require(policy.openInTrash(trashed, trash: trash))+ #expect(try ledger.origin(of: back, movedBy: getuid()) != nil, "it could never be put back again")+ }++ @Test func anItemOnAnotherDiskThanTheHelpersFolderStaysInTheTrash() throws {+ let directory = try TemporaryDirectory()+ let disk = try ScratchVolume(fileSystem: "APFS", mountedAt: directory.url.appending(path: "Disk"))+ let home = disk.url.appending(path: "home").path(percentEncoded: false)+ try FileManager.default.createDirectory(atPath: home + "/.Trash", withIntermediateDirectories: true)+ try FileManager.default.createDirectory(atPath: home + "/Library/Caches", withIntermediateDirectories: true)+ let policy = PrivilegedPathPolicy(homeDirectory: home, systemLocations: [], applicationLocations: [])+ let ledger = try #require(HelperLedger(at: directory.url.appending(path: "private/moved.plist")))+ let original = home + "/Library/Caches/org.example.cache"+ try Data("the app's".utf8).write(to: URL(filePath: original))+ let item = try policy.open(original).get()+ #expect(ledger.record([item], movedBy: getuid()))+ let trashed = try TrashMover.move(item, into: try #require(policy.openTrash(ownedBy: getuid()))).get()++ let refusal = HelperPutBack.run(trashed, to: original, for: getuid(), policy: policy, ledger: { ledger })++ #expect(refusal != nil, "the helper moved an item by name with nowhere to check it first")+ #expect(FileManager.default.fileExists(atPath: trashed))+ #expect(!FileManager.default.fileExists(atPath: original))+ }+private func path(_ relative: String, in directory: borrowing TemporaryDirectory) -> String {directory.url.appending(path: relative).path(percentEncoded: false)}diff --git a/Packages/PeelCore/Tests/PeelCoreTests/HelperLedgerTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/HelperLedgerTests.swiftindex e94a8055..6a993611 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/HelperLedgerTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/HelperLedgerTests.swift@@ -297,6 +297,120 @@ struct HelperLedgerTests {#expect(try ledger.origin(of: trashed, movedBy: getuid()) != nil, "an entry kept without its volume was forgotten")}+ @Test func putsBackAFileAFolderAndALinkItMovedWhole() throws {+ let directory = try TemporaryDirectory()+ try directory.directory("home/.Trash")+ try directory.file("root/Library/Caches/com.example.plist", contents: Data("settings".utf8))+ try directory.file("root/Library/Caches/com.example.app/Cache.db", contents: Data("cache".utf8))+ try directory.directory("root/usr/local/bin")+ try FileManager.default.createSymbolicLink(+ atPath: path("root/usr/local/bin/example", in: directory), withDestinationPath: "/nowhere/example"+ )+ let root = directory.url.path(percentEncoded: false)+ let policy = PrivilegedPathPolicy(+ homeDirectory: root + "home",+ systemLocations: [root + "root/Library/Caches"],+ applicationLocations: [],+ restoreLocations: [root + "root/Library/Caches"],+ linkLocations: [root + "root/usr/local/bin"],+ trustedOwner: getuid()+ )+ let ledger = try ledger(in: directory)+ let trash = try #require(policy.openTrash(ownedBy: getuid()))+ let originals = ["root/Library/Caches/com.example.plist", "root/Library/Caches/com.example.app", "root/usr/local/bin/example"]+ .map { path($0, in: directory) }++ let result = try #require(TrashMover.moveRecorded(+ try originals.map { ($0, try policy.open($0).get()) }, into: trash, ledger: ledger, movedBy: getuid()+ ))+ #expect(result.failed.isEmpty)+ for original in originals {+ let trashed = try #require(result.moved[original])+ #expect(HelperPutBack.run(trashed, to: original, for: getuid(), policy: policy, ledger: { ledger }) == nil)+ }++ #expect(try String(contentsOfFile: originals[0], encoding: .utf8) == "settings")+ #expect(try String(contentsOfFile: originals[1] + "/Cache.db", encoding: .utf8) == "cache")+ #expect(try FileManager.default.destinationOfSymbolicLink(atPath: originals[2]) == "/nowhere/example")+ #expect(try FileManager.default.contentsOfDirectory(atPath: path("home/.Trash", in: directory)).isEmpty)+ #expect(try FileManager.default.contentsOfDirectory(atPath: path("private/Staging", in: directory)).isEmpty)+ }++ @Test func movesNothingWhileItsStagingFolderIsNotItsOwn() throws {+ let directory = try TemporaryDirectory()+ let policy = try policy(in: directory)+ let ledger = try ledger(in: directory)+ let trash = try #require(policy.openTrash(ownedBy: getuid()))+ let original = try directory.file("root/Library/Caches/com.example.plist").path(percentEncoded: false)+ let item = try policy.open(original).get()+ let staging = path("private/Staging", in: directory)++ try directory.directory("private/Staging")+ try directory.setPermissions(0o755, of: "private/Staging")+ #expect(TrashMover.moveRecorded([(original, item)], into: trash, ledger: ledger, movedBy: getuid()) == nil)+ try FileManager.default.removeItem(atPath: staging)+ try FileManager.default.createSymbolicLink(atPath: staging, withDestinationPath: path("home/.Trash", in: directory))+ #expect(TrashMover.moveRecorded([(original, item)], into: trash, ledger: ledger, movedBy: getuid()) == nil)++ #expect(FileManager.default.fileExists(atPath: original))+ #expect(try ledger.origin(of: item, movedBy: getuid()) == nil)+ }++ @Test func whatAMoveCutShortLeftOnTheWayGoesToItsAccountsTrash() throws {+ let directory = try TemporaryDirectory()+ _ = try policy(in: directory)+ _ = try ledger(in: directory)+ try directory.directory("private/Staging")+ try directory.setPermissions(0o700, of: "private/Staging")+ try directory.file("private/Staging/\(getuid()).\(UUID().uuidString).notes.txt", contents: Data("left".utf8))+ try directory.file("private/Staging/4242424.\(UUID().uuidString).other.txt")+ try directory.file("home/.Trash/notes.txt")+ let home = path("home", in: directory)++ HelperLedger.recoverStaged(in: path("private", in: directory)) { $0 == getuid() ? home : nil }++ #expect(try String(contentsOfFile: path("home/.Trash/notes 2.txt", in: directory), encoding: .utf8) == "left")+ let left = try FileManager.default.contentsOfDirectory(atPath: path("private/Staging", in: directory))+ #expect(left.count == 1 && left[0].hasPrefix("4242424."), "an item with no Trash to go to was lost")+ }++ @Test func recoversNothingFromAFolderOthersCanReach() throws {+ let directory = try TemporaryDirectory()+ _ = try policy(in: directory)+ try directory.file("private/Staging/\(getuid()).\(UUID().uuidString).planted.txt")+ try directory.setPermissions(0o755, of: "private")+ try directory.setPermissions(0o700, of: "private/Staging")+ try directory.directory("empty")+ try directory.setPermissions(0o700, of: "empty")+ let home = path("home", in: directory)++ HelperLedger.recoverStaged(in: path("private", in: directory)) { _ in home }+ HelperLedger.recoverStaged(in: path("empty", in: directory)) { _ in home }++ #expect(try FileManager.default.contentsOfDirectory(atPath: path("home/.Trash", in: directory)).isEmpty)+ #expect(!FileManager.default.fileExists(atPath: path("empty/Staging", in: directory)))+ }++ @Test func sendsWhatWasLeftOnTheWayToItsTrashBeforeItsFolderGoes() throws {+ let directory = try TemporaryDirectory()+ let policy = try policy(in: directory)+ let trash = try #require(policy.openTrash(ownedBy: getuid()))+ _ = try ledger(in: directory)+ try directory.directory("private/Staging")+ try directory.setPermissions(0o700, of: "private/Staging")+ try directory.file("private/Staging/\(getuid()).\(UUID().uuidString).notes.txt")+ let home = path("home", in: directory)++ let moved = try #require(try HelperLedger.moveFolder(+ path("private", in: directory), into: trash, givingTo: getuid(), homeDirectory: { _ in home }+ ) { folder, entry, owner in+ entry.map { folder.give($0, to: owner) } ?? folder.giveItself(to: owner)+ }.get())++ #expect(FileManager.default.fileExists(atPath: path("home/.Trash/notes.txt", in: directory)))+ #expect(try FileManager.default.contentsOfDirectory(atPath: moved + "/Staging").isEmpty)+ }+@Test func keepsTheNewestEntriesAndOnlyInAFolderOfItsOwn() throws {let directory = try TemporaryDirectory()let policy = try policy(in: directory)diff --git a/PeelHelper/HelperService.swift b/PeelHelper/HelperService.swiftindex f2d27e58..5f81e8d4 100644--- a/PeelHelper/HelperService.swift+++ b/PeelHelper/HelperService.swift@@ -100,32 +100,7 @@ final class HelperService: NSObject, PeelHelperProtocol {}let policy = PrivilegedPathPolicy(homeDirectory: caller.homeDirectory)- guard- let trash = policy.openTrash(ownedBy: caller.user),- let trashed = policy.openInTrash(trashPath, trash: trash)- else { return reply(HelperRefusal.notInTrash.rawValue) }-- switch policy.openDestination(destination, for: trashed) {- case .failure(let rejection):- reply(rejection.explanation)- case .success(let target):- // The request comes from History's record, which any process the user runs can rewrite. So the item- // goes back only if the ledger shows the helper moved it, and only to the path recorded there.- guard- let ledger = HelperLedger(),- case .success(let origin) = Result(catching: { try ledger.origin(of: trashed, movedBy: caller.user) })- else {- return reply(HelperRefusal.cannotReadRecord.rawValue)- }- guard origin == target.path else { return reply(HelperRefusal.notInRecord.rawValue) }- switch TrashMover.rename(trashed, to: target.name, in: target.parent) {- case .success:- ledger.forget([trashed])- reply(nil)- case .failure(let error):- reply(error.localizedDescription)- }- }+ reply(HelperPutBack.run(trashPath, to: destination, for: caller.user, policy: policy))}func moveLedgerToTrash(version: Int, withReply finish: @escaping @Sendable (String?) -> Void) {diff --git a/PeelHelper/main.swift b/PeelHelper/main.swiftindex 390804e0..9a0e187f 100644--- a/PeelHelper/main.swift+++ b/PeelHelper/main.swift@@ -17,6 +17,7 @@ listener.setConnectionCodeSigningRequirement(requirement)let lifetime = HelperLifetime()let delegate = HelperListenerDelegate(lifetime: lifetime, codeSigningRequirement: requirement)listener.delegate = delegate+HelperLedger.recoverStaged()listener.resume()lifetime.start()dispatchMain()