SPB Git

Repository Public

PasskeyCryptoTests.swift 14.6 KB 259 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SP Vault9// File             : apple/SharedVaultKit/Tests/SharedVaultKitClientTests/PasskeyCryptoTests.swift10// Module           : SharedVaultKitClientTests11// Repository       : https://git.spboucher.ai/sp-vault12// Project Website  : https://vault.spboucher.ai13// Created          : 2026-11-1914// Last Modified    : 2026-11-1915//16// =============================================================================17// AUTHOR & PROFESSIONAL AFFILIATION18// =============================================================================19//20// Author           : Simon-Pierre Boucher21// Position         : Professor of Finance22// Institution      : Université du Québec en Outaouais (UQO)23// Department       : Département des sciences administratives24// Organization     : SP Boucher25//26// Website          : https://spboucher.ai27// Git              : https://git.spboucher.ai28//29// =============================================================================30// OFFICIAL CONTACT DIRECTORY31// =============================================================================32//33// General          : info@spboucher.ai34// Professional     : contact@spboucher.ai35// Direct           : simon@spboucher.ai36// Research         : research@spboucher.ai37// Development      : dev@spboucher.ai38// Support          : support@spboucher.ai39// Security/Admin   : admin@spboucher.ai40// Notifications    : notifications@spboucher.ai41//42// Preferred Contact: support@spboucher.ai43//44// =============================================================================45// COPYRIGHT & INTELLECTUAL PROPERTY46// =============================================================================47//48// Copyright (c) 202649// Simon-Pierre Boucher50//51// All rights reserved where applicable.52//53// This file is governed by the applicable project license,54// copyright notices, institutional agreements and relevant law.55//56// Unless expressly authorized by the applicable license or57// rights holder, copying, redistribution, sublicensing,58// publication and commercial exploitation are not permitted.59//60// Existing third-party rights and notices remain unaffected.61//62// =============================================================================63// CONFIDENTIALITY & SECURITY64// =============================================================================65//66// Classification   : Public67// Distribution     : Public repository; use is governed by the project license68// Security Contact : admin@spboucher.ai69//70// Access to this source does not independently grant permission71// to redistribute or disclose confidential materials.72//73// Do not embed credentials, private keys, access tokens,74// certificates or confidential personal information.75//76// =============================================================================77// LICENSE & MAINTENANCE78// =============================================================================79//80// License          : None specified (no license file in this repository)81// Maintainer       : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788// PasskeyCrypto (stored passkeys): the created credential and the assertion are checked independently —89// by parsing the CBOR / COSE structures back and verifying the signature with CryptoKit, and once with90// @simplewebauthn/server (the library the API server uses) through Tests/Tools/verify-passkey.ts.91import CryptoKit92import Foundation93import XCTest94@testable import SharedVaultKit9596/// A small, independent CBOR decoder (tests only).97indirect enum CBORValue: Equatable {98    case uint(UInt64), nint(Int64), bytes(Data), text(String), array([CBORValue]), map([(CBORValue, CBORValue)])99    static func == (a: CBORValue, b: CBORValue) -> Bool { "\(a)" == "\(b)" }100101    subscript(key: String) -> CBORValue? { if case .map(let m) = self { return m.first { $0.0 == .text(key) }?.1 }; return nil }102    subscript(key: Int64) -> CBORValue? {103        guard case .map(let m) = self else { return nil }104        return m.first { $0.0 == (key >= 0 ? .uint(UInt64(key)) : .nint(key)) }?.1105    }106107    static func decode(_ data: Data) throws -> (value: CBORValue, rest: Data) {108        var bytes = Array(data), i = 0109        func fail() -> ShellError { ShellError(description: "malformed CBOR") }110        func head() throws -> (UInt8, UInt64) {111            guard i < bytes.count else { throw fail() }112            let b = bytes[i]; i += 1113            let major = b >> 5, info = b & 31114            if info < 24 { return (major, UInt64(info)) }115            let n = info == 24 ? 1 : info == 25 ? 2 : info == 26 ? 4 : info == 27 ? 8 : 0116            guard n > 0, i + n <= bytes.count else { throw fail() }117            var v: UInt64 = 0118            for _ in 0..<n { v = v << 8 | UInt64(bytes[i]); i += 1 }119            return (major, v)120        }121        func item() throws -> CBORValue {122            let (major, n) = try head()123            switch major {124            case 0: return .uint(n)125            case 1: return .nint(-1 - Int64(n))126            case 2, 3:127                guard i + Int(n) <= bytes.count else { throw fail() }128                let d = Data(bytes[i..<i + Int(n)]); i += Int(n)129                return major == 2 ? .bytes(d) : .text(String(decoding: d, as: UTF8.self))130            case 4: return .array(try (0..<n).map { _ in try item() })131            case 5: return .map(try (0..<n).map { _ in (try item(), try item()) })132            default: throw fail()133            }134        }135        let v = try item()136        bytes = Array(bytes[i...])137        return (v, Data(bytes))138    }139}140141final class PasskeyCryptoTests: XCTestCase {142    private let rpId = "example.com"143    private func b(_ v: CBORValue?) throws -> Data { guard case .bytes(let d)? = v else { throw ShellError(description: "expected bytes") }; return d }144145    func testCreatedCredentialIsAWellFormedNoneAttestationAndAssertionVerifies() throws {146        let userHandle = Data("user-handle-1".utf8), cdh = SPV1.sha256(Data("client data".utf8))147        let c = try PasskeyCrypto.createCredential(rpId: rpId, userName: "alice", userHandle: userHandle, clientDataHash: cdh)148149        // item fields150        XCTAssertEqual(Set(c.fields.keys), ["rpId", "userName", "credentialId", "userHandle", "privateKey", "signCount"])151        XCTAssertEqual(c.fields["rpId"], rpId)152        XCTAssertEqual(c.fields["userName"], "alice")153        XCTAssertEqual(c.fields["signCount"], "0")154        XCTAssertEqual(try SPV1.unb64u(try XCTUnwrap(c.fields["credentialId"])), c.credentialID)155        XCTAssertEqual(try SPV1.unb64u(try XCTUnwrap(c.fields["userHandle"])), userHandle)156        XCTAssertEqual(try SPV1.unb64u(try XCTUnwrap(c.fields["privateKey"])).count, 97)157        XCTAssertEqual(c.credentialID.count, 16)158159        // attestation object: {"fmt": "none", "attStmt": {}, "authData": bytes}, canonical key order, nothing after it160        let (att, rest) = try CBORValue.decode(c.attestationObject)161        XCTAssertTrue(rest.isEmpty)162        guard case .map(let pairs) = att else { return XCTFail("attestation object is not a map") }163        XCTAssertEqual(pairs.map(\.0), [.text("fmt"), .text("attStmt"), .text("authData")])164        XCTAssertEqual(att["fmt"], .text("none"))165        XCTAssertEqual(att["attStmt"], .map([]))166        let authData = try b(att["authData"])167        XCTAssertEqual(authData, c.authenticatorData)168169        // authenticator data: rpIdHash ‖ flags ‖ signCount ‖ AAGUID ‖ L ‖ credentialId ‖ COSE key170        XCTAssertEqual(authData.prefix(32), SPV1.sha256(Data(rpId.utf8)))171        XCTAssertEqual(authData[32], 0x5d, "UP | UV | BE | BS | AT")172        XCTAssertEqual(Data(authData[33..<37]), Data(count: 4), "sign count 0")173        XCTAssertEqual(Data(authData[37..<53]), Data(count: 16), "AAGUID of 16 zero bytes")174        let idLen = Int(authData[53]) << 8 | Int(authData[54])175        XCTAssertEqual(idLen, 16)176        XCTAssertEqual(Data(authData[55..<55 + idLen]), c.credentialID)177        let (cose, coseRest) = try CBORValue.decode(Data(authData[(55 + idLen)...]))178        XCTAssertTrue(coseRest.isEmpty, "no extensions")179        XCTAssertEqual(cose[1], .uint(2), "kty EC2")180        XCTAssertEqual(cose[3], .nint(-7), "alg ES256")181        XCTAssertEqual(cose[-1], .uint(1), "crv P-256")182        let x = try b(cose[-2]), y = try b(cose[-3])183        XCTAssertEqual(x.count, 32); XCTAssertEqual(y.count, 32)184        let publicKey = try P256.Signing.PublicKey(x963Representation: Data([4]) + x + y)185        XCTAssertEqual(publicKey.x963Representation, c.publicKey)186187        // assertion: DER signature over authData ‖ clientDataHash, verified with the key parsed from the COSE structure188        let cdh2 = SPV1.sha256(Data("another client data".utf8))189        let a = try PasskeyCrypto.assert(fields: c.fields, clientDataHash: cdh2)190        XCTAssertEqual(a.credentialID, c.credentialID)191        XCTAssertEqual(a.userHandle, userHandle)192        XCTAssertEqual(a.authenticatorData.count, 37)193        XCTAssertEqual(a.authenticatorData.prefix(32), SPV1.sha256(Data(rpId.utf8)))194        XCTAssertEqual(a.authenticatorData[32], 0x1d, "UP | UV | BE | BS")195        XCTAssertEqual(Data(a.authenticatorData[33...]), Data(count: 4))196        XCTAssertEqual(a.signature.first, 0x30, "ASN.1 DER SEQUENCE")197        let sig = try P256.Signing.ECDSASignature(derRepresentation: a.signature)198        XCTAssertTrue(publicKey.isValidSignature(sig, for: a.authenticatorData + cdh2))199        XCTAssertFalse(publicKey.isValidSignature(sig, for: a.authenticatorData + cdh))200        // without user verification the UV flag is cleared201        XCTAssertEqual(try PasskeyCrypto.assert(fields: c.fields, clientDataHash: cdh2, userVerified: false).authenticatorData[32], 0x19)202        XCTAssertEqual(try PasskeyCrypto.createCredential(rpId: rpId, userName: "a", userHandle: userHandle, clientDataHash: cdh, userVerified: false).authenticatorData[32], 0x59)203204        // malformed input205        var broken = c.fields206        broken["privateKey"] = SPV1.b64u(SPV1.random(97))207        XCTAssertThrowsError(try PasskeyCrypto.assert(fields: broken, clientDataHash: cdh))208        XCTAssertThrowsError(try PasskeyCrypto.assert(fields: ["rpId": rpId], clientDataHash: cdh))209        XCTAssertThrowsError(try PasskeyCrypto.assert(fields: c.fields, clientDataHash: Data(count: 31)))210        XCTAssertThrowsError(try PasskeyCrypto.createCredential(rpId: "", userName: "a", userHandle: userHandle, clientDataHash: cdh))211212        // the vault item round-trips through the item model213        let item = PasskeyCrypto.makeItem(c)214        XCTAssertEqual(item.type, .passkey)215        XCTAssertEqual(try Item(json: item.jsonData).fields, c.fields)216    }217218    func testCborEncoderHeads() throws {219        XCTAssertEqual(CBOR.uint(23), Data([0x17])); XCTAssertEqual(CBOR.uint(24), Data([0x18, 24])); XCTAssertEqual(CBOR.uint(256), Data([0x19, 1, 0]))220        XCTAssertEqual(CBOR.uint(65536), Data([0x1a, 0, 1, 0, 0])); XCTAssertEqual(CBOR.nint(-7), Data([0x26])); XCTAssertEqual(CBOR.nint(-1), Data([0x20]))221        XCTAssertEqual(CBOR.bytes(Data(count: 300)).prefix(3), Data([0x59, 1, 44])); XCTAssertEqual(CBOR.text("none"), Data([0x64]) + Data("none".utf8))222        let (v, _) = try CBORValue.decode(CBOR.map([(CBOR.text("a"), CBOR.bytes(Data(count: 70000)))]))223        XCTAssertEqual(v["a"], .bytes(Data(count: 70000)))224    }225226    func testVerifiedBySimpleWebAuthnServer() throws {227        let origin = "https://example.com"228        func clientData(_ type: String, _ challenge: String) -> Data {229            (["type": .string(type), "challenge": .string(challenge), "origin": .string(origin), "crossOrigin": false] as JSONValue).serialized()230        }231        let challenge = SPV1.b64u(SPV1.random(32)), challenge2 = SPV1.b64u(SPV1.random(32))232        let cdCreate = clientData("webauthn.create", challenge), cdGet = clientData("webauthn.get", challenge2)233        let c = try PasskeyCrypto.createCredential(rpId: rpId, userName: "alice", userHandle: Data("uh".utf8), clientDataHash: SPV1.sha256(cdCreate))234        let a = try PasskeyCrypto.assert(fields: c.fields, clientDataHash: SPV1.sha256(cdGet))235        let id = SPV1.b64u(c.credentialID)236        let input: JSONValue = [237            "rpId": .string(rpId), "origin": .string(origin), "challenge": .string(challenge), "assertionChallenge": .string(challenge2),238            "registration": ["id": .string(id), "rawId": .string(id), "type": "public-key", "clientExtensionResults": .object(JSONObject()), "authenticatorAttachment": "platform",239                             "response": ["clientDataJSON": .string(SPV1.b64u(cdCreate)), "attestationObject": .string(SPV1.b64u(c.attestationObject)), "transports": ["internal"]]],240            "assertion": ["id": .string(id), "rawId": .string(id), "type": "public-key", "clientExtensionResults": .object(JSONObject()), "authenticatorAttachment": "platform",241                          "response": ["clientDataJSON": .string(SPV1.b64u(cdGet)), "authenticatorData": .string(SPV1.b64u(a.authenticatorData)), "signature": .string(SPV1.b64u(a.signature)), "userHandle": .string(SPV1.b64u(a.userHandle))]],242        ]243        guard FileManager.default.fileExists(atPath: TestEnv.repoRoot.appendingPathComponent("node_modules/@simplewebauthn/server").path) else { throw XCTSkip("node_modules not installed") }244        let out = try JSONValue.parse(try runTool("node", ["--import", "tsx", "apple/SharedVaultKit/Tests/Tools/verify-passkey.ts"], input: input.serialized(), cwd: TestEnv.repoRoot))245        XCTAssertEqual(out["registration"]?["verified"], true)246        XCTAssertEqual(out["registration"]?["fmt"], "none")247        XCTAssertEqual(out["registration"]?["credentialId"], .string(id))248        XCTAssertEqual(out["registration"]?["counter"], 0)249        XCTAssertEqual(out["registration"]?["aaguid"], "00000000-0000-0000-0000-000000000000")250        XCTAssertEqual(out["registration"]?["userVerified"], true)251        XCTAssertEqual(out["registration"]?["deviceType"], "multiDevice")252        XCTAssertEqual(out["registration"]?["backedUp"], true)253        XCTAssertEqual(out["assertion"]?["verified"], true)254        XCTAssertEqual(out["assertion"]?["userVerified"], true)255        XCTAssertEqual(out["assertion"]?["newCounter"], 0)256        XCTAssertEqual(out["assertion"]?["backedUp"], true)257    }258}259
Files main
Menu

Theme