Repository Public
1// SP Wallet Core2// File: Sources/SPWalletTestSupport/SoftwareAuthenticator.swift3// Description: A software WebAuthn authenticator (P-256, attestation "none") for integration tests against a THROWAWAY stack only.4// It lets the tests go through the real server and the real signer — registration, login, approval of an intent —5// without a device passkey. It is never compiled into a release build of the apps and must never be enrolled on6// the production wallet.7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10import Foundation11import CryptoKit12import SPWalletCore1314public final class SoftwareAuthenticator: PasskeyAuthenticator, @unchecked Sendable {15 private struct Stored: Codable { var credentialId: String; var privateKey: String; var userHandle: String }16 private let origin: String17 private let file: URL?18 private let lock = NSLock()19 private var stored: Stored?20 private var _signed: [Data] = []21 private var _failNext: PasskeyError?2223 /** Every challenge this authenticator signed, in order: tests assert on what was actually asked of the passkey. */24 public var signedChallenges: [Data] { lock.withLock { _signed } }25 /** When set, the next call throws it once (simulates the owner dismissing the sheet). */26 public var failNext: PasskeyError? {27 get { lock.withLock { _failNext } }28 set { lock.withLock { _failNext = newValue } }29 }3031 /**32 - Parameter origin: the origin written in clientDataJSON (what a browser or the system would put), e.g. http://localhost:8750.33 - Parameter file: where the test credential is kept between runs of the same throwaway stack.34 */35 public init(origin: String, file: URL? = nil) {36 precondition(!origin.contains("spboucher.ai"), "the software authenticator must never be used against the production wallet")37 self.origin = origin; self.file = file38 if let file, let d = try? Data(contentsOf: file) { stored = try? JSONDecoder().decode(Stored.self, from: d) }39 }4041 public var hasCredential: Bool { lock.withLock { stored != nil } }42 public var credentialId: String? { lock.withLock { stored?.credentialId } }4344 private func takeFailure() throws {45 try lock.withLock { if let f = _failNext { _failNext = nil; throw f } }46 }4748 private func clientData(type: String, challenge: String) -> Data {49 // field order of browsers; the server parses it as JSON50 Data(#"{"type":"\#(type)","challenge":"\#(challenge)","origin":"\#(origin)","crossOrigin":false}"#.utf8)51 }5253 public func register(_ options: PasskeyCreationOptions, rpId: String) async throws -> PasskeyRegistration {54 try takeFailure()55 let key = P256.Signing.PrivateKey()56 let id = Data((0..<16).map { _ in UInt8.random(in: 0...255) })57 let x963 = key.publicKey.x963Representation // 0x04 ‖ X ‖ Y58 let x = x963.subdata(in: 1..<33), y = x963.subdata(in: 33..<65)59 // COSE_Key: {1: 2 (EC2), 3: -7 (ES256), -1: 1 (P-256), -2: x, -3: y}60 var cose = Data([0xa5, 0x01, 0x02, 0x03, 0x26, 0x20, 0x01, 0x21, 0x58, 0x20]); cose.append(x); cose.append(contentsOf: [0x22, 0x58, 0x20]); cose.append(y)61 var authData = Data(SHA256.hash(data: Data(rpId.utf8)))62 authData.append(0x45) // user present, user verified, attested credential data63 authData.append(contentsOf: [0, 0, 0, 0])64 authData.append(Data(count: 16)) // aaguid65 authData.append(contentsOf: [0x00, 0x10]); authData.append(id); authData.append(cose)66 precondition(authData.count < 256)67 // {"fmt": "none", "attStmt": {}, "authData": bstr}68 var att = Data([0xa3, 0x63]); att.append(Data("fmt".utf8)); att.append(0x64); att.append(Data("none".utf8))69 att.append(0x67); att.append(Data("attStmt".utf8)); att.append(0xa0)70 att.append(0x68); att.append(Data("authData".utf8)); att.append(contentsOf: [0x58, UInt8(authData.count)]); att.append(authData)71 let s = Stored(credentialId: id.base64URL, privateKey: key.rawRepresentation.base64URL, userHandle: options.user.id)72 lock.withLock { stored = s }73 if let file { try JSONEncoder().encode(s).write(to: file, options: .atomic) }74 return PasskeyRegistration(credentialId: id, clientDataJSON: clientData(type: "webauthn.create", challenge: options.challenge), attestationObject: att, transports: ["internal"])75 }7677 public func assert(_ options: PasskeyRequestOptions, rpId: String) async throws -> PasskeyAssertion {78 try takeFailure()79 guard let s = lock.withLock({ stored }), let id = Data(base64URL: s.credentialId), let raw = Data(base64URL: s.privateKey) else { throw PasskeyError.noCredential }80 if let allow = options.allowCredentials, !allow.isEmpty, !allow.contains(where: { $0.id == s.credentialId }) { throw PasskeyError.noCredential }81 guard let challenge = options.challengeData else { throw PasskeyError.failed("bad challenge") }82 let key = try P256.Signing.PrivateKey(rawRepresentation: raw)83 var authData = Data(SHA256.hash(data: Data(rpId.utf8)))84 authData.append(0x05) // user present, user verified85 authData.append(contentsOf: [0, 0, 0, 0])86 let client = clientData(type: "webauthn.get", challenge: options.challenge)87 var signed = authData; signed.append(Data(SHA256.hash(data: client)))88 let sig = try key.signature(for: signed).derRepresentation89 lock.withLock { _signed.append(challenge) }90 return PasskeyAssertion(credentialId: id, clientDataJSON: client, authenticatorData: authData, signature: sig, userHandle: Data(base64URL: s.userHandle))91 }92}9394/** First-time owner setup of a throwaway stack with the software authenticator (the production wallet's setup is closed forever). */95public enum DevStackSetup {96 public static func ensureOwner(client: APIClient, authenticator: SoftwareAuthenticator, setupToken: String) async throws {97 let auth = AuthAPI(client)98 let state = try await auth.state()99 if state.authenticated { return }100 if state.setupRequired {101 struct Options: Decodable, Sendable { let challengeId: String; let options: PasskeyCreationOptions }102 let o: Options = try await client.post("/auth/setup/options")103 let reg = try await authenticator.register(o.options, rpId: client.configuration.rpId)104 struct Body: Encodable, Sendable { let challengeId: String; let response: PasskeyRegistration; let setupToken: String; let label: String }105 let _: OKResponse = try await client.post("/auth/setup/verify", body: Body(challengeId: o.challengeId, response: reg, setupToken: setupToken, label: "Software test key"))106 return107 }108 try await auth.login(with: authenticator)109 }110}111