import CottonKit import XCTest @testable import CottonUI /// Recovery on the iPhone (e2e rulings R7a, R7c, R7d): /// the iCloud Keychain copy kept and opened with nobody asked, the code /// offered once, typed with its typo check and opened, Show and Approve /// behind the phone's lock. Synthetic keys, codes and words only. @MainActor final class RecoveryKeysTests: XCTestCase { private static let scalar = "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8" private static let lines = #""lines": {"offer": "Keep a recovery code.", "copy": "Copy", "notNow": "Not now", "done": "Done", "copied": "Copied.", "alone": "Losing this phone loses these records.", "haveCode": "I have a code", "enter": "Type your code", "hint": "XXXX", "open": "Open", "madeNew": "A new code is made.", "appleKept": "Your iCloud Keychain keeps a copy too."}"# private static func status(offer: Bool = false, alone: Bool = false, apple: String = "null") -> String { #"{"code": null, "google": null, "apple": \#(apple), "trusted": null, "holdsVault": true, "offer": \#(offer), "alone": \#(alone), "signedIn": true, \#(lines)}"# } /// A synthetic code, 24 characters in six groups. private static let code = "ABCD-EFGH-JKMN-PQRS-TVWX-YZ01" final class Counter: @unchecked Sendable { private let lock = NSLock() private var n = 0 func tick() { lock.withLock { n += 1 } } var count: Int { lock.withLock { n } } } final class Said { var words: [String] = [] } private func recovery(_ core: ScriptedCore, platform: InMemoryPlatformKeys = InMemoryPlatformKeys(), presence: Counter = Counter()) -> (RecoveryKeys, Said) { let said = Said() let keyring = VaultKeyring(keys: InMemoryVaultKeyStore(seeded: Self.scalar), cache: InMemorySecretStore(), presence: { presence.tick() }) let vault = VaultAccess(keyring: keyring, ask: { .allowed }) let model = RecoveryKeys(core: core, vault: vault, platform: platform, name: { "Walk phone" }, presence: { presence.tick() }, say: { words, _ in said.words.append(words) }) return (model, said) } private func body(_ core: ScriptedCore, _ method: String) async throws -> [String: Any] { let sent = await core.calls.last { $0.method == method } return try XCTUnwrap(try JSONSerialization.jsonObject(with: Data(try XCTUnwrap(sent).requestJSON.utf8)) as? [String: Any]) } /// RULE: A new iPhone that finds the iCloud Keychain copy opens with it, store apple, the key and this device's name, with nobody asked, and says the core's line (e2e rulings R7a). func testANewIPhoneOpensWithItsICloudCopy() async throws { let core = ScriptedCore([CottonMethod.recoveryOpenPlatform: .ok(#"{"opened": true, "line": "Opened with the copy your iCloud Keychain keeps."}"#)]) let presence = Counter() let (model, said) = recovery(core, platform: InMemoryPlatformKeys(["db-1": "synthetic-platform-key"]), presence: presence) let opened = await model.openFromICloud(database: "db-1") XCTAssertTrue(opened) let sent = try await body(core, CottonMethod.recoveryOpenPlatform) XCTAssertEqual(sent["store"] as? String, "apple") XCTAssertEqual(sent["key"] as? String, "synthetic-platform-key") XCTAssertEqual(sent["privateKey"] as? String, Self.scalar) XCTAssertEqual(sent["name"] as? String, "Walk phone") XCTAssertEqual(presence.count, 0) XCTAssertEqual(said.words, ["Opened with the copy your iCloud Keychain keeps."]) } /// RULE: A phone with no iCloud copy tries nothing. func testNoCopyTriesNothing() async { let core = ScriptedCore() let (model, _) = recovery(core) let opened = await model.openFromICloud(database: "db-1") XCTAssertFalse(opened) let asked = await core.methodsCalled() XCTAssertEqual(asked, []) } /// RULE: A phone holding the vault with no current apple copy makes the platform key with nobody asked and keeps it in the iCloud Keychain store (e2e rulings R7a). func testAPhoneHoldingTheVaultKeepsTheICloudCopy() async throws { let core = ScriptedCore([ CottonMethod.recoveryStatus: .ok(Self.status()), CottonMethod.recoveryMakePlatform: .ok(#"{"key": "synthetic-platform-key"}"#), CottonMethod.recoveryHelpAsks: .ok(#"{"asks": []}"#), ]) let platform = InMemoryPlatformKeys() let presence = Counter() let (model, _) = recovery(core, platform: platform, presence: presence) await model.whileHeld(database: "db-1", bannerUp: false) let sent = try await body(core, CottonMethod.recoveryMakePlatform) XCTAssertEqual(sent["store"] as? String, "apple") XCTAssertEqual(platform.read(database: "db-1"), "synthetic-platform-key") XCTAssertEqual(presence.count, 0) } /// A Keychain that keeps nothing: every write is refused. struct RefusingPlatformKeys: PlatformKeyKeeping { func read(database: String) -> String? { nil } @discardableResult func write(_ key: String, database: String) -> Bool { false } } /// RULE: A phone whose Keychain will not keep the iCloud copy makes the platform key once a launch, not at every pull: a second read makes no new key and reads no status again (e2e rulings R7a; the walk of Todos never came to rest). func testACopyTheKeychainRefusesIsTriedOnceALaunch() async throws { let core = ScriptedCore([ CottonMethod.recoveryStatus: .ok(Self.status()), CottonMethod.recoveryMakePlatform: .ok(#"{"key": "synthetic-platform-key"}"#), CottonMethod.recoveryHelpAsks: .ok(#"{"asks": []}"#), ]) let said = Said() let keyring = VaultKeyring(keys: InMemoryVaultKeyStore(seeded: Self.scalar), cache: InMemorySecretStore(), presence: {}) let model = RecoveryKeys(core: core, vault: VaultAccess(keyring: keyring, ask: { .allowed }), platform: RefusingPlatformKeys(), name: { "Walk phone" }, presence: {}, say: { words, _ in said.words.append(words) }) await model.whileHeld(database: "db-1", bannerUp: false) await model.whileHeld(database: "db-1", bannerUp: false) await model.whileHeld(database: "db-1", bannerUp: false) let made = await core.calls.filter { $0.method == CottonMethod.recoveryMakePlatform }.count let reads = await core.calls.filter { $0.method == CottonMethod.recoveryStatus } XCTAssertEqual(made, 1) // Once to learn the vault, once after the refusal so the offer says why; never again. XCTAssertEqual(reads.count, 2) XCTAssertFalse(reads[0].requestJSON.contains("copy")) XCTAssertTrue(reads[1].requestJSON.contains(#""copy":"none""#), reads[1].requestJSON) } /// RULE: The code is offered once, made with nobody asked, and Not now on a phone that is the person's only way in says the honest line once (e2e rulings R7c). func testTheCodeIsOfferedOnceAndNotNowSaysTheHonestLine() async throws { let core = ScriptedCore([ CottonMethod.recoveryStatus: .ok(Self.status(offer: true, alone: true, apple: #"{"made": "2026-11-16", "current": true, "line": "x"}"#)), CottonMethod.recoveryMake: .ok(#"{"code": "\#(Self.code)"}"#), CottonMethod.recoveryHelpAsks: .ok(#"{"asks": []}"#), ]) let (model, said) = recovery(core, platform: InMemoryPlatformKeys(["db-1": "k"])) await model.whileHeld(database: "db-1", bannerUp: true) XCTAssertNil(model.shown, "no offer while another line stands") await model.whileHeld(database: "db-1", bannerUp: false) XCTAssertEqual(model.shown, ShownCode(code: Self.code, offered: true)) await model.dismiss() XCTAssertEqual(said.words, ["Losing this phone loses these records."]) await model.whileHeld(database: "db-1", bannerUp: false) XCTAssertNil(model.shown, "offered once") let makes = await core.methodsCalled().filter { $0 == CottonMethod.recoveryMake }.count XCTAssertEqual(makes, 1) } /// RULE: I have a code checks the typo once a whole code is typed and says the core's line; Open hands the code, the quiet key and this device's name to recovery.open (e2e rulings R7c). func testIHaveACodeChecksThenOpens() async throws { let core = ScriptedCore([ CottonMethod.recoveryCheck: .ok(#"{"ok": false, "problem": "recovery_code_check", "line": "That code has a typo."}"#), CottonMethod.recoveryOpen: .ok(#"{"opened": true, "line": "Opened with your recovery code."}"#), ]) let presence = Counter() let (model, said) = recovery(core, presence: presence) model.typed = "ABCD-EFGH" await model.check() XCTAssertNil(model.problem, "nothing said before a whole code") model.typed = Self.code await model.check() XCTAssertEqual(model.problem, "That code has a typo.") await core.answer(CottonMethod.recoveryCheck, .ok(#"{"ok": true}"#)) await model.check() XCTAssertNil(model.problem) await model.open() let sent = try await body(core, CottonMethod.recoveryOpen) XCTAssertEqual(sent["code"] as? String, Self.code) XCTAssertEqual(sent["privateKey"] as? String, Self.scalar) XCTAssertEqual(sent["name"] as? String, "Walk phone") XCTAssertEqual(presence.count, 0) XCTAssertEqual(said.words, ["Opened with your recovery code."]) } /// RULE: Show my recovery code asks the phone's lock, then shows the code with Done. func testShowIsBehindTheLock() async throws { let core = ScriptedCore([ CottonMethod.recoveryShow: .ok(#"{"code": "\#(Self.code)"}"#), CottonMethod.recoveryStatus: .ok(Self.status()), ]) let presence = Counter() let (model, _) = recovery(core, presence: presence) await model.show() XCTAssertEqual(presence.count, 1) XCTAssertEqual(model.shown, ShownCode(code: Self.code, offered: false)) } /// RULE: A helper's ask stands with the core's words; Approve asks the phone's lock and approves that ask (e2e rulings R7d). func testAHelpersApproveIsBehindTheLock() async throws { let core = ScriptedCore([ CottonMethod.recoveryHelpAsks: .ok(#"{"asks": [{"id": "h-1", "name": "Walk A", "code": "AB12", "line": "Help Walk A get back in. Their new device shows this code: AB12", "approve": "Approve", "decline": "Not now", "approved": "Done."}]}"#), CottonMethod.recoveryHelpApprove: .ok(#"{"approved": true}"#), ]) let presence = Counter() let (model, said) = recovery(core, presence: presence) await model.readHelpAsks() let ask = try XCTUnwrap(model.helpAsks.first) XCTAssertEqual(ask.line, "Help Walk A get back in. Their new device shows this code: AB12") await model.approve(ask) let sent = try await body(core, CottonMethod.recoveryHelpApprove) XCTAssertEqual(sent["id"] as? String, "h-1") XCTAssertEqual(presence.count, 1) XCTAssertEqual(said.words, ["Done."]) } /// RULE: Choosing a helper asks the phone's lock and trusts that person by number. func testTrustIsBehindTheLock() async throws { let core = ScriptedCore([ CottonMethod.recoveryTrust: .ok(#"{"trusted": true, "line": "Walk B can now help you get back in."}"#), CottonMethod.recoveryStatus: .ok(Self.status()), ]) let presence = Counter() let (model, _) = recovery(core, presence: presence) await model.trust(number: "+15550100", name: "Walk B") let sent = try await body(core, CottonMethod.recoveryTrust) XCTAssertEqual(sent["number"] as? String, "+15550100") XCTAssertEqual(presence.count, 1) } }