Cotton code
226 lines · 11.0 KB · SwiftRaw
// This device's vault key: what is minted, what prompts, and what does not.//// Every case runs against `InMemoryVaultKeyStore`. A simulator's Keychain is// shared between test runs, so a test that minted into the real one is a test// that passes once and then asserts whatever the run before it left behind —// the same reason `DeviceKeyTests` drives a double.//// Every fixture is invented: a scalar counting up, a public key nobody holds.import CottonKitimport XCTestfinal class VaultKeyTests: XCTestCase {    /// A private scalar that is fixed rather than minted, so the public half    /// below is reproducible. 32 bytes counting up — not a key anything holds.    private static let scalar = "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8"    /// The public half of that scalar, **derived in Rust** and written out here.    ///    /// `crates/cotton-core/src/vault/wrap_tests.rs`'s    /// `the_public_half_of_a_known_scalar_is_the_vector_swift_derives_too`    /// asserts the same string from the same bytes. **Neither side reads the    /// other's file**: the vector IS the contract, written out in both, so a    /// change to either derivation is a red run in that language rather than a    /// phone publishing a key nothing can wrap for.    ///    /// This is the ONE guard that x25519-dalek and CryptoKit agree about what    /// "the public half" means, clamping included, and it is worth having as a    /// value rather than as a path read: a by-path guard goes quiet when the    /// file it reads moves, and this one cannot.    private static let publicHalf = "j0DFrbaPJWJK5bIU6nZ6bslNgp09e14a0bpvPiE4KF8"    // ── minting ────────────────────────────────────────────────────────────    func testAFreshStoreMintsOnceAndThenAnswersTheSameKey() throws {        let store = InMemoryVaultKeyStore()        let first = try VaultKey.key(store: store)        XCTAssertTrue(VaultKey.isKey(first))        XCTAssertEqual(store.mintCount, 1)        XCTAssertEqual(try VaultKey.key(store: store), first)        XCTAssertEqual(store.mintCount, 1, "a second read minted a second key")    }    /// **Unlike the DEVICE key, an unreadable slot is REPLACED.**    ///    /// Minting over an identity is a different phone; minting over a vault key    /// costs nothing, because the passwords are sealed under the workspace's    /// master key rather than under this one. The phone publishes the new    /// public half and the server's worker re-wraps within a tick.    func testASlotHoldingSomethingThatIsNotAKeyIsMintedOverRatherThanRefused() throws {        let store = InMemoryVaultKeyStore(seeded: "not-a-key")        let key = try VaultKey.key(store: store)        XCTAssertTrue(VaultKey.isKey(key))        XCTAssertNotEqual(key, "not-a-key")    }    func testMintIfAbsentAnswersNothingWhenThereIsAlreadyOne() throws {        let store = InMemoryVaultKeyStore(seeded: VaultKeyTests.scalar)        XCTAssertNil(            try VaultKey.mintIfAbsent(store: store),            "nil is what says 'already there' WITHOUT reading it — the launch path"        )        XCTAssertEqual(store.mintCount, 0)    }    func testMintIfAbsentMintsAndHandsBackWhatItMinted() throws {        let store = InMemoryVaultKeyStore()        let minted = try XCTUnwrap(try VaultKey.mintIfAbsent(store: store))        XCTAssertTrue(VaultKey.isKey(minted))        XCTAssertEqual(store.mintCount, 1)    }    // ── the shape of a key ─────────────────────────────────────────────────    func testAKeyIsFortyThreeBase64urlCharactersOverThirtyTwoBytes() {        XCTAssertTrue(VaultKey.isKey(VaultKeyTests.scalar))        XCTAssertEqual(VaultKeyTests.scalar.count, VaultKey.keyLength)        for wrong in ["", "short", String(repeating: "A", count: 42), "!!!"] {            XCTAssertFalse(VaultKey.isKey(wrong), "\(wrong) passed as a key")        }    }    func testTheVaultKeyIsFiledBesideTheDeviceKeyAndNotOverIt() {        // Two accounts, on both platforms. An account name shared with the        // device key would be one item doing two jobs, and reading either would        // prompt for the other's access control.        XCTAssertNotEqual(VaultKey.account, DeviceKey.account)        XCTAssertEqual(VaultKey.account, "vault-key")        // The SERVICE has two spellings, because there are two apps. On the        // phone it is the bundle id, beside the device key. On the Mac it is        // the Mac app's own service, because the item these screens read for a        // reveal must be the one the Mac's boot hands to the core — two        // services would be two keys, one of them wrapped for and one not.        // `CottonHostTests.VaultKeychainTests` is what pins the Mac's spelling        // to `Keychain.service` itself; this only says they are not the phone's.        #if os(macOS)            XCTAssertEqual(VaultKey.service, AppFlavor.current.macKeychainService)            XCTAssertNotEqual(VaultKey.service, DeviceKey.service)        #else            XCTAssertEqual(VaultKey.service, DeviceKey.service)        #endif    }    // ── the public half ────────────────────────────────────────────────────    func testThePublicHalfIsTheVectorTheRustSideDerivesFromTheSameBytes() {        XCTAssertEqual(            VaultKey.publicHalf(of: VaultKeyTests.scalar),            VaultKeyTests.publicHalf,            """            CryptoKit and x25519-dalek disagree about this scalar's public half. \            The same vector is asserted in crates/cotton-core/src/vault/wrap_tests.rs; \            if that one is green and this is red, the phone would publish a key \            the server wraps for and this device cannot open.            """        )    }    func testThePublicHalfOfSomethingThatIsNotAKeyIsNothing() {        for wrong in ["", "not-base64url!!", String(repeating: "A", count: 40)] {            XCTAssertNil(VaultKey.publicHalf(of: wrong))        }    }    // ── the keyring: which half costs what ─────────────────────────────────    /// **The launch path must never prompt.** `publicKey()` reads the CACHE and    /// the private item's existence, never the private item itself — which is    /// the whole reason the keyring exists rather than two lines at a call site.    func testPublishingAtLaunchNeverReadsThePrivateHalf() throws {        // The double counts reads; on the phone every one is the prompt.        let keys = InMemoryVaultKeyStore(seeded: VaultKeyTests.scalar)        let cache = InMemorySecretStore()        cache.write(VaultKeyTests.publicHalf, to: VaultKeyring.publicSlot)        let keyring = VaultKeyring(keys: keys, cache: cache, slot: VaultKeyring.publicSlot)        XCTAssertEqual(try keyring.publicKey(), VaultKeyTests.publicHalf)        XCTAssertEqual(keys.readCount, 0)    }    /// An `exists()` that answers no for a key that IS there ends in the mint    /// finding the slot taken — answered as "there was one", never by reading    /// it, and never by minting over it.    func testAMintThatFindsTheSlotTakenNeitherReadsNorMintsOver() throws {        let keys = InMemoryVaultKeyStore(seeded: VaultKeyTests.scalar, indexed: false)        XCTAssertNil(try VaultKey.mintIfAbsent(store: keys))        XCTAssertEqual(keys.readCount, 0)        XCTAssertEqual(keys.mintCount, 0)        XCTAssertEqual(try keys.read(), VaultKeyTests.scalar)    }    func testAFirstLaunchMintsCachesThePublicHalfAndAnswersIt() throws {        let keys = InMemoryVaultKeyStore()        let cache = InMemorySecretStore()        let keyring = VaultKeyring(keys: keys, cache: cache, slot: VaultKeyring.publicSlot)        let published = try XCTUnwrap(try keyring.publicKey())        XCTAssertEqual(keys.mintCount, 1)        XCTAssertEqual(            cache.read(VaultKeyring.publicSlot),            published,            """            the public half is cached AT MINT — deriving it later would mean \            reading the private item, which prompts            """        )        // Saying it twice mints nothing and answers the same thing.        XCTAssertEqual(try keyring.publicKey(), published)        XCTAssertEqual(keys.mintCount, 1)    }    /// The one state the launch path cannot answer: a private item that exists    /// with no cached public half. It answers `nil` rather than prompting, and    /// never mints over the item — minting there would orphan a wrap the server    /// has already written.    func testAPrivateKeyWithNoCachedPublicHalfAnswersNothingRatherThanMintingAgain() throws {        let keys = InMemoryVaultKeyStore(seeded: VaultKeyTests.scalar)        let cache = InMemorySecretStore()        let keyring = VaultKeyring(keys: keys, cache: cache, slot: VaultKeyring.publicSlot)        XCTAssertNil(try keyring.publicKey())        XCTAssertEqual(keys.mintCount, 0, "it minted over a key the server may have wrapped for")    }    /// The reveal path DOES read the private half, and repairs the cache on the    /// way past — which is what fixes the state above without a prompt of its    /// own next launch.    func testReadingThePrivateHalfRefreshesTheCachedPublicOne() throws {        let keys = InMemoryVaultKeyStore(seeded: VaultKeyTests.scalar)        let cache = InMemorySecretStore()        let keyring = VaultKeyring(keys: keys, cache: cache, slot: VaultKeyring.publicSlot)        XCTAssertEqual(try keyring.privateKey(), VaultKeyTests.scalar)        XCTAssertEqual(cache.read(VaultKeyring.publicSlot), VaultKeyTests.publicHalf)        XCTAssertEqual(try keyring.publicKey(), VaultKeyTests.publicHalf)    }    func testForgettingTakesBothHalvesSoTheNextLaunchMintsAndPublishes() throws {        let keys = InMemoryVaultKeyStore(seeded: VaultKeyTests.scalar)        let cache = InMemorySecretStore()        cache.write(VaultKeyTests.publicHalf, to: VaultKeyring.publicSlot)        let keyring = VaultKeyring(keys: keys, cache: cache, slot: VaultKeyring.publicSlot)        keyring.forget()        XCTAssertNil(try keys.read())        XCTAssertNil(            cache.read(VaultKeyring.publicSlot),            """            a cached public half with no private one is a key this phone would \            publish and never be able to use            """        )    }    /// A cancelled prompt is a DECISION and travels as one, rather than as a    /// store that is broken.    func testACancelledPromptTravelsAsItsOwnState() {        let keys = InMemoryVaultKeyStore(seeded: VaultKeyTests.scalar, failing: .cancelled)        let keyring = VaultKeyring(keys: keys, cache: InMemorySecretStore())        XCTAssertThrowsError(try keyring.privateKey()) { error in            XCTAssertEqual(error as? VaultKeyError, .cancelled)        }    }}