Skip to content

Free fork of NotProton: Windows Steam games in Mac Steam, on CodeWeavers' Wine and Apple's Game Porting Toolkit

fix(setup): sign Steam without a keychain password prompt

raymondchinse48c314812b0
diff --git a/app/Sources/BridgeplayApp/Model/LocalSigning.swift b/app/Sources/BridgeplayApp/Model/LocalSigning.swift
index 46acea4..8cfc2d5 100644
--- a/app/Sources/BridgeplayApp/Model/LocalSigning.swift
+++ b/app/Sources/BridgeplayApp/Model/LocalSigning.swift
@@ -1,23 +1,27 @@
import Foundation
+import Security
// Creates the self-signed code signing identity that SteamInstaller signs Steam with, so
// Steam's designated requirement (and with it the Input Monitoring approval macOS keys to
// it) stays the same across Bridgeplay updates. Without it Steam is signed ad hoc, the
// requirement is the cdhash, and every update makes macOS forget the controller approval.
//
-// Design, checked on macOS 27 with a throwaway keychain:
-// - The key and certificate come from /usr/bin/openssl (LibreSSL 3.3.6 accepts -addext)
-// and go in through `security import -T /usr/bin/codesign`. The key's access list then
-// names codesign, so signing never shows a keychain prompt. A key made with
-// SecKeyCreateRandomKey inside this app would instead belong to this app's own
-// signature, which changes with every ad hoc Bridgeplay build, and codesign would ask.
-// - Nothing calls `security set-key-partition-list`: it needs the keychain password, and
-// the import above already leaves codesign able to use the key without asking.
-// - The certificate is NOT marked trusted (`security add-trusted-cert`). codesign signs
-// with an untrusted identity just as well; the designated requirement is then
-// `certificate leaf = H"<sha1>"`, which is what the owner's existing identity produces.
-// Trusting it would cost a password prompt and could change that requirement's form
-// (leaf to root), which would make macOS drop the approval once more.
+// Design, checked on macOS 27:
+// - The identity lives in a keychain of Bridgeplay's own, in the support folder and outside
+// the user's search list, with a random password. A key that `security import` adds,
+// even with `-T /usr/bin/codesign`, carries a partition list codesign is not in, so in the
+// login keychain macOS asked for the login password once per signed file until the user
+// picked Always Allow. Only the keychain's password can change that list, and Bridgeplay
+// knows this one: `set-key-partition-list -S apple-tool:,apple:,codesign:` runs at
+// creation and codesign never asks.
+// - The keychain stays locked except while Steam is signed. Its password is a generic
+// password in the login keychain that only Bridgeplay's signature can read, so other
+// processes can't unlock it and sign as Steam (after Always Allow, any process could run
+// codesign with the login keychain key).
+// - Macs that already have the identity in the login keychain keep using it: a new
+// certificate would change Steam's requirement and drop the controller approval once more.
+// - The key and certificate come from /usr/bin/openssl. The certificate is NOT marked
+// trusted, so the designated requirement is `certificate leaf = H"<sha1>"`.
// - The name stays "NotProton Local Signing": existing installs look it up by that name.
enum LocalSigning {
@@ -28,8 +32,15 @@ enum LocalSigning {
static let realRunner: Runner = { try Shell.run($0, $1) }
- static var loginKeychain: URL {
- SupportPaths.home.appending(path: "Library/Keychains/login.keychain-db")
+ static var privateKeychain: URL {
+ SupportPaths.support.appending(path: "signing/local-signing.keychain-db")
+ }
+
+ // Where the identity is: `keychain` is nil for one in the user's search list (the login
+ // keychain of older installs), else Bridgeplay's own keychain, passed to codesign.
+ struct Identity: Equatable, Sendable {
+ let hash: String
+ let keychain: URL?
}
enum Outcome: Equatable, Sendable {
@@ -37,6 +48,45 @@ enum LocalSigning {
case created(hash: String)
}
+ // The private keychain's password, kept in the login keychain.
+ struct Secrets: Sendable {
+ var save: @Sendable (String) throws -> Void
+ var load: @Sendable () -> String?
+ var delete: @Sendable () -> Void
+
+ static let service = "com.bridgeplay.local-signing"
+
+ private static var query: [String: Any] {
+ [kSecClass as String: kSecClassGenericPassword,
+ kSecAttrService as String: service,
+ kSecAttrAccount as String: "keychain"]
+ }
+
+ static let live = Secrets(
+ save: { password in
+ SecItemDelete(query as CFDictionary)
+ var item = query
+ item[kSecAttrLabel as String] = "Bridgeplay signing keychain"
+ item[kSecValueData as String] = Data(password.utf8)
+ let status = SecItemAdd(item as CFDictionary, nil)
+ guard status == errSecSuccess else {
+ AppLog.note("signing: saving the keychain password failed: \(status)")
+ throw StepFailure(step: step, detail: String(localized: "macOS did not add the certificate to your keychain."))
+ }
+ },
+ load: {
+ var read = query
+ read[kSecReturnData as String] = true
+ read[kSecMatchLimit as String] = kSecMatchLimitOne
+ var result: CFTypeRef?
+ guard SecItemCopyMatching(read as CFDictionary, &result) == errSecSuccess,
+ let data = result as? Data else { return nil }
+ return String(data: data, encoding: .utf8)
+ },
+ delete: { SecItemDelete(query as CFDictionary) }
+ )
+ }
+
// `security find-identity -p codesigning` without -v, so an untrusted identity, which
// is what this creates, still counts. Each line reads ` 1) <SHA-1> "<name>" (...)`.
static func identityHash(in output: String, named wanted: String = name) -> String? {
@@ -56,6 +106,15 @@ enum LocalSigning {
return identityHash(in: result.stdout)
}
+ // An identity from an older install in the search list first, then Bridgeplay's own.
+ static func existing(lookIn: [URL] = [], privateKeychain: URL = privateKeychain,
+ run: Runner = realRunner) -> Identity? {
+ if let hash = existingHash(in: lookIn, run: run) { return Identity(hash: hash, keychain: nil) }
+ guard FileManager.default.fileExists(atPath: privateKeychain.path(percentEncoded: false)),
+ let hash = existingHash(in: [privateKeychain], run: run) else { return nil }
+ return Identity(hash: hash, keychain: privateKeychain)
+ }
+
struct Command: Equatable, Sendable {
let executable: String
let arguments: [String]
@@ -63,11 +122,14 @@ enum LocalSigning {
// The commands that make the identity, in order. The key only ever exists in `work`,
// which ensure() creates private to this user and removes afterwards.
- static func creationCommands(work: URL, keychain: URL, transportPassword: String) -> [Command] {
+ static func creationCommands(work: URL, keychain: URL, keychainPassword: String,
+ transportPassword: String) -> [Command] {
let key = work.appending(path: "key.pem").path(percentEncoded: false)
let cert = work.appending(path: "cert.pem").path(percentEncoded: false)
let bundle = work.appending(path: "identity.p12").path(percentEncoded: false)
+ let path = keychain.path(percentEncoded: false)
return [
+ Command(executable: "/usr/bin/security", arguments: ["create-keychain", "-p", keychainPassword, path]),
Command(executable: "/usr/bin/openssl", arguments: [
"req", "-x509", "-newkey", "rsa:2048", "-nodes", "-sha256", "-days", "7300",
"-subj", "/CN=\(name)",
@@ -82,43 +144,115 @@ enum LocalSigning {
"pkcs12", "-export", "-inkey", key, "-in", cert, "-name", name,
"-out", bundle, "-passout", "pass:\(transportPassword)",
]),
+ Command(executable: "/usr/bin/security", arguments: ["unlock-keychain", "-p", keychainPassword, path]),
+ Command(executable: "/usr/bin/security", arguments: [
+ "import", bundle, "-k", path, "-f", "pkcs12", "-P", transportPassword, "-T", "/usr/bin/codesign",
+ ]),
Command(executable: "/usr/bin/security", arguments: [
- "import", bundle, "-k", keychain.path(percentEncoded: false), "-f", "pkcs12",
- "-P", transportPassword, "-T", "/usr/bin/codesign",
+ "set-key-partition-list", "-S", "apple-tool:,apple:,codesign:", "-s", "-k", keychainPassword, path,
]),
+ Command(executable: "/usr/bin/security", arguments: ["lock-keychain", path]),
]
}
- // Creates the identity unless one with this name is already there. Never asks for a
- // password, except macOS's own prompt to unlock a locked login keychain.
+ // Creates the identity unless one is already there. Never asks for a password.
static func ensure(
- keychain: URL = loginKeychain,
+ privateKeychain: URL = privateKeychain,
lookIn: [URL] = [],
run: Runner = realRunner,
+ secrets: Secrets = .live,
temporaryRoot: URL = FileManager.default.temporaryDirectory
) throws -> Outcome {
- if let hash = existingHash(in: lookIn, run: run) {
- return .alreadyPresent(hash: hash)
+ if let identity = existing(lookIn: lookIn, privateKeychain: privateKeychain, run: run) {
+ return .alreadyPresent(hash: identity.hash)
}
let files = FileManager.default
let work = temporaryRoot.appending(path: "bridgeplay-signing-\(UUID().uuidString)", directoryHint: .isDirectory)
try files.createDirectory(at: work, withIntermediateDirectories: true,
attributes: [.posixPermissions: 0o700])
defer { try? files.removeItem(at: work) }
+ try files.createDirectory(at: privateKeychain.deletingLastPathComponent(), withIntermediateDirectories: true,
+ attributes: [.posixPermissions: 0o700])
+ // A keychain left by a failed attempt has a password nobody kept.
+ try? files.removeItem(at: privateKeychain)
- let password = UUID().uuidString
- for command in creationCommands(work: work, keychain: keychain, transportPassword: password) {
- let result = try run(command.executable, command.arguments)
- guard result.succeeded else {
- let tool = (command.executable as NSString).lastPathComponent
- AppLog.note("signing: \(tool) \(command.arguments.first ?? "") failed: \(result.stderr.trimmingCharacters(in: .whitespacesAndNewlines))")
- throw StepFailure(step: step, detail: String(localized: "macOS did not add the certificate to your keychain."))
+ let password = randomPassword()
+ try secrets.save(password)
+ var created = false
+ do {
+ for command in creationCommands(work: work, keychain: privateKeychain, keychainPassword: password,
+ transportPassword: UUID().uuidString) {
+ let result = try run(command.executable, command.arguments)
+ guard result.succeeded else {
+ let tool = (command.executable as NSString).lastPathComponent
+ AppLog.note("signing: \(tool) \(command.arguments.first ?? "") failed: \(result.stderr.trimmingCharacters(in: .whitespacesAndNewlines))")
+ throw StepFailure(step: step, detail: String(localized: "macOS did not add the certificate to your keychain."))
+ }
+ if command.arguments.first == "create-keychain" {
+ created = true
+ leaveSearchList(privateKeychain, run: run)
+ }
+ }
+ guard let hash = existingHash(in: [privateKeychain], run: run) else {
+ throw StepFailure(step: step, detail: String(localized: "The certificate was added, but macOS does not offer it for signing."))
}
+ AppLog.note("signing: created \(name) \(hash) in Bridgeplay's keychain")
+ return .created(hash: hash)
+ } catch {
+ if created { _ = try? run("/usr/bin/security", ["delete-keychain", privateKeychain.path(percentEncoded: false)]) }
+ try? files.removeItem(at: privateKeychain)
+ secrets.delete()
+ throw error
+ }
+ }
+
+ // Some macOS versions add a new keychain to the user's search list. A locked keychain
+ // there could make other apps ask for a password the user never set, so it comes out.
+ // Every other entry is passed back as it was, one argument each.
+ static func leaveSearchList(_ keychain: URL, run: Runner = realRunner) {
+ guard let result = try? run("/usr/bin/security", ["list-keychains", "-d", "user"]), result.succeeded else { return }
+ let ours = keychain.resolvingSymlinksInPath().path(percentEncoded: false)
+ let entries = result.stdout.split(separator: "\n")
+ .map { $0.trimmingCharacters(in: .whitespaces).trimmingCharacters(in: CharacterSet(charactersIn: "\"")) }
+ .filter { !$0.isEmpty }
+ let others = entries.filter { URL(filePath: $0).resolvingSymlinksInPath().path(percentEncoded: false) != ours }
+ guard others.count == entries.count - 1, !others.isEmpty else { return }
+ _ = try? run("/usr/bin/security", ["list-keychains", "-d", "user", "-s"] + others)
+ }
+
+ // Runs `body` with Bridgeplay's keychain unlocked and locks it again after. `body` gets
+ // the identity to sign with: nil when the keychain can't be unlocked, so Steam is signed
+ // ad hoc. codesign must never meet that keychain locked: on macOS 27 an attempt leaves it
+ // refusing its own password afterwards. An identity in the search list needs nothing.
+ static func unlocked<T>(_ identity: Identity?, secrets: Secrets = .live, _ body: (Identity?) throws -> T) rethrows -> T {
+ guard let identity, let path = identity.keychain?.path(percentEncoded: false) else { return try body(identity) }
+ var keychain: SecKeychain?
+ guard SecKeychainOpen(path, &keychain) == errSecSuccess, let keychain, let password = secrets.load() else {
+ AppLog.note("signing: Bridgeplay's keychain or its password is missing, signing ad hoc")
+ return try body(nil)
+ }
+ let bytes = Array(password.utf8)
+ let status = SecKeychainUnlock(keychain, UInt32(bytes.count), bytes, true)
+ var state: SecKeychainStatus = 0
+ guard status == errSecSuccess, SecKeychainGetStatus(keychain, &state) == errSecSuccess,
+ state & UInt32(kSecUnlockStateStatus) != 0 else {
+ AppLog.note("signing: unlocking Bridgeplay's keychain failed (\(status)), signing ad hoc")
+ return try body(nil)
}
- guard let hash = existingHash(in: lookIn, run: run) else {
- throw StepFailure(step: step, detail: String(localized: "The certificate was added, but macOS does not offer it for signing."))
+ defer { SecKeychainLock(keychain) }
+ return try body(identity)
+ }
+
+ // Uninstall: the keychain file goes with the support folder, its password goes here.
+ static func forgetPrivateKeychain(secrets: Secrets = .live) {
+ secrets.delete()
+ }
+
+ private static func randomPassword() -> String {
+ var bytes = [UInt8](repeating: 0, count: 32)
+ if SecRandomCopyBytes(kSecRandomDefault, bytes.count, &bytes) != errSecSuccess {
+ return UUID().uuidString + UUID().uuidString
}
- AppLog.note("signing: created \(name) \(hash)")
- return .created(hash: hash)
+ return bytes.map { String(format: "%02x", $0) }.joined()
}
}
diff --git a/app/Sources/BridgeplayApp/Model/SteamInstaller.swift b/app/Sources/BridgeplayApp/Model/SteamInstaller.swift
index 88fbbc4..fdba4c1 100644
--- a/app/Sources/BridgeplayApp/Model/SteamInstaller.swift
+++ b/app/Sources/BridgeplayApp/Model/SteamInstaller.swift
@@ -203,10 +203,11 @@ enum SteamInstaller {
try setInsert(at: plist, to: dylib)
report(.signing)
- let identity = signingIdentity()
- try sign(dylib, identity: identity)
- try sign(app.appending(path: "Contents/MacOS/steam_osx"), identity: identity)
- try sign(app, identity: identity)
+ try LocalSigning.unlocked(signingIdentity()) { identity in
+ try sign(dylib, identity: identity)
+ try sign(app.appending(path: "Contents/MacOS/steam_osx"), identity: identity)
+ try sign(app, identity: identity)
+ }
} catch {
do {
try revertPlist(priorPlist, at: plist, app: app)
@@ -428,23 +429,29 @@ enum SteamInstaller {
try sign(url, identity: "-", step: step)
}
- // A self-signed code signing identity in the login keychain. When it exists Steam is signed
- // with it instead of ad hoc, which keeps its designated requirement, and with it the user's
- // Input Monitoring approval, the same across Bridgeplay updates.
+ // A self-signed code signing identity, in Bridgeplay's own keychain (or the login keychain
+ // on older installs). When it exists Steam is signed with it instead of ad hoc, which keeps
+ // its designated requirement, and with it the user's Input Monitoring approval, the same
+ // across Bridgeplay updates.
static let localSigningIdentity = "NotProton Local Signing"
// LocalSigning creates it from the Setup Assistant or the Status page.
- static func signingIdentity() -> String {
- LocalSigning.existingHash() ?? "-"
+ static func signingIdentity() -> LocalSigning.Identity? {
+ LocalSigning.existing()
+ }
+
+ static func sign(_ url: URL, identity: LocalSigning.Identity?, step: String = step) throws {
+ try sign(url, identity: identity?.hash ?? "-", keychain: identity?.keychain, step: step)
}
- static func sign(_ url: URL, identity: String, step: String = step) throws {
+ static func sign(_ url: URL, identity: String, keychain: URL? = nil, step: String = step) throws {
let path = url.path(percentEncoded: false)
- var result = try Shell.run("/usr/bin/codesign", ["-f", "-s", identity, path])
+ let lookup = keychain.map { ["--keychain", $0.path(percentEncoded: false)] } ?? []
+ var result = try Shell.run("/usr/bin/codesign", ["-f", "-s", identity] + lookup + [path])
// Fixes codesign refusing a Steam.app that carries Finder info or a resource fork.
if !result.succeeded, result.stderr.contains("detritus not allowed") {
clearFinderData(in: enclosingBundle(of: url))
- result = try Shell.run("/usr/bin/codesign", ["-f", "-s", identity, path])
+ result = try Shell.run("/usr/bin/codesign", ["-f", "-s", identity] + lookup + [path])
}
// A keychain that refuses the identity must not leave Steam unsigned.
if !result.succeeded, identity != "-" {
diff --git a/app/Sources/BridgeplayApp/Model/Uninstall.swift b/app/Sources/BridgeplayApp/Model/Uninstall.swift
index 9efe4f9..242c2c3 100644
--- a/app/Sources/BridgeplayApp/Model/Uninstall.swift
+++ b/app/Sources/BridgeplayApp/Model/Uninstall.swift
@@ -72,6 +72,8 @@ enum Uninstall {
var defaultToolBackup: URL
var files: [URL]
var steamRunning: @Sendable () -> Bool
+ // The password of Bridgeplay's signing keychain, kept in the login keychain.
+ var forgetSigning: @Sendable () -> Void = {}
static var live: Leftovers {
Leftovers(
@@ -80,7 +82,8 @@ enum Uninstall {
steamConfig: SteamDefaultTool.config,
defaultToolBackup: SteamDefaultTool.backup,
files: [SupportPaths.homeDir],
- steamRunning: { SteamBundle.isRunningForThisUser })
+ steamRunning: { SteamBundle.isRunningForThisUser },
+ forgetSigning: { LocalSigning.forgetPrivateKeychain() })
}
}
@@ -185,6 +188,7 @@ enum Uninstall {
var removed = try remove(
legacyCompat: legacyCompat, compatTools: compatTools, directories: directories + leftovers.files
)
+ leftovers.forgetSigning()
// The record of modified bundles is kept while one is out of reach, so a later
// removal still finds it.
if missing.isEmpty, try modifications.paths().isEmpty {
diff --git a/app/Sources/BridgeplayApp/SetupAssistant.swift b/app/Sources/BridgeplayApp/SetupAssistant.swift
index 784da92..ad52f57 100644
--- a/app/Sources/BridgeplayApp/SetupAssistant.swift
+++ b/app/Sources/BridgeplayApp/SetupAssistant.swift
@@ -57,6 +57,8 @@ final class SetupAssistant {
// The keychain identity that keeps Steam's controller permission across updates.
enum TrustState: Equatable { case unknown, needed, working, done, declined(String) }
var trust: TrustState = .unknown
+ // An older install's identity in the login keychain, which macOS asks about when Steam is signed.
+ var trustInLoginKeychain = false
// Finish
var tasks: [SetupTask] = SetupAssistant.plannedTasks
@@ -247,8 +249,9 @@ final class SetupAssistant {
func checkTrust() async {
guard trust == .unknown else { return }
- let present = await Task.detached(priority: .utility) { LocalSigning.existingHash() != nil }.value
- if trust == .unknown { trust = present ? .done : .needed }
+ let identity = await Task.detached(priority: .utility) { LocalSigning.existing() }.value
+ trustInLoginKeychain = identity != nil && identity?.keychain == nil
+ if trust == .unknown { trust = identity != nil ? .done : .needed }
}
// One click, no password: see LocalSigning for why no prompt is needed. A failure keeps
@@ -259,6 +262,7 @@ final class SetupAssistant {
if isPreview { await pretend(); trust = .done; return }
do {
_ = try await Task.detached(priority: .userInitiated) { try LocalSigning.ensure() }.value
+ trustInLoginKeychain = await Task.detached(priority: .utility) { LocalSigning.existing()?.keychain == nil }.value
trust = .done
} catch {
AppLog.note("setup: signing identity not created: \(error.localizedDescription)")
diff --git a/app/Sources/BridgeplayApp/SystemStatus.swift b/app/Sources/BridgeplayApp/SystemStatus.swift
index 69266b9..6830448 100644
--- a/app/Sources/BridgeplayApp/SystemStatus.swift
+++ b/app/Sources/BridgeplayApp/SystemStatus.swift
@@ -720,7 +720,7 @@ final class SystemStatus {
private(set) var signingIdentityReady: Bool?
func refreshSigningIdentity() async {
- signingIdentityReady = await Task.detached(priority: .utility) { LocalSigning.existingHash() != nil }.value
+ signingIdentityReady = await Task.detached(priority: .utility) { LocalSigning.existing() != nil }.value
}
func trustThisMac() async {
diff --git a/app/Sources/BridgeplayApp/Views/SetupAssistantView.swift b/app/Sources/BridgeplayApp/Views/SetupAssistantView.swift
index 180ed07..2eaf706 100644
--- a/app/Sources/BridgeplayApp/Views/SetupAssistantView.swift
+++ b/app/Sources/BridgeplayApp/Views/SetupAssistantView.swift
@@ -337,15 +337,14 @@ struct SetupAssistantView: View {
.padding(.horizontal, 2)
}
- // Told before Set Up is pressed, so the macOS dialogs that follow are expected. Signing
- // Steam with the step 3 certificate can make macOS ask for the login password, once per
- // signed file (the add-on, Steam's executable, Steam.app), until the user picks Always
- // Allow: that adds codesign to the key's partition list, which only the login password
- // can change. App Management can ask too.
+ // Told before Set Up is pressed, so the macOS dialogs that follow are expected. An older
+ // install's certificate in the login keychain makes macOS ask for the login password, once
+ // per signed file, until the user picks Always Allow; one in Bridgeplay's own keychain
+ // never asks (LocalSigning). App Management can ask too.
@ViewBuilder
private var approvals: some View {
SetupCard {
- if model.trust == .done {
+ if model.trust == .done, model.trustInLoginKeychain {
WizardRow(row: StatusRow(title: String(localized: "Confirm the Steam update"),
value: String(localized: "macOS asks for your Mac password once, so Steam keeps working with Bridgeplay. Type it and choose Always Allow, and it won't ask again."),
tone: .info))
diff --git a/app/Tests/BridgeplayAppTests/LocalSigningTests.swift b/app/Tests/BridgeplayAppTests/LocalSigningTests.swift
index 3946337..2524a09 100644
--- a/app/Tests/BridgeplayAppTests/LocalSigningTests.swift
+++ b/app/Tests/BridgeplayAppTests/LocalSigningTests.swift
@@ -70,72 +70,149 @@ struct LocalSigningTests {
#expect(fake.commands == [["/usr/bin/security", "find-identity", "-p", "codesigning"]])
}
- @Test("A missing identity is made with openssl and imported for codesign only")
+ private final class MemorySecrets: @unchecked Sendable {
+ private let lock = NSLock()
+ private var stored: String?
+ var value: String? { lock.withLock { stored } }
+ var secrets: LocalSigning.Secrets {
+ LocalSigning.Secrets(save: { value in self.lock.withLock { self.stored = value } },
+ load: { self.lock.withLock { self.stored } },
+ delete: { self.lock.withLock { self.stored = nil } })
+ }
+ }
+
+ private func directory(_ label: String) throws -> URL {
+ let url = FileManager.default.temporaryDirectory.appending(path: "signing-\(label)-\(UUID().uuidString)", directoryHint: .isDirectory)
+ try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)
+ return url
+ }
+
+ @Test("A missing identity goes into Bridgeplay's own keychain, with codesign in its partition list")
func createsWhenMissing() throws {
- let temporary = FileManager.default.temporaryDirectory.appending(path: "signing-\(UUID().uuidString)")
- try FileManager.default.createDirectory(at: temporary, withIntermediateDirectories: true)
- let keychain = URL(filePath: "/tmp/test.keychain-db")
+ let temporary = try directory("work")
+ let home = try directory("home")
+ defer { try? FileManager.default.removeItem(at: temporary); try? FileManager.default.removeItem(at: home) }
+ let keychain = home.appending(path: "signing/local-signing.keychain-db")
let fake = FakeSecurity(listings: [" 0 identities found\n", Self.listing])
+ let memory = MemorySecrets()
- let outcome = try LocalSigning.ensure(keychain: keychain, run: fake.runner, temporaryRoot: temporary)
+ let outcome = try LocalSigning.ensure(privateKeychain: keychain, run: fake.runner, secrets: memory.secrets,
+ temporaryRoot: temporary)
#expect(outcome == .created(hash: "E9B6B93497770DB40F9E30E511810EC68B9D4D93"))
- let created = fake.created
- #expect(created.map { $0[0] } == ["/usr/bin/openssl", "/usr/bin/openssl", "/usr/bin/security"])
- let request = created[0]
- #expect(request.contains("/CN=NotProton Local Signing"))
- #expect(request.contains("extendedKeyUsage=critical,codeSigning"))
- let importing = created[2]
- #expect(importing[1] == "import")
- #expect(importing.contains(keychain.path(percentEncoded: false)))
- #expect(importing.firstIndex(of: "-T").map { importing[$0 + 1] } == "/usr/bin/codesign")
- // Neither asks for a password: no trust settings change, no partition list.
+ let steps = fake.created.filter { $0[1] != "list-keychains" }
+ #expect(steps.map { "\(($0[0] as NSString).lastPathComponent) \($0[1])" } == [
+ "security create-keychain", "openssl req", "openssl pkcs12", "security unlock-keychain",
+ "security import", "security set-key-partition-list", "security lock-keychain",
+ ])
+ #expect(steps[1].contains("/CN=NotProton Local Signing"))
+ #expect(steps[1].contains("keyUsage=critical,digitalSignature"))
+ let password = try #require(memory.value)
+ #expect(steps[0].contains(password) && steps[3].contains(password) && steps[5].contains(password))
+ #expect(steps[5].firstIndex(of: "-S").map { steps[5][$0 + 1] } == "apple-tool:,apple:,codesign:")
+ #expect(steps[4].firstIndex(of: "-T").map { steps[4][$0 + 1] } == "/usr/bin/codesign")
+ #expect(steps.allSatisfy { $0.contains(keychain.path(percentEncoded: false)) || $0[0] == "/usr/bin/openssl" })
+ // No trust settings change, nothing in the login keychain but the password.
#expect(!fake.commands.joined().contains("add-trusted-cert"))
- #expect(!fake.commands.joined().contains("set-key-partition-list"))
// The private key never outlives the call.
#expect(try FileManager.default.contentsOfDirectory(atPath: temporary.path(percentEncoded: false)).isEmpty)
}
+ @Test("A keychain without its password signs ad hoc instead of meeting codesign locked")
+ func missingPasswordFallsBack() throws {
+ let identity = LocalSigning.Identity(hash: "E9B6B93497770DB40F9E30E511810EC68B9D4D93",
+ keychain: URL(filePath: "/nonexistent/k.keychain-db"))
+ let nothing = LocalSigning.Secrets(save: { _ in }, load: { nil }, delete: {})
+ #expect(LocalSigning.unlocked(identity, secrets: nothing) { $0 } == nil)
+ let login = LocalSigning.Identity(hash: identity.hash, keychain: nil)
+ #expect(LocalSigning.unlocked(login, secrets: nothing) { $0 } == login)
+ }
+
+ @Test("An older install's identity in the login keychain is kept")
+ func keepsLoginKeychainIdentity() throws {
+ let fake = FakeSecurity(listings: [Self.listing])
+ let identity = LocalSigning.existing(privateKeychain: URL(filePath: "/nonexistent/k.keychain-db"), run: fake.runner)
+ #expect(identity == LocalSigning.Identity(hash: "E9B6B93497770DB40F9E30E511810EC68B9D4D93", keychain: nil))
+ }
+
@Test("The PKCS#12 password matches between export and import")
func transportPasswordMatches() {
- let commands = LocalSigning.creationCommands(work: URL(filePath: "/w"), keychain: URL(filePath: "/k"), transportPassword: "secret")
- #expect(commands[1].arguments.contains("pass:secret"))
- #expect(commands[2].arguments.firstIndex(of: "-P").map { commands[2].arguments[$0 + 1] } == "secret")
+ let commands = LocalSigning.creationCommands(work: URL(filePath: "/w"), keychain: URL(filePath: "/k"),
+ keychainPassword: "kc", transportPassword: "secret")
+ #expect(commands[2].arguments.contains("pass:secret"))
+ #expect(commands[4].arguments.firstIndex(of: "-P").map { commands[4].arguments[$0 + 1] } == "secret")
+ }
+
+ @Test("Only Bridgeplay's keychain leaves the search list, every other entry stays as it was")
+ func leavesSearchList() {
+ let ours = URL(filePath: "/Users/x/Library/Application Support/bridgeplay/signing/local-signing.keychain-db")
+ let fake = FakeSecurity(listings: [])
+ let listing = """
+ "/Users/x/Library/Keychains/login.keychain-db"
+ "/Users/x/Library/Application Support/bridgeplay/signing/local-signing.keychain-db"
+ "/Users/x/Library/Keychains/other one.keychain-db"
+ """
+ let runner: LocalSigning.Runner = { executable, arguments in
+ _ = try fake.runner(executable, arguments)
+ return CommandResult(status: 0, stdout: arguments.contains("-s") ? "" : listing, stderr: "")
+ }
+ LocalSigning.leaveSearchList(ours, run: runner)
+ #expect(fake.commands.last == ["/usr/bin/security", "list-keychains", "-d", "user", "-s",
+ "/Users/x/Library/Keychains/login.keychain-db",
+ "/Users/x/Library/Keychains/other one.keychain-db"])
+
+ let untouched = FakeSecurity(listings: [])
+ LocalSigning.leaveSearchList(URL(filePath: "/elsewhere.keychain-db")) { executable, arguments in
+ _ = try untouched.runner(executable, arguments)
+ return CommandResult(status: 0, stdout: listing, stderr: "")
+ }
+ #expect(untouched.commands.count == 1)
}
- @Test("A refused import is reported and leaves no key behind")
+ @Test("A refused import is reported and leaves no key, keychain or password behind")
func refusedImport() throws {
- let temporary = FileManager.default.temporaryDirectory.appending(path: "signing-\(UUID().uuidString)")
- try FileManager.default.createDirectory(at: temporary, withIntermediateDirectories: true)
+ let temporary = try directory("work")
+ let home = try directory("home")
+ defer { try? FileManager.default.removeItem(at: temporary); try? FileManager.default.removeItem(at: home) }
+ let keychain = home.appending(path: "signing/local-signing.keychain-db")
let fake = FakeSecurity(listings: [""])
fake.failing = "import"
+ let memory = MemorySecrets()
- #expect(throws: StepFailure.self) { try LocalSigning.ensure(run: fake.runner, temporaryRoot: temporary) }
+ #expect(throws: StepFailure.self) {
+ try LocalSigning.ensure(privateKeychain: keychain, run: fake.runner, secrets: memory.secrets, temporaryRoot: temporary)
+ }
+ #expect(memory.value == nil)
+ #expect(!FileManager.default.fileExists(atPath: keychain.path(percentEncoded: false)))
#expect(try FileManager.default.contentsOfDirectory(atPath: temporary.path(percentEncoded: false)).isEmpty)
}
- // Uses the real tools against a throwaway keychain file (not added to the search list)
- // and signs a copy of /bin/echo with the result: proves the identity is usable by
- // codesign without a prompt. Off by default because a prompt would hang the run.
- @Test("A real identity in a throwaway keychain signs without a prompt",
+ // Uses the real tools against a throwaway keychain and signs a copy of /bin/echo: proves
+ // codesign uses the identity without a prompt. Off by default because a prompt would hang the run.
+ @Test("A real identity in Bridgeplay's keychain signs without a prompt",
.enabled(if: ProcessInfo.processInfo.environment["NOTPROTON_KEYCHAIN_TEST"] != nil))
func realKeychain() throws {
- let work = FileManager.default.temporaryDirectory.appending(path: "signing-real-\(UUID().uuidString)", directoryHint: .isDirectory)
- try FileManager.default.createDirectory(at: work, withIntermediateDirectories: true)
+ let work = try directory("real")
defer { try? FileManager.default.removeItem(at: work) }
- let keychain = work.appending(path: "test.keychain-db")
- let path = keychain.path(percentEncoded: false)
- try Shell.check("/usr/bin/security", ["create-keychain", "-p", "test", path])
- defer { _ = try? Shell.run("/usr/bin/security", ["delete-keychain", path]) }
- try Shell.check("/usr/bin/security", ["unlock-keychain", "-p", "test", path])
+ let keychain = work.appending(path: "signing/local-signing.keychain-db")
+ let nowhere = work.appending(path: "none.keychain-db")
+ let memory = MemorySecrets()
+ let searchList = try Shell.run("/usr/bin/security", ["list-keychains", "-d", "user"]).stdout
- let first = try LocalSigning.ensure(keychain: keychain, lookIn: [keychain])
+ let first = try LocalSigning.ensure(privateKeychain: keychain, lookIn: [nowhere], secrets: memory.secrets)
+ defer { _ = try? Shell.run("/usr/bin/security", ["delete-keychain", keychain.path(percentEncoded: false)]) }
guard case .created(let hash) = first else { Issue.record("expected a new identity, got \(first)"); return }
- #expect(try LocalSigning.ensure(keychain: keychain, lookIn: [keychain]) == .alreadyPresent(hash: hash))
+ #expect(try Shell.run("/usr/bin/security", ["list-keychains", "-d", "user"]).stdout == searchList)
+ #expect(try LocalSigning.ensure(privateKeychain: keychain, lookIn: [nowhere], secrets: memory.secrets) == .alreadyPresent(hash: hash))
+ let identity = try #require(LocalSigning.existing(lookIn: [nowhere], privateKeychain: keychain))
let binary = work.appending(path: "echo")
try FileManager.default.copyItem(at: URL(filePath: "/bin/echo"), to: binary)
- try Shell.check("/usr/bin/codesign", ["-f", "-s", hash, "--keychain", path, binary.path(percentEncoded: false)])
+ try LocalSigning.unlocked(identity, secrets: memory.secrets) { unlocked in
+ #expect(unlocked == identity)
+ try Shell.check("/usr/bin/codesign", ["-f", "-s", hash, "--keychain", keychain.path(percentEncoded: false),
+ binary.path(percentEncoded: false)])
+ }
let requirement = try Shell.run("/usr/bin/codesign", ["-d", "-r-", binary.path(percentEncoded: false)])
#expect((requirement.stdout + requirement.stderr).lowercased().contains("h\"\(hash.lowercased())\""))
}