Cotton code
182 lines · 12.0 KB · SwiftRaw
import CottonKitimport XCTest@testable import CottonUI/// The vault founded, approved and re-opened with no wall/// (e2e rulings R7b, R8, R9), Android's order/// (`core/SealedKeys.kt`). Synthetic keys, ids and words only.@MainActorfinal class SealedKeysTests: XCTestCase {    private static let scalar = "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8"    private static let needs = #"{"database": "db-1", "keyHeld": false, "needsKey": true, "founds": true, "minted": false, "parked": [], "said": {"line": "Key needed", "act": "Unlock"}}"#    private static let joins = #"{"database": "db-1", "keyHeld": false, "needsKey": true, "founds": false, "minted": false, "parked": [], "said": {"line": "Key needed", "act": "Unlock"}}"#    private static let held = #"{"database": "db-1", "keyHeld": true, "needsKey": false, "founds": false, "minted": false, "parked": [], "said": null}"#    private static let nobody = #"{"waiting": null, "mine": null, "pollSeconds": null}"#    private static let mine = #"{"waiting": null, "mine": {"deviceId": "d-new", "line": "Open Cotton on a device you already use", "ask": "Approve on another device"}, "pollSeconds": 10}"#    private static let asks = #"{"waiting": {"deviceId": "d-new", "name": "Walk phone", "line": "Walk phone asks to read your sealed records", "how": "On Walk phone, choose Approve on another device", "refuse": "Refuse", "confirm": "Refuse this device?"}, "mine": null, "pollSeconds": null}"#    private static let askCard = #"{"askId": "ask-1", "heading": "Approve on another device", "line": "Open Cotton on a phone you're signed in on", "left": "3 minutes left", "pollSeconds": 1, "sendCode": "Send code", "cancel": "Cancel"}"#    private static let approved = #"{"state": "approved", "done": true, "line": "Approved", "credential": "synthetic-credential", "person": {"id": "p-1"}, "expiresIn": 60, "databaseId": "db-1"}"#    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 Kept: DataKeyKeeping, @unchecked Sendable {        private let lock = NSLock()        private var keys: [String: String] = [:]        init(_ seeded: [String: String] = [:]) { keys = seeded }        func read(database: String) -> String? { lock.withLock { keys[database] } }        @discardableResult func write(_ key: String, database: String) -> Bool { lock.withLock { keys[database] = key }; return true }        func forget(database: String) { _ = lock.withLock { keys.removeValue(forKey: database) } }    }    final class Said { var words: [String] = [] }    private func keys(_ core: ScriptedCore, kept: Kept = Kept(), presence: Counter = Counter(),                      account: SignedInAs? = nil) -> (SealedKeys, 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 = SealedKeys(core: core, vault: vault, keeper: kept, platform: InMemoryPlatformKeys(), name: { "Walk phone" }, account: { account }, pause: { _ in }, 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 first sign-in founds with no question: while the core says the key is needed and this device founds, the vault opens with the key read quietly and this device's name, and the phone's lock is never asked (e2e rulings R8).    func testAFirstSignInFoundsWithNoPrompt() async throws {        let core = ScriptedCore([            CottonMethod.sealStatus: .ok(Self.needs), CottonMethod.vaultApproval: .ok(Self.nobody),            CottonMethod.vaultUnlock: .ok(#"{"unlocked": true, "until": "2099-01-01T00:00:00Z"}"#),        ])        let presence = Counter()        let (model, _) = keys(core, presence: presence)        await model.read()        let sent = try await body(core, CottonMethod.vaultUnlock)        XCTAssertEqual(sent["privateKey"] as? String, Self.scalar)        XCTAssertEqual(sent["name"] as? String, "Walk phone")        XCTAssertEqual(presence.count, 0, "founding asks nobody")    }    /// RULE: A phone that has not signed in is never asked for a key: while the core says it makes its own (`makes`), the key is made with no question, kept in the Keychain as a first sign-in's is, and no line is drawn; the vault is not opened and the phone's lock is never asked (no Unlock before sign-in, 20 Nov 2026).    func testAPhoneNotSignedInMakesItsKeyWithNoPrompt() async throws {        let makes = #"{"database": "db-local", "keyHeld": false, "needsKey": true, "founds": false, "makes": true, "minted": false, "parked": [], "said": null}"#        let made = #"{"database": "db-local", "keyHeld": true, "needsKey": false, "founds": false, "makes": false, "minted": false, "parked": [], "said": null}"#        let core = ScriptedCore([            CottonMethod.sealStatus: .ok(makes), CottonMethod.vaultApproval: .ok(Self.nobody),            CottonMethod.sealMakeKey: .ok(#"{"key": "synthetic-local-key", "made": true}"#),            CottonMethod.sealHeldKey: .ok(#"{"key": "synthetic-local-key", "database": "db-local"}"#),        ])        let kept = Kept()        let presence = Counter()        let (model, _) = keys(core, kept: kept, presence: presence)        await model.read()        let asked = await core.methodsCalled()        XCTAssertTrue(asked.contains(CottonMethod.sealMakeKey), "the key is made")        XCTAssertFalse(asked.contains(CottonMethod.vaultUnlock), "the vault is not opened")        XCTAssertNil(model.line, "no banner")        // Held now (the core's next status): kept in the Keychain for the next launch.        await core.answer(CottonMethod.sealStatus, .ok(made))        await model.read()        XCTAssertEqual(kept.read(database: "db-local"), "synthetic-local-key", "kept as a first sign-in's key is")        XCTAssertNil(model.line)        XCTAssertEqual(presence.count, 0)    }    /// RULE: An app installed after another founded opens with no step: the data key the shared Keychain group kept is handed back, and the vault is not opened (e2e rulings R9).    func testASecondAppOpensFromTheSharedKey() async throws {        let core = ScriptedCore([            CottonMethod.sealStatus: .ok(Self.joins), CottonMethod.vaultApproval: .ok(Self.nobody),            CottonMethod.sealUseKey: .ok(#"{"held": true}"#),        ])        let (model, _) = keys(core, kept: Kept(["db-1": "synthetic-data-key"]))        await model.read()        let sent = try await body(core, CottonMethod.sealUseKey)        XCTAssertEqual(sent["key"] as? String, "synthetic-data-key")        let asked = await core.methodsCalled()        XCTAssertFalse(asked.contains(CottonMethod.vaultUnlock), "no founding on a device that does not found")    }    /// RULE: A device that must be let in says the core's waiting line in place of the key's line, offers its own ask (`mine.ask`; no code until that ask is made) and stops trying; once the approval lands (mine gone) it opens again by itself with nobody asked (e2e rulings R7b, signin-harden).    func testAWaitingDeviceSaysItsWaitAndReopensOnceApproved() async throws {        let core = ScriptedCore([            CottonMethod.sealStatus: .ok(Self.needs), CottonMethod.vaultApproval: .ok(Self.mine),            CottonMethod.vaultUnlock: .refuse(code: "vault_not_wrapped_yet", message: "Waiting"),        ])        let presence = Counter()        let (model, _) = keys(core, presence: presence)        await model.read()        XCTAssertTrue(model.waiting)        XCTAssertEqual(model.line, "Open Cotton on a device you already use")        XCTAssertEqual(model.mineAsk, "Approve on another device")        XCTAssertNil(model.act)        let tries = await core.methodsCalled().filter { $0 == CottonMethod.vaultUnlock }.count        XCTAssertEqual(tries, 1, "a device another must approve stops at once")        await core.answer(CottonMethod.vaultApproval, .ok(Self.nobody))        await core.answer(CottonMethod.sealStatus, .ok(Self.joins))        await core.answer(CottonMethod.vaultUnlock, .ok(#"{"unlocked": true, "until": "2099-01-01T00:00:00Z"}"#))        await model.read()        let after = await core.methodsCalled().filter { $0 == CottonMethod.vaultUnlock }.count        XCTAssertEqual(after, 2, "approved: opened again")        XCTAssertEqual(presence.count, 0)    }    /// RULE: Another device asking stands as the approval card in any app with who asks and how it comes in, and no Approve: nothing on the card lets a device into the vault on a tap.    func testTheVaultCardSaysHowAndHasNoApprove() async throws {        let core = ScriptedCore([CottonMethod.sealStatus: .ok(Self.held), CottonMethod.vaultApproval: .ok(Self.asks)])        let presence = Counter()        let (model, _) = keys(core, kept: Kept(["db-1": "synthetic-data-key"]), presence: presence)        await model.read()        XCTAssertEqual(model.asking?.line, "Walk phone asks to read your sealed records")        XCTAssertEqual(model.asking?.how, "On Walk phone, choose Approve on another device")        let called = await core.methodsCalled()        XCTAssertFalse(called.contains("vault.approveDevice"))        XCTAssertEqual(presence.count, 0)    }    /// RULE (GETTING-IN.md): a phone waiting for the vault gets the page by itself: gettingIn.screen for its own    /// number, with nothing prompting; Do this later closes it and leaves the slim line's act; that act opens it again.    func testTheWaitingPhoneGetsThePageByItselfAndDoThisLaterLeavesTheSlimLine() async throws {        let core = ScriptedCore([            CottonMethod.sealStatus: .ok(Self.joins), CottonMethod.vaultApproval: .ok(Self.mine),            CottonMethod.gettingInScreen: .ok(#"{"show": true, "state": "waiting", "heading": "One more step: open another device of yours", "line": "Open any Cotton app there and scan this code.", "qr": {"text": "COTTON-IN:1:ask-1:n", "size": 1, "rows": ["1"]}, "later": "Do this later", "signOut": "Sign out", "noDevice": "No other device?", "pollSeconds": 30}"#),        ])        let presence = Counter()        let (model, _) = keys(core, presence: presence, account: SignedInAs(server: "https://dev.example", phone: "test:+15550100"))        await model.read()        XCTAssertTrue(model.waiting)        for _ in 0..<50 where model.page == nil { try await Task.sleep(for: .milliseconds(100)) }        XCTAssertEqual(model.page?.text("heading"), "One more step: open another device of yours")        XCTAssertEqual(presence.count, 0, "nothing prompts: the page asks with this device's published key")        let sent = try await body(core, CottonMethod.gettingInScreen)        XCTAssertEqual(sent["phone"] as? String, "test:+15550100")        XCTAssertEqual(sent["server"] as? String, "https://dev.example")        XCTAssertNil(sent["privateKey"], "no key lent for the ask")        XCTAssertFalse(model.offersAsk)        model.later = true        XCTAssertTrue(model.offersAsk, "the slim line's act stands")        model.openPage()        XCTAssertFalse(model.later)    }    /// RULE: Refuse calls vault.refuseDevice for the device that asked.    func testRefuseNamesTheDevice() async throws {        let core = ScriptedCore([            CottonMethod.sealStatus: .ok(Self.held), CottonMethod.vaultApproval: .ok(Self.asks),            CottonMethod.vaultRefuseDevice: .ok(#"{"id": "vk-2", "deviceId": "d-new", "removed": true}"#),        ])        let (model, _) = keys(core, kept: Kept(["db-1": "synthetic-data-key"]))        await model.read()        await model.refuse()        let sent = try await body(core, CottonMethod.vaultRefuseDevice)        XCTAssertEqual(sent["deviceId"] as? String, "d-new")    }}