Cotton code
39 lines · 2.3 KB · SwiftRaw
import CottonKitimport XCTest/// "Re-key this device" in the Keychain: the successor waits beside the key/// in use and replaces it only when promoted.final class DeviceRekeyKeyTests: XCTestCase {    private func seed(_ byte: UInt8) -> String {        DeviceKey.encode(Data(repeating: byte, count: DeviceKey.seedBytes))    }    /// RULE: A re-key never loses a key: the successor is minted beside the key in use and a second press finds the same one; promotion puts the successor in the key's slot before it leaves its own, so the old key leaves the Keychain only as the new one takes its place.    func testPromotionPutsTheSuccessorInPlaceBeforeItLeavesItsSlot() throws {        let current = InMemoryDeviceKeyStore(seeded: seed(1))        let successor = InMemoryDeviceKeyStore()        let minted = try DeviceKey.seed(store: successor)        XCTAssertEqual(try DeviceKey.seed(store: successor), minted, "a second press minted a second successor")        XCTAssertEqual(try current.read(), seed(1), "minting the successor touched the key in use")        XCTAssertTrue(try DeviceKey.promote(successor: successor, into: current))        XCTAssertEqual(try current.read(), minted)        XCTAssertNil(try successor.read())        XCTAssertFalse(try DeviceKey.promote(successor: successor, into: current), "nothing left to promote")        XCTAssertEqual(try current.read(), minted)    }    /// RULE: A launch asks only about a successor that is not already the key in use; one that is (a promotion cut short after its first half) is finished by forgetting the successor slot, and the key in use is never touched.    func testALaunchFinishesAPromotionCutShortAndAsksAboutAnUnpromotedOne() {        let current = InMemoryDeviceKeyStore(seeded: seed(2))        let successor = InMemoryDeviceKeyStore(seeded: seed(3))        XCTAssertEqual(DeviceKey.successorPending(successor: successor, current: current), seed(3))        let cutShort = InMemoryDeviceKeyStore(seeded: seed(2))        XCTAssertNil(DeviceKey.successorPending(successor: cutShort, current: current))        XCTAssertNil(try cutShort.read(), "the finished promotion left its successor behind")        XCTAssertEqual(try current.read(), seed(2))        XCTAssertNil(DeviceKey.successorPending(successor: InMemoryDeviceKeyStore(), current: current))    }}