Cotton code
133 lines · 6.8 KB · SwiftRaw
// The provider's Swift WebAuthn encoder, held to the core's bytes.//// `crates/cotton-core/tests/passkey_vector.rs` makes a vector with// `cotton_core::keys::passkey` over a fixed synthetic key and commits it; this// reads the same file and must make the same COSE key, registration// authenticatorData and `none` attestation object, byte for byte. The// assertion's authenticatorData must match too, and its signature (Rust's,// deterministic) must verify under CryptoKit — while CryptoKit's own// (randomised) signature verifies under the same key. The key is synthetic// and opens nothing.import CottonMailboximport CryptoKitimport XCTestfinal class PasskeyAuthenticatorTests: XCTestCase {    private struct Vector: Decodable {        let rp_id: String        let user_handle: String        let credential_id: String        let private_scalar_hex: String        let client_data_hash_hex: String        let public_key: String        let attestation: Attestation        let assertion: Assertion        struct Attestation: Decodable {            let authenticator_data_hex: String            let attestation_object_hex: String        }        struct Assertion: Decodable {            let counter: Int            let authenticator_data_hex: String            let signature_der_hex: String        }    }    private func vector() throws -> Vector {        let root = URL(fileURLWithPath: #filePath)            .deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()            .deletingLastPathComponent().deletingLastPathComponent()        let file = root.appendingPathComponent("crates/cotton-core/tests/fixtures/passkey_vector.json")        return try JSONDecoder().decode(Vector.self, from: Data(contentsOf: file))    }    private func hex(_ text: String) -> Data {        var out = Data()        var index = text.startIndex        while index < text.endIndex {            let next = text.index(index, offsetBy: 2)            out.append(UInt8(text[index..<next], radix: 16)!)            index = next        }        return out    }    // RULE (Cotton Keys provider, 8 Nov 2026): the provider's registration is    // the core's, byte for byte: COSE key, authenticatorData (UP|UV|AT,    // counter 0, AAGUID zero, the credential id) and the `none` attestation.    func testRegistrationIsTheCoresBytes() throws {        let vector = try vector()        let key = try P256.Signing.PrivateKey(rawRepresentation: hex(vector.private_scalar_hex))        let credential = try XCTUnwrap(PasskeyAuthenticator.fromBase64url(vector.credential_id))        XCTAssertEqual(PasskeyAuthenticator.base64url(PasskeyAuthenticator.coseKey(key.publicKey)), vector.public_key)        let authData = PasskeyAuthenticator.registrationAuthData(rpId: vector.rp_id, credentialId: credential, publicKey: key.publicKey)        XCTAssertEqual(authData, hex(vector.attestation.authenticator_data_hex))        XCTAssertEqual(PasskeyAuthenticator.attestationObject(authData: authData), hex(vector.attestation.attestation_object_hex))    }    // RULE: the provider's assertion is the core's authenticatorData (UP|UV,    // counter 0), and both writers' signatures verify under the one key.    func testAssertionMatchesAndBothSignaturesVerify() throws {        let vector = try vector()        XCTAssertEqual(vector.assertion.counter, 0)        let key = try P256.Signing.PrivateKey(rawRepresentation: hex(vector.private_scalar_hex))        let authData = PasskeyAuthenticator.assertionAuthData(rpId: vector.rp_id)        XCTAssertEqual(authData, hex(vector.assertion.authenticator_data_hex))        let hash = hex(vector.client_data_hash_hex)        let rust = try P256.Signing.ECDSASignature(derRepresentation: hex(vector.assertion.signature_der_hex))        XCTAssertTrue(key.publicKey.isValidSignature(rust, for: authData + hash), "the core's signature verifies under CryptoKit")        let ours = try P256.Signing.ECDSASignature(derRepresentation: PasskeyAuthenticator.signature(authData: authData, clientDataHash: hash, key: key))        XCTAssertTrue(key.publicKey.isValidSignature(ours, for: authData + hash), "the provider's signature verifies")    }    func testCredentialIdsAreSixteenFreshBytesAndBase64urlRoundTrips() {        let one = PasskeyAuthenticator.newCredentialId()        XCTAssertEqual(one.count, 16)        XCTAssertNotEqual(one, PasskeyAuthenticator.newCredentialId())        let text = PasskeyAuthenticator.base64url(one)        XCTAssertFalse(text.contains("=") || text.contains("+") || text.contains("/"))        XCTAssertEqual(PasskeyAuthenticator.fromBase64url(text), one)    }}/// The passkey mailbox: its own key beside the share channel's, one spelling.final class PasskeyMailboxTests: XCTestCase {    private final class Storage: ShareMailboxStorage, @unchecked Sendable {        var values: [String: String] = [:]        func text(_ key: String) -> String? { values[key] }        func set(_ key: String, _ value: String?) { values[key] = value }    }    // RULE: a passkey entry is written under its own key in the share    // channel's spelling, so a share drain never takes it and the passkey    // drain never takes a share; waiting puts it back whole.    func testPasskeyEntriesNeverMeetTheShareDrain() throws {        let storage = Storage()        let passkeys = PasskeyMailbox(storage: storage)        let shares = ShareMailbox(storage: storage)        shares.append(ShareEntry(at: "2026-11-08T09:00:00Z", kind: "url", url: "https://passkey.example"))        let entry = PasskeyEntry(            at: "2026-11-08T09:30:00Z", kind: PasskeyChannel.registered, credentialId: "wMHCw8TFxsfIycrLzM3Ozw",            rpId: "passkey.example", userName: "ada@passkey.example", userHandle: "c3ludGhldGljLXVzZXItMQ",            algorithm: "ES256", publicKey: "pQECAyYg", createdAt: "2026-11-08T09:30:00Z"        )        passkeys.append(entry)        XCTAssertNotNil(storage.values[PasskeyChannel.mailboxKey])        let raw = try XCTUnwrap(storage.values[PasskeyChannel.mailboxKey])        XCTAssertTrue(raw.contains("\"credential_id\""), "the core's snake keys: \(raw)")        XCTAssertEqual(shares.drain().map(\.kind), ["url"])        XCTAssertEqual(passkeys.waiting(), [entry])        XCTAssertEqual(passkeys.drain(), [entry])        XCTAssertEqual(passkeys.drain(), [])        passkeys.wait([entry])        XCTAssertEqual(passkeys.drain(), [entry])        XCTAssertEqual(entry.arguments["rp_id"], "passkey.example")        XCTAssertNil(entry.arguments["used_at"])    }    func testTheGroupOfTheProviderIsItsApps() {        XCTAssertEqual(CottonDefaults.appGroup(bundleIdentifier: "com.cottondb.keys.dev.provider", family: .phone), "group.com.cottondb.keys.dev")        XCTAssertEqual(PasskeyChannel.knockName(bundleIdentifier: "com.cottondb.keys.provider"), "group.com.cottondb.keys.passkey.knock")    }}