import CryptoKit import Foundation import Testing @testable import ParcelDev @Suite struct UpdateKeyTests { @Test func keyGenerationAndMockedStorageNeverOpenNativeKeychainsOrLeaveSeedsOnDisk() throws { let root = try ReleaseTestSupport.temporary() defer { #expect(throws: Never.self) { try FileManager.default.removeItem(at: root) } } let path = root.appendingPathComponent("mock.keychain-db") let original = Data("Mock Keychain file; no native keychain was created.\n".utf8) try original.write(to: path) var generations = 0 var calls = 0 var stored: UpdateKey.Generated? var refuse = false let generate = { generations += 1 return UpdateKey.generate() } let store: (URL, String, Data, String) throws -> Void = { selected, account, seed, publicKey in calls += 1 #expect(selected == path) #expect(account == "fixture-update") let bytes = try UpdateCrypto.canonical( String(decoding: seed, as: UTF8.self), count: 32, message: "Invalid fixture seed") let key = try Curve25519.Signing.PrivateKey(rawRepresentation: bytes) #expect(key.publicKey.rawRepresentation.base64EncodedString() == publicKey) if refuse { throw DevError("Mock keychain refused the write") } guard stored == nil else { throw DevError("A key already exists for this account; refusing to rotate it") } stored = UpdateKey.Generated(seed: seed, publicKey: publicKey) } let output = try UpdateKey.create(path: path, account: "fixture-update", generate: generate, store: store) let key = try #require(stored) #expect(output == key.publicKey) #expect(!output.contains(String(decoding: key.seed, as: UTF8.self))) #expect(generations == 1 && calls == 1) do { _ = try UpdateKey.create(path: path, account: "fixture-update", generate: generate, store: store) Issue.record("Expected refusal to rotate") } catch { #expect(String(describing: error).contains("refusing to rotate")) #expect(!String(describing: error).contains(String(decoding: key.seed, as: UTF8.self))) } refuse = true do { _ = try UpdateKey.create(path: path, account: "fixture-update", generate: generate, store: store) Issue.record("Expected storage rejection") } catch { #expect(String(describing: error).contains("refused the write")) #expect(!String(describing: error).contains(String(decoding: key.seed, as: UTF8.self))) } #expect(stored == key) #expect(generations == 3 && calls == 3) #expect(throws: DevError.self) { try UpdateKey.create( path: path, account: "fixture-update", generate: { throw DevError("Fixture generation failure") }, store: store) } #expect(calls == 3) #expect(try FileManager.default.contentsOfDirectory(atPath: root.path) == ["mock.keychain-db"]) #expect(try Data(contentsOf: path) == original) let signing = try Curve25519.Signing.PrivateKey(rawRepresentation: #require(Data(base64Encoded: key.seed))) let archive = Data("fixture archive".utf8) let signature = try signing.signature(for: archive) #expect(signing.publicKey.isValidSignature(signature, for: archive)) } @Test(arguments: ["", " ", "\0", "\n\t"]) func invalidAccountsFailBeforeGenerationOrStorage(account: String) throws { var called = false #expect(throws: DevError.self) { try UpdateKey.create( path: URL(fileURLWithPath: "/missing"), account: account, generate: { called = true; return UpdateKey.generate() }, store: { _, _, _, _ in called = true }) } #expect(!called) } @Test func keychainCommandQuotingDoesNotTurnMetadataIntoCommands() throws { #expect(try UpdateKey.quoted("account \"\\ value") == "\"account \\\"\\\\ value\"") for value in ["account\nadd-generic-password", "account\rcommand", "value\0suffix"] { #expect(throws: DevError.self) { try UpdateKey.quoted(value) } } } @Test func explicitKeychainFrontendKeepsSeedOnStdinAndVerifiesReadback() throws { let key = UpdateKey.generate() let path = URL(fileURLWithPath: "/fixture/selected keychain-db") let account = "fixture \"quoted\" account" var calls: [([String], Data?)] = [] try UpdateKey.store(path, account, key.seed, key.publicKey) { executable, arguments, input in #expect(executable == "/usr/bin/security") #expect(!arguments.contains(String(decoding: key.seed, as: UTF8.self))) calls.append((arguments, input)) if calls.count == 1 { return DevProcessResult(status: 44, stdout: Data(), stderr: Data()) } if calls.count == 2 { return DevProcessResult(status: 0, stdout: Data(), stderr: Data()) } return DevProcessResult(status: 0, stdout: key.seed + Data([10]), stderr: Data()) } #expect(calls.count == 3) #expect( calls[0].0 == [ "find-generic-password", "-a", account, "-s", "https://sparkle-project.org", "-w", path.path, ]) #expect(calls[0].1 == nil && calls[2].1 == nil) #expect(calls[2].0 == calls[0].0) #expect(calls[1].0 == ["-i"]) let payload = String(decoding: try #require(calls[1].1), as: UTF8.self) #expect(payload.contains(try UpdateKey.quoted(account))) #expect(payload.contains(try UpdateKey.quoted(path.path))) #expect(payload.contains(try UpdateKey.quoted(String(decoding: key.seed, as: UTF8.self)))) #expect(!payload.contains("-U")) #expect(!calls.flatMap { $0.0 }.contains("default-keychain")) #expect(!calls.flatMap { $0.0 }.contains("list-keychains")) } @Test(arguments: [ "existing", "lookup-failed", "write-failed", "duplicate-write", "readback-failed", "readback-mismatch", ]) func frontendFailuresNeverRotateOrExposeSeeds(kind: String) throws { let key = UpdateKey.generate() var calls = 0 do { try UpdateKey.store(URL(fileURLWithPath: "/fixture/keychain-db"), "fixture", key.seed, key.publicKey) { executable, arguments, input in #expect(executable == "/usr/bin/security") #expect(!arguments.contains(String(decoding: key.seed, as: UTF8.self))) calls += 1 if calls == 1 { let status: Int32 = kind == "existing" ? 0 : kind == "lookup-failed" ? 1 : 44 return DevProcessResult(status: status, stdout: key.seed, stderr: key.seed) } if calls == 2 { #expect(arguments == ["-i"] && input != nil) let status: Int32 = kind == "write-failed" ? 80 : kind == "duplicate-write" ? 45 : 0 return DevProcessResult(status: status, stdout: key.seed, stderr: key.seed) } return DevProcessResult( status: kind == "readback-failed" ? 44 : 0, stdout: Data("wrong seed".utf8), stderr: key.seed) } Issue.record("Expected keychain frontend rejection") } catch { let message = String(describing: error) #expect(!message.contains(String(decoding: key.seed, as: UTF8.self))) if ["existing", "duplicate-write"].contains(kind) { #expect(message.contains("refusing to rotate")) } } #expect( calls == (["existing", "lookup-failed"].contains(kind) ? 1 : ["write-failed", "duplicate-write"].contains(kind) ? 2 : 3)) } @Test func propertyListsRetainTypedValuesAcrossUpdatePolicyEdits() throws { let root = try ReleaseTestSupport.temporary() defer { #expect(throws: Never.self) { try FileManager.default.removeItem(at: root) } } let path = root.appendingPathComponent("Info.plist") let values: [String: UpdatePlist] = [ "name": .string("fixture"), "enabled": .bool(true), "count": .integer(3), "ratio": .real(1.5), "wholeReal": .real(2.0), "zero": .integer(0), "one": .integer(1), "negative": .integer(-123), "large": .integer(Int64.max), "disabled": .bool(false), "bytes": .data(Data([0, 255])), "date": .date(Date(timeIntervalSince1970: 1_700_000_000)), "list": .array([.string("item")]), "dict": .dictionary(["field": .string("value")]), ] try UpdatePlist.write(values, to: path.path) #expect(try UpdatePlist.read(path.path) == values) let encoder = PropertyListEncoder() encoder.outputFormat = .binary try encoder.encode(UpdatePlist.dictionary(values)).write(to: path) #expect(try UpdatePlist.read(path.path) == values) } }