SPB Git

Repository Public

SoftwareAuthenticator.swift 4.1 KB 64 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: SPChat/Tests/CoreTests/Support/SoftwareAuthenticator.swift3// Description: In-process WebAuthn authenticator (P-256, "none" attestation, user verification asserted) used to test real ceremonies without Touch ID.4import Foundation5import CryptoKit6@testable import SPChatCore78final class SoftwareAuthenticator: PasskeyAuthenticator, @unchecked Sendable {9    let origin: String10    private let lock = NSLock()11    private var keys: [Data: (key: P256.Signing.PrivateKey, userId: Data, counter: UInt32)] = [:]12    var failNext: Error?13    private(set) var assertions = 01415    init(origin: String) { self.origin = origin }16    var credentialCount: Int { lock.withLock { keys.count } }1718    private func clientData(type: String, challenge: Data) -> Data {19        Data(#"{"type":"\#(type)","challenge":"\#(challenge.base64URLEncodedString())","origin":"\#(origin)","crossOrigin":false}"#.utf8)20    }21    private static func be(_ v: UInt32) -> [UInt8] { [UInt8(v >> 24), UInt8((v >> 16) & 0xff), UInt8((v >> 8) & 0xff), UInt8(v & 0xff)] }22    private static func cborBytes(_ d: Data) -> [UInt8] {23        d.count < 24 ? [0x40 | UInt8(d.count)] + d : d.count < 256 ? [0x58, UInt8(d.count)] + d : [0x59, UInt8(d.count >> 8), UInt8(d.count & 0xff)] + d24    }25    private static func cborText(_ s: String) -> [UInt8] { [0x60 | UInt8(s.utf8.count)] + Array(s.utf8) }2627    func register(_ request: RegistrationRequest) async throws -> PasskeyRegistration {28        if let e = lock.withLock({ () -> Error? in let e = failNext; failNext = nil; return e }) { throw e }29        let key = P256.Signing.PrivateKey()30        var credId = Data(count: 32); credId.withUnsafeMutableBytes { _ = SecRandomCopyBytes(kSecRandomDefault, 32, $0.baseAddress!) }31        let raw = key.publicKey.rawRepresentation // x || y32        let x = raw.prefix(32), y = raw.suffix(32)33        // COSE_Key: {1: 2 (EC2), 3: -7 (ES256), -1: 1 (P-256), -2: x, -3: y}34        let cose: [UInt8] = [0xa5, 0x01, 0x02, 0x03, 0x26, 0x20, 0x01, 0x21] + Self.cborBytes(Data(x)) + [0x22] + Self.cborBytes(Data(y))35        var authData = Data(SHA256.hash(data: Data(request.rpId.utf8)))36        authData.append(0x45) // UP | UV | AT37        authData.append(contentsOf: Self.be(0))38        authData.append(Data(count: 16)) // aaguid39        authData.append(contentsOf: [UInt8(credId.count >> 8), UInt8(credId.count & 0xff)])40        authData.append(credId); authData.append(contentsOf: cose)41        // attestationObject: {"fmt": "none", "attStmt": {}, "authData": bytes}42        let att: [UInt8] = [0xa3] + Self.cborText("fmt") + Self.cborText("none") + Self.cborText("attStmt") + [0xa0] + Self.cborText("authData") + Self.cborBytes(authData)43        lock.withLock { keys[credId] = (key, request.userId, 0) }44        return PasskeyRegistration(credentialId: credId, clientDataJSON: clientData(type: "webauthn.create", challenge: request.challenge), attestationObject: Data(att), transports: ["internal"])45    }4647    func assert(_ request: AssertionRequest) async throws -> PasskeyAssertion {48        if let e = lock.withLock({ () -> Error? in let e = failNext; failNext = nil; return e }) { throw e }49        let entry = lock.withLock { () -> (Data, P256.Signing.PrivateKey, Data, UInt32)? in50            let id = request.allowCredentials.first(where: { keys[$0] != nil }) ?? keys.keys.first51            guard let id, var e = keys[id] else { return nil }52            e.counter += 1; keys[id] = e; assertions += 153            return (id, e.key, e.userId, e.counter)54        }55        guard let (id, key, userId, counter) = entry else { throw PasskeyError(.cancelled, "Aucune clé d'accès pour ce site.") }56        var authData = Data(SHA256.hash(data: Data(request.rpId.utf8)))57        authData.append(0x05) // UP | UV58        authData.append(contentsOf: Self.be(counter))59        let cdj = clientData(type: "webauthn.get", challenge: request.challenge)60        let sig = try key.signature(for: authData + Data(SHA256.hash(data: cdj)))61        return PasskeyAssertion(credentialId: id, clientDataJSON: cdj, authenticatorData: authData, signature: sig.derRepresentation, userHandle: userId)62    }63}64
Files main
Menu

Theme