Skip to content

armgit / peel

Public Imported from GitHub
0

Uninstall Mac apps with every file they leave behind, and see why each belongs. Free up space, fine-tune macOS, and set up Terminal.

The helper never writes over a ledger it cannot read

Țugui Dragoș463682581e1c
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md
index 04cac13d..cb67566b 100644
--- a/ARCHITECTURE.md
+++ b/ARCHITECTURE.md
@@ -145,9 +145,10 @@ macOS asks the user to approve it once. It talks to the app over XPC.
- It opens folders by descriptor and works through them, so a path swapped for a link after the check leads
nowhere.
- It keeps a ledger of what it moved, in a folder only root can write (`/private/var/db/com.tuguidragos.Peel.Helper`),
- and puts back only what that ledger knows.
-- Adding an operation means bumping `HelperIdentity.protocolVersion`, which asks users to install the helper
- again.
+ and puts back only what that ledger knows. While the ledger can't be read it moves nothing, and one it can't make
+ sense of is kept under another name (`DamagedFile`), never written over.
+- Any change to the helper means bumping `HelperIdentity.protocolVersion`, which asks users to install the
+ helper again.
## The app
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 065ce730..8a66bfea 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -154,7 +154,7 @@ Tests enforce these. If your change makes one of them fail, the rule is right an
text the compiler keeps. XProtect, the malware scanner in macOS, takes a binary that carries a few wallet IDs for
a program that steals them and moves it to the Trash, a test binary included, so tests read the IDs from those
comments (`WalletIDs`). `BrowserWalletTests` checks every fingerprint against the ID above it.
-- **The privileged helper**: `PrivilegedPathPolicyTests`, and for a new operation a bump of
+- **The privileged helper**: `PrivilegedPathPolicyTests`, and for any change to the helper a bump of
`HelperIdentity.protocolVersion`.
- **`DeveloperCaches.definitions`**: a source showing the folder is a cache, and a `DeveloperCachesTests` run.
Never a toolchain, never an installation, never a file holding an account or a token, and never a path inside
@@ -175,8 +175,8 @@ disk that somebody may have replaced.
debugged.
- It never uses a path again after checking it. It holds the folder open and works through that descriptor, so
a folder swapped after the check leads nowhere.
-- A new operation needs `PrivilegedPathPolicyTests` and a protocol version bump, which asks every user to
- install the helper again. That cost is deliberate.
+- A new operation needs `PrivilegedPathPolicyTests`, and any change to the helper a protocol version bump,
+ which asks every user to install the helper again. That cost is deliberate.
If you are unsure whether something belongs in the helper, it doesn't. The helper should stay small enough to
read in one sitting.
diff --git a/Localization/Peel/Localizable.xcstrings b/Localization/Peel/Localizable.xcstrings
index 08558ff4..a6bb7fb6 100644
--- a/Localization/Peel/Localizable.xcstrings
+++ b/Localization/Peel/Localizable.xcstrings
@@ -85143,6 +85143,112 @@
}
}
},
+ "Peel’s helper can’t read its record of what it moved, so nothing was put back." : {
+ "localizations" : {
+ "cs" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Pomocník Peelu nemůže přečíst svůj záznam o tom, co přesunul, a proto se nic nevrátilo zpět."
+ }
+ },
+ "de" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Das Hilfsprogramm von Peel kann seine Aufzeichnungen darüber, was es verschoben hat, nicht lesen, daher wurde nichts zurückgelegt."
+ }
+ },
+ "es" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "El asistente de Peel no puede leer su registro de lo que ha trasladado, así que no se ha restaurado nada."
+ }
+ },
+ "fr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "L’utilitaire de Peel ne peut pas lire le registre de ce qu’il a déplacé : rien n’a donc été remis en place."
+ }
+ },
+ "it" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "L’assistente di Peel non riesce a leggere il registro di ciò che ha spostato, quindi non è stato ripristinato nulla."
+ }
+ },
+ "ja" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Peelのヘルパーが移動したものの記録を読み取れないため、何も戻しませんでした。"
+ }
+ },
+ "ko" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Peel 보조 프로그램이 이동한 항목에 대한 기록을 읽을 수 없으므로 아무것도 되돌려 놓지 않았습니다."
+ }
+ },
+ "nl" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Het hulpprogramma van Peel kan zijn overzicht van wat het heeft verplaatst niet lezen, dus er is niets teruggezet."
+ }
+ },
+ "pl" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Pomocnik Peel nie może odczytać swojego zapisu tego, co przeniósł, więc niczego nie przywrócono."
+ }
+ },
+ "pt" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "O auxiliar do Peel não consegue ler o registro do que moveu, então nada foi colocado de volta."
+ }
+ },
+ "ro" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Instrumentul de ajutor Peel nu își poate citi evidența a ceea ce a mutat, așa că nu s‑a pus nimic înapoi."
+ }
+ },
+ "ru" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Помощник Peel не может прочитать свой журнал того, что он переместил, поэтому ничего не восстановлено."
+ }
+ },
+ "sv" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Peels hjälpprogram kan inte läsa sin förteckning över vad det flyttade, så inget lades tillbaka."
+ }
+ },
+ "tr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Peel’in yardımcısı taşıdıklarının kaydını okuyamıyor, bu yüzden hiçbir şey yerine konmadı."
+ }
+ },
+ "uk" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Помічник Peel не може прочитати свій запис того, що перемістив, тож нічого не повернуто."
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Peel的帮助程序无法读取它所移动内容的记录,因此没有放回任何内容。"
+ }
+ },
+ "zh-Hant" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Peel的輔助程式無法讀取它所移動項目的記錄,因此未還原任何項目。"
+ }
+ }
+ }
+ },
"Peel’s helper didn’t move this from there, so it stays in the Trash. You can drag it back out in Finder." : {
"localizations" : {
"cs" : {
diff --git a/Packages/PeelCore/Sources/PeelCore/Apps/AppMemory.swift b/Packages/PeelCore/Sources/PeelCore/Apps/AppMemory.swift
index 31145c0d..d2a808c3 100644
--- a/Packages/PeelCore/Sources/PeelCore/Apps/AppMemory.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Apps/AppMemory.swift
@@ -1,4 +1,5 @@
public import Foundation
+internal import PeelPrivileged
/// An app Peel has seen installed, kept after the app is gone. An app dragged to the Trash leaves its files
/// behind with nothing to name them, so Peel shows them under the remembered name instead of an identifier.
diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/RefusalLog.swift b/Packages/PeelCore/Sources/PeelCore/Removal/RefusalLog.swift
index 431f8f3b..a7f14dac 100644
--- a/Packages/PeelCore/Sources/PeelCore/Removal/RefusalLog.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Removal/RefusalLog.swift
@@ -1,4 +1,5 @@
public import Foundation
+internal import PeelPrivileged
public struct RefusalRecord: Sendable, Codable, Hashable, Identifiable {
public let id: UUID
diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/RemovalLog.swift b/Packages/PeelCore/Sources/PeelCore/Removal/RemovalLog.swift
index 70677c19..d59801eb 100644
--- a/Packages/PeelCore/Sources/PeelCore/Removal/RemovalLog.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Removal/RemovalLog.swift
@@ -1,4 +1,5 @@
public import Foundation
+internal import PeelPrivileged
/// A problem reading or writing the log, for History to show.
public enum RemovalLogProblem: Sendable, Equatable {
diff --git a/Packages/PeelCore/Sources/PeelCore/Support/FixedSentence.swift b/Packages/PeelCore/Sources/PeelCore/Support/FixedSentence.swift
index 8d13981f..2a991cd4 100644
--- a/Packages/PeelCore/Sources/PeelCore/Support/FixedSentence.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Support/FixedSentence.swift
@@ -8,8 +8,8 @@ internal import PeelPrivileged
public enum FixedSentence: CaseIterable, Sendable {
case notAFullPath, dotInPath, controlCharacter, folderNotFound, outsideHelpersFolders, onlyAppsThere
case notThereAnymore, alreadyThere, protectedByMacOS, irreplaceable, codeFolder, onlyLinksThere, leadsSomewhere
- case helperOutOfDate, accountNotAllowed, tooManyItems, noTrash, pathTooLong, cannotKeepRecord, notInTrash
- case notMovedByHelper, invalidRequest, configurationMissing
+ case helperOutOfDate, accountNotAllowed, tooManyItems, noTrash, pathTooLong, cannotKeepRecord, cannotReadRecord
+ case notInTrash, notMovedByHelper, invalidRequest, configurationMissing
case toolTimedOut, toolStopped
case receiptMisplaced, homebrewNotInstalled, helperUnavailable
@@ -40,6 +40,7 @@ public enum FixedSentence: CaseIterable, Sendable {
case .noTrash: HelperRefusal.noTrash.rawValue
case .pathTooLong: HelperRefusal.pathTooLong.rawValue
case .cannotKeepRecord: HelperRefusal.cannotKeepRecord.rawValue
+ case .cannotReadRecord: HelperRefusal.cannotReadRecord.rawValue
case .notInTrash: HelperRefusal.notInTrash.rawValue
case .notMovedByHelper: HelperRefusal.notMovedByHelper.rawValue
case .invalidRequest: HelperRefusal.invalidRequest.rawValue
diff --git a/Packages/PeelCore/Sources/PeelCore/Updates/TeamRegistry.swift b/Packages/PeelCore/Sources/PeelCore/Updates/TeamRegistry.swift
index 1d09d773..3d621d9b 100644
--- a/Packages/PeelCore/Sources/PeelCore/Updates/TeamRegistry.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Updates/TeamRegistry.swift
@@ -1,4 +1,5 @@
public import Foundation
+internal import PeelPrivileged
/// Remembers which team signs each app, so the user can be told when a different team, or no team, signs it.
public struct TeamRegistry: Sendable {
diff --git a/Packages/PeelCore/Sources/PeelCore/Support/DamagedFile.swift b/Packages/PeelCore/Sources/PeelPrivileged/DamagedFile.swift
similarity index 92%
rename from Packages/PeelCore/Sources/PeelCore/Support/DamagedFile.swift
rename to Packages/PeelCore/Sources/PeelPrivileged/DamagedFile.swift
index 7827d298..517f2d40 100644
--- a/Packages/PeelCore/Sources/PeelCore/Support/DamagedFile.swift
+++ b/Packages/PeelCore/Sources/PeelPrivileged/DamagedFile.swift
@@ -1,8 +1,8 @@
-import Foundation
+public import Foundation
/// Renames one of Peel's own files that cannot be read, so the next save does not overwrite it.
-enum DamagedFile {
- static func setAside(_ url: URL) -> URL? {
+public enum DamagedFile {
+ public static func setAside(_ url: URL) -> URL? {
let folder = url.deletingLastPathComponent()
let name = url.deletingPathExtension().lastPathComponent
let ext = url.pathExtension
diff --git a/Packages/PeelCore/Sources/PeelPrivileged/HelperInterface.swift b/Packages/PeelCore/Sources/PeelPrivileged/HelperInterface.swift
index dac34ded..403d5efc 100644
--- a/Packages/PeelCore/Sources/PeelPrivileged/HelperInterface.swift
+++ b/Packages/PeelCore/Sources/PeelPrivileged/HelperInterface.swift
@@ -5,8 +5,9 @@ public enum HelperIdentity {
public static let helperIdentifier = "com.tuguidragos.Peel.Helper"
public static let machServiceName = "com.tuguidragos.Peel.Helper"
public static let launchdPlistName = "com.tuguidragos.Peel.Helper.plist"
- /// Raise it whenever `PeelHelperProtocol` changes. The helper refuses requests that carry any other version.
- public static let protocolVersion = 6
+ /// Raise it whenever the helper changes, so Peel asks for the helper to be installed again rather than work with
+ /// an older one. The helper refuses requests that carry any other version.
+ public static let protocolVersion = 7
}
/// 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.swift
index ad89e56e..bc923033 100644
--- a/Packages/PeelCore/Sources/PeelPrivileged/HelperLedger.swift
+++ b/Packages/PeelCore/Sources/PeelPrivileged/HelperLedger.swift
@@ -44,7 +44,8 @@ public final class HelperLedger: @unchecked Sendable {
item.identity.map { Entry(path: item.path, identity: $0, user: user, date: .now) }
}
let known = Set(added.map(\.identity))
- return write((read().filter { !known.contains($0.identity) } + added).suffix(maximumEntries))
+ guard let entries = read() else { return false }
+ return write((entries.filter { !known.contains($0.identity) } + added).suffix(maximumEntries))
}
}
@@ -52,8 +53,8 @@ public final class HelperLedger: @unchecked Sendable {
public func forget(_ items: [OpenItem]) {
Self.lock.withLock {
let gone = Set(items.compactMap(\.identity))
- guard !gone.isEmpty else { return }
- _ = write(read().filter { !gone.contains($0.identity) })
+ guard !gone.isEmpty, let entries = read() else { return }
+ _ = write(entries.filter { !gone.contains($0.identity) })
}
}
@@ -74,17 +75,36 @@ public final class HelperLedger: @unchecked Sendable {
}
}
+ public struct Unreadable: Error {}
+
/// The place `item` was taken from, when this helper took it on behalf of `user`.
- public func origin(of item: OpenItem, movedBy user: uid_t) -> String? {
- Self.lock.withLock {
- guard let identity = item.identity else { return nil }
- return read().last { $0.identity == identity && $0.user == user }?.path
+ public func origin(of item: OpenItem, movedBy user: uid_t) throws(Unreadable) -> String? {
+ guard let entries = Self.lock.withLock({ read() }) else { throw Unreadable() }
+ guard let identity = item.identity else { return nil }
+ return entries.last { $0.identity == identity && $0.user == user }?.path
+ }
+
+ /// The entries, or nil when the ledger is there and cannot be read: then nothing moves and nothing goes back.
+ /// A ledger that is not a list of entries is set aside and a new one begins; an entry that makes no sense is
+ /// left out.
+ private func read() -> [Entry]? {
+ var info = stat()
+ if lstat(url.path(percentEncoded: false), &info) != 0 {
+ return errno == ENOENT ? [] : nil
+ }
+ guard let data = try? Data(contentsOf: url) else { return nil }
+ guard let entries = try? PropertyListDecoder().decode([Readable].self, from: data) else {
+ return DamagedFile.setAside(url) == nil ? nil : []
}
+ return entries.compactMap(\.entry)
}
- private func read() -> [Entry] {
- guard let data = try? Data(contentsOf: url) else { return [] }
- return (try? PropertyListDecoder().decode([Entry].self, from: data)) ?? []
+ private struct Readable: Decodable {
+ let entry: Entry?
+
+ init(from decoder: any Decoder) throws {
+ entry = try? Entry(from: decoder)
+ }
}
private func write(_ entries: some Sequence<Entry>) -> Bool {
diff --git a/Packages/PeelCore/Sources/PeelPrivileged/HelperRefusal.swift b/Packages/PeelCore/Sources/PeelPrivileged/HelperRefusal.swift
index 19cb5f0e..df3430b9 100644
--- a/Packages/PeelCore/Sources/PeelPrivileged/HelperRefusal.swift
+++ b/Packages/PeelCore/Sources/PeelPrivileged/HelperRefusal.swift
@@ -8,6 +8,7 @@ public enum HelperRefusal: String, CaseIterable, Sendable {
case noTrash = "There’s no Trash to move this to."
case pathTooLong = "The path is too long."
case cannotKeepRecord = "Peel’s helper can’t keep its record of what it moves, so nothing was moved."
+ case cannotReadRecord = "Peel’s helper can’t read its record of what it moved, so nothing was put back."
case notInTrash = "It isn’t in the Trash."
case notMovedByHelper = "Peel’s helper didn’t move this from there, so it stays in the Trash. You can drag it back out in Finder."
case invalidRequest = "The request wasn’t valid."
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/DamagedFileTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/DamagedFileTests.swift
index 49428cf6..ef884be4 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/DamagedFileTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/DamagedFileTests.swift
@@ -1,5 +1,5 @@
import Foundation
-@testable import PeelCore
+import PeelPrivileged
import Testing
struct DamagedFileTests {
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/HelperLedgerTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/HelperLedgerTests.swift
index af54b1a1..631bacb3 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/HelperLedgerTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/HelperLedgerTests.swift
@@ -44,12 +44,12 @@ struct HelperLedgerTests {
try FileManager.default.moveItem(atPath: trashedPath, toPath: renamed)
let trashed = try #require(policy.openInTrash(renamed, trash: trash))
- let origin = try #require(ledger.origin(of: trashed, movedBy: getuid()))
+ let origin = try #require(try ledger.origin(of: trashed, movedBy: getuid()))
#expect(origin.hasSuffix("/root/Library/Caches/com.example.plist"))
- #expect(ledger.origin(of: trashed, movedBy: getuid() + 1) == nil, "another account's request was believed")
+ #expect(try ledger.origin(of: trashed, movedBy: getuid() + 1) == nil, "another account's request was believed")
ledger.forget([trashed])
- #expect(ledger.origin(of: trashed, movedBy: getuid()) == nil)
+ #expect(try ledger.origin(of: trashed, movedBy: getuid()) == nil)
}
/// One request can name an item twice, by the same path or by two spellings that reach it. It moves once and
@@ -74,7 +74,7 @@ struct HelperLedgerTests {
let destination = try #require(result.moved[direct])
#expect(result.moved[linked] == destination)
let trashed = try #require(policy.openInTrash(destination, trash: trash))
- #expect(ledger.origin(of: trashed, movedBy: getuid()) != nil, "the ledger forgot the item it moved, so Put Back would refuse it")
+ #expect(try ledger.origin(of: trashed, movedBy: getuid()) != nil, "the ledger forgot the item it moved, so Put Back would refuse it")
}
@Test func knowsNothingAboutAnItemItDidNotMove() throws {
@@ -86,14 +86,14 @@ struct HelperLedgerTests {
// Dropped into the Trash by hand, which is all a crafted record would need without the ledger.
try directory.file("home/.Trash/planted.plist")
let planted = try #require(policy.openInTrash(path("home/.Trash/planted.plist", in: directory), trash: trash))
- #expect(ledger.origin(of: planted, movedBy: getuid()) == nil)
+ #expect(try ledger.origin(of: planted, movedBy: getuid()) == nil)
// The name of something the helper did move, with another file behind it.
let trashedPath = try move("root/Library/Caches/com.example.plist", with: ledger, policy: policy, in: directory)
try FileManager.default.removeItem(atPath: trashedPath)
try Data("swapped".utf8).write(to: URL(filePath: trashedPath))
let swapped = try #require(policy.openInTrash(trashedPath, trash: trash))
- #expect(ledger.origin(of: swapped, movedBy: getuid()) == nil, "ATTACK SUCCEEDED: a file swapped in under the same name is believed")
+ #expect(try ledger.origin(of: swapped, movedBy: getuid()) == nil, "ATTACK SUCCEEDED: a file swapped in under the same name is believed")
}
/// The helper serves each connection on a queue of its own, and each request opens the ledger afresh, so two
@@ -110,7 +110,7 @@ struct HelperLedgerTests {
_ = HelperLedger(at: url)?.record([items[index]], movedBy: getuid())
}
let ledger = try ledger(in: directory)
- #expect(items.filter { ledger.origin(of: $0, movedBy: getuid()) == nil }.isEmpty, "a record was lost")
+ #expect(try items.filter { try ledger.origin(of: $0, movedBy: getuid()) == nil }.isEmpty, "a record was lost")
}
/// Remove Peel has the helper move its ledger to the Trash before it goes, since nothing else can move it. It
@@ -142,6 +142,59 @@ struct HelperLedgerTests {
#expect(FileManager.default.fileExists(atPath: path("root/Library/Caches", in: directory)))
}
+ @Test func setsAsideALedgerItCannotReadAsOneAndStartsAnother() 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()))
+ try Data("damaged".utf8).write(to: directory.url.appending(path: "private/moved.plist"))
+
+ let trashedPath = try move("root/Library/Caches/com.example.plist", with: ledger, policy: policy, in: directory)
+
+ let aside = try FileManager.default.contentsOfDirectory(atPath: path("private", in: directory))
+ .filter { $0.hasPrefix("moved-damaged-") }
+ #expect(aside.count == 1, "the damaged ledger was written over")
+ let kept = try aside.map { try Data(contentsOf: directory.url.appending(path: "private/\($0)")) }
+ #expect(kept == [Data("damaged".utf8)])
+ #expect(try ledger.origin(of: try #require(policy.openInTrash(trashedPath, trash: trash)), movedBy: getuid()) != nil)
+ }
+
+ @Test func oneEntryItCannotReadCostsThatEntryOnly() 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 trashedPath = try move("root/Library/Caches/com.example.plist", with: ledger, policy: policy, in: directory)
+
+ let url = directory.url.appending(path: "private/moved.plist")
+ var entries = try #require(try PropertyListSerialization.propertyList(from: Data(contentsOf: url), format: nil) as? [Any])
+ entries.append(["path": 1])
+ try PropertyListSerialization.data(fromPropertyList: entries, format: .binary, options: 0).write(to: url)
+
+ let trashed = try #require(policy.openInTrash(trashedPath, trash: trash))
+ #expect(try ledger.origin(of: trashed, movedBy: getuid()) != nil, "one entry it could not read emptied the ledger")
+ }
+
+ @Test(.permissionsHold) func movesNothingWhileItsLedgerCannotBeRead() throws {
+ let directory = try TemporaryDirectory()
+ let policy = try policy(in: directory)
+ let ledger = try ledger(in: directory)
+ _ = try move("root/Library/Caches/com.example.plist", with: ledger, policy: policy, in: directory)
+ let url = directory.url.appending(path: "private/moved.plist")
+ let before = try Data(contentsOf: url)
+ try directory.setPermissions(0o000, of: url)
+
+ try directory.file("root/Library/Caches/other.plist")
+ let item = try policy.open(path("root/Library/Caches/other.plist", in: directory)).get()
+ #expect(!ledger.record([item], movedBy: getuid()), "a ledger it could not read was written over")
+ #expect(throws: HelperLedger.Unreadable.self, "a ledger it could not read answered for Put Back") {
+ try ledger.origin(of: item, movedBy: getuid())
+ }
+
+ try directory.setPermissions(0o600, of: url)
+ #expect(try Data(contentsOf: url) == before)
+ }
+
@Test func keepsTheNewestEntriesAndOnlyInAFolderOfItsOwn() throws {
let directory = try TemporaryDirectory()
let policy = try policy(in: directory)
@@ -149,7 +202,7 @@ struct HelperLedgerTests {
let trash = try #require(policy.openTrash(ownedBy: getuid()))
let paths = try ["a.plist", "b.plist", "c.plist"].map { try move("root/Library/Caches/\($0)", with: ledger, policy: policy, in: directory) }
- let origins = try paths.map { ledger.origin(of: try #require(policy.openInTrash($0, trash: trash)), movedBy: getuid()) }
+ let origins = try paths.map { try ledger.origin(of: try #require(policy.openInTrash($0, trash: trash)), movedBy: getuid()) }
#expect(origins.map { $0 != nil } == [false, true, true])
let attributes = try FileManager.default.attributesOfItem(atPath: path("private/moved.plist", in: directory))
diff --git a/Peel/Views/FixedSentenceText.swift b/Peel/Views/FixedSentenceText.swift
index 969a689c..624a5be5 100644
--- a/Peel/Views/FixedSentenceText.swift
+++ b/Peel/Views/FixedSentenceText.swift
@@ -24,6 +24,7 @@ extension FixedSentence {
case .noTrash: "There’s no Trash to move this to."
case .pathTooLong: "The path is too long."
case .cannotKeepRecord: "Peel’s helper can’t keep its record of what it moves, so nothing was moved."
+ case .cannotReadRecord: "Peel’s helper can’t read its record of what it moved, so nothing was put back."
case .notInTrash: "It isn’t in the Trash."
case .notMovedByHelper: "Peel’s helper didn’t move this from there, so it stays in the Trash. You can drag it back out in Finder."
case .invalidRequest: "The request wasn’t valid."
diff --git a/PeelHelper/HelperService.swift b/PeelHelper/HelperService.swift
index 43c50719..831a9d8b 100644
--- a/PeelHelper/HelperService.swift
+++ b/PeelHelper/HelperService.swift
@@ -105,9 +105,13 @@ final class HelperService: NSObject, PeelHelperProtocol {
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(), ledger.origin(of: trashed, movedBy: caller.user) == target.path else {
- return reply(HelperRefusal.notMovedByHelper.rawValue)
+ 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.notMovedByHelper.rawValue) }
switch TrashMover.rename(trashed, to: target.name, in: target.parent) {
case .success:
ledger.forget([trashed])
diff --git a/SAFETY.md b/SAFETY.md
index 09df63d5..04b3c884 100644
--- a/SAFETY.md
+++ b/SAFETY.md
@@ -292,8 +292,9 @@ is deliberately small: no shell, no arbitrary paths, and it fails closed.
it. It keeps its own ledger, in a folder that is root's alone, of what it moved and from where: the item is
recognized by what it is (not by its name or place in the Trash), and it goes back only to the exact place
the helper took it from. Something dropped into your Trash by hand, or swapped in under a known name, stays
- there. A folder that code is loaded from takes back only what is still owned by root and writable by
- nobody else.
+ there. While the ledger can't be read, the helper moves nothing and puts nothing back; one it can't make sense
+ of is kept under another name, never written over, and a new one begins. A folder that code is loaded from
+ takes back only what is still owned by root and writable by nobody else.
If you never install the helper, Peel still works; it just cannot touch what needs administrator rights.
Home lists the helper as required for that reason, and keeps a reminder there until it is installed.