Free fork of NotProton: Windows Steam games in Mac Steam, on CodeWeavers' Wine and Apple's Game Porting Toolkit
Swift apple-silicond3dmetaldxmtdxvkgame-porting-toolkitgptkmac-gamingmacosmetalfxrosetta-2steamsteam-playwinewinecx
fix(install): name the right owner and bundle in write refusals (#391)
Raystorm973b4b7cd395
diff --git a/app/Sources/BridgeplayApp/Model/SteamInstaller.swift b/app/Sources/BridgeplayApp/Model/SteamInstaller.swiftindex 919279d..a191b2b 100644--- a/app/Sources/BridgeplayApp/Model/SteamInstaller.swift+++ b/app/Sources/BridgeplayApp/Model/SteamInstaller.swift@@ -332,7 +332,7 @@ enum SteamInstaller {static func refusalDetail(_ remedy: Remedy, deployed: Bool) -> String? {switch remedy {case .otherAccount: deployed ? mismatchAcrossAccounts : unpatchedAcrossAccounts- case .rootOwned: remedy.advice+ case .rootOwned: deployed ? mismatchRootOwned + " " + remedy.advice : remedy.advicecase .appManagement, .ownership: nil}}@@ -340,6 +340,9 @@ enum SteamInstaller {private static let mismatchAcrossAccounts =String(localized: "Steam has a different copy of Bridgeplay, installed by another account on this Mac. Update Bridgeplay from that account, then try again.")+ private static let mismatchRootOwned =+ String(localized: "Steam has a different copy of Bridgeplay, and this account cannot update it.")+private static let unpatchedAcrossAccounts =String(localized: "Steam has not been set up for Bridgeplay, and this account cannot change it. Install from the account that owns Steam.")diff --git a/app/Sources/BridgeplayApp/Resources/Localization/Localizable.xcstrings b/app/Sources/BridgeplayApp/Resources/Localization/Localizable.xcstringsindex fae8b43..9616d92 100644--- a/app/Sources/BridgeplayApp/Resources/Localization/Localizable.xcstrings+++ b/app/Sources/BridgeplayApp/Resources/Localization/Localizable.xcstrings@@ -8453,6 +8453,22 @@}}},+ "Steam has a different copy of Bridgeplay, and this account cannot update it." : {+ "localizations" : {+ "it" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Steam ha una copia diversa di Bridgeplay e questo account non può aggiornarla."+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Steam 中有另一份 Bridgeplay,而此账户无法更新它。"+ }+ }+ }+ },"Steam has a different copy of Bridgeplay, installed by another account on this Mac. Update Bridgeplay from that account, then try again." : {"localizations" : {"it" : {@@ -9685,18 +9701,18 @@}}},- "This folder belongs to the system (root), not to your account, so Bridgeplay cannot change it. An administrator has to make your account its owner." : {+ "This folder belongs to the system (root), and your account cannot write to it. Try again from an administrator account, or ask an administrator for help." : {"localizations" : {"it" : {"stringUnit" : {"state" : "translated",- "value" : "Questa cartella appartiene al sistema (root), non al tuo account, quindi Bridgeplay non può modificarla. Un amministratore deve rendere il tuo account proprietario."+ "value" : "Questa cartella appartiene al sistema (root) e il tuo account non può scriverci. Riprova da un account amministratore oppure chiedi aiuto a un amministratore."}},"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "此文件夹属于系统(root),而不是你的账户,因此 Bridgeplay 无法修改它。需要由管理员将其所有者改为你的账户。"+ "value" : "此文件夹属于系统(root),你的账户无法写入。请使用管理员账户重试,或向管理员寻求帮助。"}}}diff --git a/app/Sources/BridgeplayApp/Support/RemoveEverythingCommand.swift b/app/Sources/BridgeplayApp/Support/RemoveEverythingCommand.swiftindex 9075a4b..71f63c7 100644--- a/app/Sources/BridgeplayApp/Support/RemoveEverythingCommand.swift+++ b/app/Sources/BridgeplayApp/Support/RemoveEverythingCommand.swift@@ -36,18 +36,10 @@ enum RemoveEverythingCommand {static func failureMessage(_ error: Error) -> String {guard let refused = error as? WriteRefused else { return error.localizedDescription }- let advice = switch refused.remedy {- case .appManagement:- "Allow your terminal app in System Settings > Privacy & Security > App Management, then run it again."- case .otherAccount:- "Steam was installed by another account on this Mac. Run this again while logged in to that account."- case .rootOwned(let bundle?):- "\(bundle) belongs to root. Make your account its owner with: \(Remedy.chownCommand(bundle))"- case .rootOwned(nil):- "The folder belongs to root. An administrator has to make your account its owner."- case .ownership:- "Check permissions, make sure your user owns the folder."- }+ // Only App Management names a different app here: the terminal, not Bridgeplay.+ let advice = refused.remedy == .appManagement+ ? "Allow your terminal app in System Settings > Privacy & Security > App Management, then run it again."+ : refused.remedy.advicereturn "Could not write \(refused.path). \(advice)"}diff --git a/app/Sources/BridgeplayApp/Support/WriteRefused.swift b/app/Sources/BridgeplayApp/Support/WriteRefused.swiftindex ce8a8dc..3e07918 100644--- a/app/Sources/BridgeplayApp/Support/WriteRefused.swift+++ b/app/Sources/BridgeplayApp/Support/WriteRefused.swift@@ -5,6 +5,13 @@ import Foundationstruct WriteRefused: LocalizedError {let path: String+ // Worked out when the write fails, while the folder is as the write found it.+ let remedy: Remedy++ init(path: String, remedy: Remedy? = nil) {+ self.path = path+ self.remedy = remedy ?? Remedy(forPath: path)+ }var errorDescription: String? { String(localized: "Could not write files.") }}@@ -21,8 +28,6 @@ extension WriteRefused {static func catching<T>(_ url: URL, _ body: () throws -> T) throws -> T {try catching(url.path(percentEncoded: false), body)}-- var remedy: Remedy { Remedy(forPath: path) }}// A write failure generally equals App Management permission error@@ -31,7 +36,7 @@ enum Remedy: Hashable {case appManagementcase otherAccount// Root owns it (MDM, `sudo cp`). Only a bundle gets a chown command: a root folder- // outside one may be /Applications itself.+ // outside one may be /Applications itself, which nobody should take over.case rootOwned(bundle: String?)case ownership@@ -46,12 +51,14 @@ enum Remedy: Hashable {case .rootOwned(let bundle?):String(localized: "\(bundle) belongs to the system (root), not to your account, so Bridgeplay cannot change it. An administrator has to make your account its owner, for example by running this in Terminal: \(Self.chownCommand(bundle))")case .rootOwned(nil):- String(localized: "This folder belongs to the system (root), not to your account, so Bridgeplay cannot change it. An administrator has to make your account its owner.")+ String(localized: "This folder belongs to the system (root), and your account cannot write to it. Try again from an administrator account, or ask an administrator for help.")case .ownership: String(localized: "Check permissions, make sure your user owns the folder.")}}// Names this account rather than $(whoami): the administrator may run it from their own.+ // One owning account is what dragging Steam.app in gives; other accounts are already+ // handled as .otherAccount.static func chownCommand(_ path: String, user: String = NSUserName()) -> String {func quoted(_ word: String) -> String { "'" + word.replacingOccurrences(of: "'", with: "'\\''") + "'" }return "sudo chown -R \(quoted(user)) \(quoted(path))"@@ -75,7 +82,20 @@ enum Remedy: Hashable {NSWorkspace.shared.open(pane)}- static func owner(of path: String) -> uid_t? {+ struct Owner: Equatable {+ var uid: uid_t+ var gid: gid_t+ var mode: Int++ // The POSIX check: owner bits for the owner, group bits for a member, other bits otherwise.+ func letsWrite(_ user: uid_t, groups: Set<gid_t>) -> Bool {+ if uid == user { return mode & 0o200 != 0 }+ if groups.contains(gid) { return mode & 0o020 != 0 }+ return mode & 0o002 != 0+ }+ }++ static func owner(of path: String) -> Owner? {let files = FileManager.defaultlet url = URL(filePath: path)for candidate in [url, url.deletingLastPathComponent()] {@@ -83,39 +103,69 @@ enum Remedy: Hashable {let attributes = try? files.attributesOfItem(atPath: candidate.path(percentEncoded: false)),- let owner = attributes[.ownerAccountID] as? NSNumber+ let uid = attributes[.ownerAccountID] as? NSNumber,+ let gid = attributes[.groupOwnerAccountID] as? NSNumber,+ let mode = attributes[.posixPermissions] as? NSNumberelse { continue }- return uid_t(owner.uint32Value)+ return Owner(uid: uid_t(uid.uint32Value), gid: gid_t(gid.uint32Value), mode: mode.intValue)}return nil}+ static func groups(of user: String = NSUserName(), primary: gid_t = getgid()) -> Set<gid_t> {+ var size: Int32 = 64+ while size <= 4096 {+ var list = [Int32](repeating: 0, count: Int(size))+ var count = size+ if getgrouplist(user, Int32(bitPattern: primary), &list, &count) == 0 {+ return Set(list.prefix(Int(count)).map { gid_t(bitPattern: $0) })+ }+ size *= 2+ }+ return [primary]+ }++ // The outermost one, so a refusal inside Steam Helper.app names Steam.app.static func enclosingBundle(of path: String) -> String? {let files = FileManager.defaultvar directory = URL(filePath: path)+ var outermost: String?while directory.pathComponents.count > 1 {let plist = directory.appending(path: "Contents/Info.plist")if files.fileExists(atPath: plist.path(percentEncoded: false)) {var bundle = directory.path(percentEncoded: false)if bundle.count > 1, bundle.hasSuffix("/") { bundle.removeLast() }- return bundle+ outermost = bundle}directory = directory.deletingLastPathComponent()}- return nil+ return outermost}init(forPath path: String,- owner: (String) -> uid_t? = Remedy.owner(of:),- user: uid_t = getuid()+ owner: (String) -> Owner? = Remedy.owner(of:),+ user: uid_t = getuid(),+ groups: @autoclosure () -> Set<gid_t> = Remedy.groups()) {- let bundle = Self.enclosingBundle(of: path)- switch owner(path) {- case 0? where user != 0: self = .rootOwned(bundle: bundle)- case let other? where other != user: self = .otherAccount- default: self = bundle == nil ? .ownership : .appManagement+ // A folder the permissions let this account write was refused by App Management,+ // whoever owns it (a root:admin 775 Steam.app, for an admin).+ if let owner = owner(path), owner.uid != user, !owner.letsWrite(user, groups: groups()) {+ self = owner.uid == 0 ? .rootOwned(bundle: Self.enclosingBundle(of: path)) : .otherAccount+ return+ }+ self = Self.enclosingBundle(of: path) == nil ? .ownership : .appManagement+ }++ // One piece of advice for several refusals. Root-owned folders in different places+ // share theirs without a command, since no single chown covers them all.+ static func shared(by remedies: [Remedy]) -> Remedy? {+ let distinct = Set(remedies)+ if distinct.count == 1 { return distinct.first }+ let allRoot = !distinct.isEmpty && distinct.allSatisfy {+ if case .rootOwned = $0 { true } else { false }}+ return allRoot ? .rootOwned(bundle: nil) : nil}}@@ -132,8 +182,7 @@ struct FailureReport {let reasons = errors.map(\.localizedDescription).filter { seen.insert($0).inserted }let refusals = errors.compactMap { $0 as? WriteRefused }- let wanted = Set(refusals.map(\.remedy))- remedy = refusals.count == errors.count && wanted.count == 1 ? wanted.first : nil+ remedy = refusals.count == errors.count ? Remedy.shared(by: refusals.map(\.remedy)) : nilvar parts = reasonsif let advice = remedy?.advice { parts.append(advice) }diff --git a/app/Tests/BridgeplayAppTests/RemedyOwnerTests.swift b/app/Tests/BridgeplayAppTests/RemedyOwnerTests.swiftindex 12d4ace..a19cc1c 100644--- a/app/Tests/BridgeplayAppTests/RemedyOwnerTests.swift+++ b/app/Tests/BridgeplayAppTests/RemedyOwnerTests.swift@@ -8,6 +8,17 @@ import Testingstruct RemedyOwnerTests {private static let user: uid_t = 501+ private static let staff: gid_t = 20+ private static let admin: gid_t = 80++ private static func owned(by uid: uid_t, group: gid_t = 0, mode: Int = 0o755) -> (String) -> Remedy.Owner? {+ { _ in Remedy.Owner(uid: uid, gid: group, mode: mode) }+ }++ private func remedy(_ path: String, _ owner: @escaping (String) -> Remedy.Owner?,+ groups: Set<gid_t> = [staff]) -> Remedy {+ Remedy(forPath: path, owner: owner, user: Self.user, groups: groups)+ }private func steamBundle() throws -> (root: URL, app: URL, inside: String) {let root = URL.temporaryDirectory.appending(path: "np-owner-\(UUID().uuidString)")@@ -23,18 +34,62 @@ struct RemedyOwnerTests {let steam = try steamBundle()defer { try? FileManager.default.removeItem(at: steam.root) }- let remedy = Remedy(forPath: steam.inside, owner: { _ in 0 }, user: Self.user)+ let found = remedy(steam.inside, Self.owned(by: 0))++ #expect(found == .rootOwned(bundle: steam.app.path(percentEncoded: false)))+ #expect(found.settingsPane == nil)+ }++ @Test("A refusal inside a nested app names the outer bundle")+ func nestedAppNamesTheOuterBundle() throws {+ let steam = try steamBundle()+ defer { try? FileManager.default.removeItem(at: steam.root) }+ let helper = steam.app.appending(path: "Contents/MacOS/Frameworks/Steam Helper.app")+ try FileManager.default.createDirectory(+ at: helper.appending(path: "Contents/MacOS"), withIntermediateDirectories: true+ )+ try Data("{}".utf8).write(to: helper.appending(path: "Contents/Info.plist"))++ let inside = helper.appending(path: "Contents/MacOS").path(percentEncoded: false)- #expect(remedy == .rootOwned(bundle: steam.app.path(percentEncoded: false)))- #expect(remedy.settingsPane == nil)+ #expect(remedy(inside, Self.owned(by: 0)) == .rootOwned(bundle: steam.app.path(percentEncoded: false)))}@Test("A root folder outside a bundle gets no chown command")func rootOwnedFolder() {- let remedy = Remedy(forPath: "/nonexistent/folder", owner: { _ in 0 }, user: Self.user)+ let found = remedy("/nonexistent/folder", Self.owned(by: 0))++ #expect(found == .rootOwned(bundle: nil))+ #expect(!found.advice.contains("chown"))+ #expect(!found.advice.contains("its owner"), "advised taking over a system folder")+ }++ // /Applications itself is root:admin 775. A target missing under it is looked up there.+ @Test("A missing target under /Applications is not advised to take over /Applications")+ func missingTargetUnderApplications() {+ let found = remedy("/Applications/np-missing-\(UUID().uuidString).app",+ Self.owned(by: 0, group: Self.admin, mode: 0o775))++ #expect(found == .rootOwned(bundle: nil))+ #expect(!found.advice.contains("chown"))+ }++ @Test("A root:admin group-writable bundle asks an admin for App Management")+ func groupWritableBundleAsksForAppManagement() throws {+ let steam = try steamBundle()+ defer { try? FileManager.default.removeItem(at: steam.root) }+ let owner = Self.owned(by: 0, group: Self.admin, mode: 0o775)++ #expect(remedy(steam.inside, owner, groups: [Self.staff, Self.admin]) == .appManagement)+ #expect(remedy(steam.inside, owner, groups: [Self.staff]) == .rootOwned(bundle: steam.app.path(percentEncoded: false)))+ }- #expect(remedy == .rootOwned(bundle: nil))- #expect(!remedy.advice.contains("chown"))+ @Test("A world-writable bundle another account owns asks for App Management")+ func worldWritableBundleAsksForAppManagement() throws {+ let steam = try steamBundle()+ defer { try? FileManager.default.removeItem(at: steam.root) }++ #expect(remedy(steam.inside, Self.owned(by: 502, group: Self.staff, mode: 0o777)) == .appManagement)}@Test("A bundle another user owns is still another account's")@@ -42,7 +97,7 @@ struct RemedyOwnerTests {let steam = try steamBundle()defer { try? FileManager.default.removeItem(at: steam.root) }- #expect(Remedy(forPath: steam.inside, owner: { _ in 502 }, user: Self.user) == .otherAccount)+ #expect(remedy(steam.inside, Self.owned(by: 502, group: Self.staff)) == .otherAccount)}@Test("Root running the app owns what root owns")@@ -50,7 +105,7 @@ struct RemedyOwnerTests {let steam = try steamBundle()defer { try? FileManager.default.removeItem(at: steam.root) }- #expect(Remedy(forPath: steam.inside, owner: { _ in 0 }, user: 0) == .appManagement)+ #expect(Remedy(forPath: steam.inside, owner: Self.owned(by: 0), user: 0, groups: [0]) == .appManagement)}@Test("An own folder inside a bundle asks for App Management")@@ -59,7 +114,7 @@ struct RemedyOwnerTests {defer { try? FileManager.default.removeItem(at: steam.root) }#expect(Remedy(forPath: steam.inside) == .appManagement)- #expect(Remedy(forPath: steam.inside, owner: { _ in Self.user }, user: Self.user) == .appManagement)+ #expect(remedy(steam.inside, Self.owned(by: Self.user, group: Self.staff)) == .appManagement)}@Test("An own folder outside a bundle asks to check ownership")@@ -71,6 +126,24 @@ struct RemedyOwnerTests {#expect(Remedy(forPath: root.path(percentEncoded: false)) == .ownership)}+ @Test("The real lookup reads owner, group and mode")+ func realLookup() throws {+ let owner = try #require(Remedy.owner(of: "/usr/bin"))++ #expect(owner.uid == 0)+ #expect(!owner.letsWrite(Self.user, groups: [Self.staff, Self.admin]))+ #expect(Remedy.groups().contains(getgid()))+ }++ @Test("The remedy is fixed when the write is refused")+ func remedyIsTakenAtRefusal() throws {+ let steam = try steamBundle()+ let refusal = WriteRefused(path: steam.inside)+ try FileManager.default.removeItem(at: steam.root)++ #expect(refusal.remedy == .appManagement)+ }+@Test("The advice names the bundle and a command that hands it over")func adviceCarriesTheCommand() {let advice = Remedy.rootOwned(bundle: "/Applications/Steam.app").advice@@ -88,14 +161,53 @@ struct RemedyOwnerTests {)}+ @Test("Refusals root owns in one bundle keep the command")+ func oneRootBundleKeepsTheCommand() throws {+ let steam = Remedy.rootOwned(bundle: "/Applications/Steam.app")+ let report = try #require(FailureReport([+ WriteRefused(path: "/Applications/Steam.app/Contents/MacOS", remedy: steam),+ WriteRefused(path: "/Applications/Steam.app/Contents/Info.plist", remedy: steam),+ ]))++ #expect(report.remedy == steam)+ #expect(report.message.contains("sudo chown -R"))+ }++ @Test("Refusals root owns in different places still get advice")+ func rootRefusalsInDifferentPlacesShareAdvice() throws {+ let report = try #require(FailureReport([+ WriteRefused(path: "/Applications/Steam.app/Contents/MacOS",+ remedy: .rootOwned(bundle: "/Applications/Steam.app")),+ WriteRefused(path: "/Library/Shared/np", remedy: .rootOwned(bundle: nil)),+ ]))++ #expect(report.remedy == .rootOwned(bundle: nil))+ #expect(report.message.contains("belongs to the system (root)"))+ #expect(!report.message.contains("chown"))+ }++ @Test("Refusals with different causes share no advice")+ func mixedRefusalsShareNothing() throws {+ let report = try #require(FailureReport([+ WriteRefused(path: "/a", remedy: .rootOwned(bundle: nil)),+ WriteRefused(path: "/b", remedy: .otherAccount),+ ]))++ #expect(report.remedy == nil)+ }+@Test("Installing into a root-owned Steam says root owns it, not another account")func installerNamesRoot() throws {let root = Remedy.rootOwned(bundle: "/Applications/Steam.app")- for deployed in [false, true] {- let detail = try #require(SteamInstaller.refusalDetail(root, deployed: deployed))- #expect(detail.contains("(root)"))- #expect(detail.contains("sudo chown -R"))+ let unpatched = try #require(SteamInstaller.refusalDetail(root, deployed: false))+ #expect(unpatched == root.advice)++ let mismatch = try #require(SteamInstaller.refusalDetail(root, deployed: true))+ #expect(mismatch.hasPrefix("Steam has a different copy of Bridgeplay, and this account cannot update it."))+ #expect(mismatch.hasSuffix(root.advice))++ for detail in [unpatched, mismatch] {#expect(!detail.contains("another account"))#expect(!detail.contains("account that owns Steam"))}@@ -112,12 +224,13 @@ struct RemedyOwnerTests {#expect(SteamInstaller.refusalDetail(.ownership, deployed: true) == nil)}- @Test("The command line says root owns it")- func commandLineNamesRoot() {- let refusal = WriteRefused(path: "/usr/bin")- let message = RemoveEverythingCommand.failureMessage(refusal)+ @Test("The command line gives the app's advice, except for App Management")+ func commandLineSharesTheAdvice() {+ let root = Remedy.rootOwned(bundle: "/Applications/Steam.app")- #expect(message.contains("belongs to root"))- #expect(!message.contains("another account"))+ #expect(RemoveEverythingCommand.failureMessage(WriteRefused(path: "/x", remedy: root))+ == "Could not write /x. \(root.advice)")+ #expect(RemoveEverythingCommand.failureMessage(WriteRefused(path: "/x", remedy: .appManagement))+ .contains("Allow your terminal app"))}}