import CryptoKit import Foundation import Testing @testable import EquipoKit /// The server's bytes, from `personapi.TestNativeDeviceProofVectors`. struct ProofVector: Decodable { let name, seed, publicKey, instance, id, challenge, nonce, message, signature: String } @Suite struct DeviceProofTests { let vectors: [ProofVector] = try! Fixture.decode("device-proof-vectors") @Test func messageIsTheServersBytes() { for v in vectors { let ours = DeviceProof.message(instance: v.instance, id: v.id, challenge: v.challenge, nonce: v.nonce) #expect(String(decoding: ours, as: UTF8.self) == v.message, "vector \(v.name)") } } @Test func signaturesVerifyBothWays() throws { for v in vectors { let key = try Curve25519.Signing.PrivateKey(rawRepresentation: Base64URL.decode(v.seed)!) #expect(Base64URL.encode(key.publicKey.rawRepresentation) == v.publicKey) let message = Data(v.message.utf8) // The server's signature verifies here, and ours verifies with the server's key. #expect(key.publicKey.isValidSignature(Base64URL.decode(v.signature)!, for: message)) #expect(key.publicKey.isValidSignature(try key.signature(for: message), for: message)) } } @Test func instanceComesFromTheChallenge() { for v in vectors { #expect(DeviceProof.instance(fromChallenge: v.challenge) == v.instance) } #expect(DeviceProof.instance(fromChallenge: "not base64 json") == nil) } @Test func noncesAreFreshAndLongEnough() { let a = DeviceProof.nonce(), b = DeviceProof.nonce() #expect(a != b) #expect(Base64URL.decode(a)!.count == 32) } @Test func exchangeBodyIsSnakeCase() throws { let challenge: DeviceChallenge = try Fixture.decode("device-challenge") let body = try DeviceProof.body(for: challenge, key: .init(), nonce: "nonce-0123456789ab") let json = try JSONSerialization.jsonObject(with: EquipoJSON.encoder.encode(body)) as! [String: String] #expect(Set(json.keys) == ["id", "device_secret", "challenge", "nonce", "signature"]) } }