SPB Git

Repository Public

IdentityTests.swift 39.0 KB 621 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Tests/QyvoraIdentityTests/IdentityTests.swift8// Module           : Tests9// Repository       : https://git.spboucher.ai/qyvora10// Project Website  : Not specified11// Created          : 2026-12-0412// Last Modified    : 2026-12-0413//14// Author           : Simon-Pierre Boucher15// Position         : Professor of Finance16// Institution      : Université du Québec en Outaouais (UQO)17// Organization     : SP Boucher18// Website          : https://spboucher.ai19// Git              : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development      : dev@spboucher.ai23// Support          : support@spboucher.ai24// Security/Admin   : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License          : None specified (no license file in this repository)33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041import CryptoKit42import Foundation43import QyvoraMath44import QyvoraStorage45import QyvoraVault46import Testing4748@testable import QyvoraIdentity4950/// Key generation (SLH-DSA in particular) is slow in debug builds: the suites share four identities.51enum People {52    static let alice = Identity.generate(createdAt: Date(timeIntervalSince1970: 1_800_000_000))53    static let bob = Identity.generate(createdAt: Date(timeIntervalSince1970: 1_800_000_100))54    static let carol = Identity.generate(createdAt: Date(timeIntervalSince1970: 1_800_000_200))55    static let mallory = Identity.generate(createdAt: Date(timeIntervalSince1970: 1_800_000_300))56}5758@Suite struct PublicIdentityTests {59    @Test func binaryAndTextRoundTrip() throws {60        let p = People.alice.publicIdentity61        let encoded = p.encoded()62        #expect(encoded.count == 4278)63        #expect(Bytes(encoded[0..<6]) == Bytes("QYID".utf8) + [1, 1])64        #expect(try PublicIdentity(encoded: encoded) == p)65        #expect(p.text.hasPrefix("qyvora-id:"))66        #expect(try PublicIdentity(text: p.text) == p)67        #expect(p.createdAt == 1_800_000_000)68        #expect(p.mldsaPublicKey.count == 2592 && p.slhdsaPublicKey.count == 64 && p.mlkemPublicKey.count == 1568 && p.x25519PublicKey.count == 32)69    }7071    @Test func strictParsing() throws {72        let p = People.alice.publicIdentity73        let encoded = p.encoded()74        #expect(throws: IdentityError.malformed) { _ = try PublicIdentity(encoded: encoded + [0]) }75        #expect(throws: IdentityError.malformed) { _ = try PublicIdentity(encoded: Bytes(encoded.dropLast())) }76        #expect(throws: IdentityError.malformed) { _ = try PublicIdentity(encoded: []) }77        var bad = encoded78        bad[0] = 0x51 ^ 0x2079        #expect(throws: IdentityError.malformed) { _ = try PublicIdentity(encoded: bad) }80        bad = encoded81        bad[4] = 282        #expect(throws: IdentityError.unsupportedVersion(2)) { _ = try PublicIdentity(encoded: bad) }83        bad = encoded84        bad[5] = 985        #expect(throws: IdentityError.malformed) { _ = try PublicIdentity(encoded: bad) }86        // a length prefix that disagrees with the suite87        bad = encoded88        bad[15] ^= 0x0189        #expect(throws: (any Error).self) { _ = try PublicIdentity(encoded: bad) }9091        #expect(throws: IdentityError.invalidText) { _ = try PublicIdentity(text: "qyvora:" + Base64URL.encode(encoded)) }92        #expect(throws: IdentityError.invalidText) { _ = try PublicIdentity(text: p.text + "=") }93        #expect(throws: IdentityError.invalidText) { _ = try PublicIdentity(text: p.text.replacingOccurrences(of: "-", with: "+")) }94        #expect(throws: IdentityError.invalidText) { _ = try PublicIdentity(text: " " + p.text) }95        #expect(throws: IdentityError.malformed) { _ = try PublicIdentity(text: String(p.text.dropLast(4))) }9697        // key validation98        #expect(throws: IdentityError.invalidKey) {99            _ = try PublicIdentity(createdAt: 0, mldsaPublicKey: Bytes(p.mldsaPublicKey.dropLast()), slhdsaPublicKey: p.slhdsaPublicKey, mlkemPublicKey: p.mlkemPublicKey, x25519PublicKey: p.x25519PublicKey)100        }101        var kem = p.mlkemPublicKey102        kem[0] = 0xff103        kem[1] = 0xff  // first coefficient 4095 ≥ q: fails the FIPS 203 modulus check104        #expect(throws: IdentityError.invalidKey) {105            _ = try PublicIdentity(createdAt: 0, mldsaPublicKey: p.mldsaPublicKey, slhdsaPublicKey: p.slhdsaPublicKey, mlkemPublicKey: kem, x25519PublicKey: p.x25519PublicKey)106        }107    }108109    @Test func fingerprint() throws {110        let p = People.alice.publicIdentity111        #expect(p.fingerprint.count == 32)112        #expect(p.fingerprint != People.bob.publicIdentity.fingerprint)113114        // independent recomputation with CryptoKit SHA3-256115        var input = Bytes("QYVORA-IDENTITY-v1/fingerprint".utf8) + [1]116        for key in [p.mldsaPublicKey, p.slhdsaPublicKey, p.mlkemPublicKey, p.x25519PublicKey] {117            input += [UInt8(key.count >> 8), UInt8(key.count & 0xff)] + key118        }119        #expect(p.fingerprint == Bytes(CryptoKit.SHA3_256.hash(data: input)))120121        // the creation time is not part of it; each key is122        let later = try PublicIdentity(createdAt: 5, mldsaPublicKey: p.mldsaPublicKey, slhdsaPublicKey: p.slhdsaPublicKey, mlkemPublicKey: p.mlkemPublicKey, x25519PublicKey: p.x25519PublicKey)123        #expect(later.fingerprint == p.fingerprint && later != p)124        let b = People.bob.publicIdentity125        let variants = [126            try PublicIdentity(createdAt: p.createdAt, mldsaPublicKey: b.mldsaPublicKey, slhdsaPublicKey: p.slhdsaPublicKey, mlkemPublicKey: p.mlkemPublicKey, x25519PublicKey: p.x25519PublicKey),127            try PublicIdentity(createdAt: p.createdAt, mldsaPublicKey: p.mldsaPublicKey, slhdsaPublicKey: b.slhdsaPublicKey, mlkemPublicKey: p.mlkemPublicKey, x25519PublicKey: p.x25519PublicKey),128            try PublicIdentity(createdAt: p.createdAt, mldsaPublicKey: p.mldsaPublicKey, slhdsaPublicKey: p.slhdsaPublicKey, mlkemPublicKey: b.mlkemPublicKey, x25519PublicKey: p.x25519PublicKey),129            try PublicIdentity(createdAt: p.createdAt, mldsaPublicKey: p.mldsaPublicKey, slhdsaPublicKey: p.slhdsaPublicKey, mlkemPublicKey: p.mlkemPublicKey, x25519PublicKey: b.x25519PublicKey),130        ]131        #expect(Set(variants.map(\.fingerprint) + [p.fingerprint]).count == 5)132133        let text = p.fingerprintText134        let groups = text.split(separator: " ")135        #expect(groups.count == 16 && groups.allSatisfy { $0.count == 4 })136        #expect(text.replacingOccurrences(of: " ", with: "").lowercased() == p.fingerprint.hex)137        #expect(text == text.uppercased())138    }139}140141@Suite struct IdentityKeyTests {142    @Test func privateEncodingRoundTrip() throws {143        let alice = People.alice144        var encoding = alice.privateEncoding()145        defer { SecureMemory.zero(&encoding) }146        #expect(Bytes(encoding[0..<5]) == Bytes("QYIK".utf8) + [1])147        #expect(encoding.count == 4 + 1 + 4 + 4278 + (2 + 4896) + (2 + 128) + (2 + 3168) + (2 + 32))148        let restored = try Identity(privateEncoding: encoding)149        #expect(restored.publicIdentity == alice.publicIdentity)150        let message = Bytes("restored keys sign".utf8)151        #expect(try restored.sign(message).verify(message: message, signer: alice.publicIdentity, purpose: .message))152153        #expect(throws: IdentityError.malformed) { _ = try Identity(privateEncoding: Bytes(encoding.dropLast())) }154        #expect(throws: IdentityError.malformed) { _ = try Identity(privateEncoding: encoding + [0]) }155        #expect(throws: IdentityError.malformed) { _ = try Identity(privateEncoding: Bytes(encoding.dropFirst())) }156        var bad = encoding157        bad[4] = 7158        #expect(throws: IdentityError.unsupportedVersion(7)) { _ = try Identity(privateEncoding: bad) }159    }160161    @Test func privateKeysMustMatchThePublicIdentity() throws {162        let a = People.alice, b = People.bob163        let mixes = [164            Identity(publicIdentity: a.publicIdentity, mldsaPrivateKey: b.mldsaPrivateKey, slhdsaSecretKey: a.slhdsaSecretKey, mlkemDecapsulationKey: a.mlkemDecapsulationKey, x25519PrivateKey: a.x25519PrivateKey),165            Identity(publicIdentity: a.publicIdentity, mldsaPrivateKey: a.mldsaPrivateKey, slhdsaSecretKey: b.slhdsaSecretKey, mlkemDecapsulationKey: a.mlkemDecapsulationKey, x25519PrivateKey: a.x25519PrivateKey),166            Identity(publicIdentity: a.publicIdentity, mldsaPrivateKey: a.mldsaPrivateKey, slhdsaSecretKey: a.slhdsaSecretKey, mlkemDecapsulationKey: b.mlkemDecapsulationKey, x25519PrivateKey: a.x25519PrivateKey),167            Identity(publicIdentity: a.publicIdentity, mldsaPrivateKey: a.mldsaPrivateKey, slhdsaSecretKey: a.slhdsaSecretKey, mlkemDecapsulationKey: a.mlkemDecapsulationKey, x25519PrivateKey: b.x25519PrivateKey),168        ]169        for mix in mixes {170            #expect(throws: IdentityError.invalidKey) { _ = try Identity(privateEncoding: mix.privateEncoding()) }171        }172    }173174    @Test func storedInTheVaultAsAnIdentityRecord() async throws {175        let root = FileManager.default.temporaryDirectory.appendingPathComponent("qyvora-identity-\(UUID().uuidString)", isDirectory: true)176        defer { try? FileManager.default.removeItem(at: root) }177        let vault = Vault(178            fileStore: try FileStore(root: root), keychain: InMemoryKeychainStore(), configuration: .init(kdf: .insecureForTesting))179        try await vault.create(password: "pw")180        let id = try await People.alice.store(in: vault)181        #expect(try await vault.recordSummaries().map(\.type) == [.identityKeys])182        let other = try await vault.addRecord(type: .custom, payload: [1])183        await vault.lock()184        do {185            _ = try await Identity.load(from: vault, record: id)186            Issue.record("a locked vault must not release the identity")187        } catch let error as IdentityError {188            #expect(error == .vault(.locked))189        }190        try await vault.unlock(password: "pw")191        let loaded = try await Identity.load(from: vault, record: id)192        #expect(loaded.publicIdentity == People.alice.publicIdentity)193        #expect(loaded.privateEncoding() == People.alice.privateEncoding())194        do {195            _ = try await Identity.load(from: vault, record: other)196            Issue.record("a record of another type is not an identity")197        } catch let error as IdentityError {198            #expect(error == .malformed)199        }200    }201202    @Test func x25519() throws {203        let a = X25519.generateKeyPair(), b = X25519.generateKeyPair()204        #expect(try X25519.publicKey(privateKey: a.privateKey) == a.publicKey)205        let s1 = try X25519.sharedSecret(privateKey: a.privateKey, publicKey: b.publicKey)206        let s2 = try X25519.sharedSecret(privateKey: b.privateKey, publicKey: a.publicKey)207        #expect(s1 == s2 && s1.count == 32)208        // RFC 7748, section 6.1209        let alicePrivate = try #require(Bytes(hex: "77076d0a7318a57d3c16c17251b26645df4c2f87ebc0992ab177fba51db92c2a"))210        let bobPublic = try #require(Bytes(hex: "de9edb7d7b7dc1b4d35b61c2ece435373f8343c85b78674dadfc7e146f882b4f"))211        #expect(try X25519.publicKey(privateKey: alicePrivate).hex == "8520f0098930a754748b7ddcb43ef75a0dbf3a0d26381af4eba4a98eaa9b4e6a")212        #expect(try X25519.sharedSecret(privateKey: alicePrivate, publicKey: bobPublic).hex == "4a5d9d5ba4ce2de1728e3bf480350f25e07e21c947d19e3376f09b3c1e161742")213        // the all-zero point gives an all-zero secret: refused214        #expect(throws: X25519.Failure.weakSharedSecret) { _ = try X25519.sharedSecret(privateKey: a.privateKey, publicKey: Bytes(repeating: 0, count: 32)) }215        #expect(throws: X25519.Failure.invalidKey) { _ = try X25519.sharedSecret(privateKey: a.privateKey, publicKey: [1, 2, 3]) }216    }217}218219@Suite struct IdentitySignatureTests {220    let message = Bytes("I, Alice, approve this device.".utf8)221222    @Test func signAndVerify() throws {223        let alice = People.alice224        let signature = try alice.sign(message)225        #expect(!signature.isDual)226        #expect(signature.signerFingerprint == alice.fingerprint)227        #expect(signature.verify(message: message, signer: alice.publicIdentity, purpose: .message))228        #expect(signature.encoded().count == 4 + 1 + 1 + 32 + 1 + 7 + 2 + 4627)229        #expect(try IdentitySignature(encoded: signature.encoded()) == signature)230231        // hedged signing: two signatures of the same message differ and both verify232        let again = try alice.sign(message)233        #expect(again != signature && again.verify(message: message, signer: alice.publicIdentity, purpose: .message))234235        // what must fail236        #expect(!signature.verify(message: message + [0], signer: alice.publicIdentity, purpose: .message))237        #expect(!signature.verify(message: Bytes(message.dropLast()), signer: alice.publicIdentity, purpose: .message))238        #expect(!signature.verify(message: message, signer: People.bob.publicIdentity, purpose: .message))239        #expect(!signature.verify(message: message, signer: alice.publicIdentity, purpose: .backup))240        #expect(!signature.verify(message: message, signer: alice.publicIdentity, purpose: .message, requireDual: true))241        for offset in [0, 1, 100, 2000, 4626] {242            var bytes = signature.mldsaSignature243            bytes[offset] ^= 0x04244            let tampered = IdentitySignature(signerFingerprint: signature.signerFingerprint, purpose: .message, mldsaSignature: bytes, slhdsaSignature: nil)245            #expect(!tampered.verify(message: message, signer: alice.publicIdentity, purpose: .message))246        }247    }248249    @Test func contextSeparatesPurposes() throws {250        let alice = People.alice251        let custom = try #require(SignaturePurpose("payment-request/v1"))252        #expect(custom.context == Bytes("QYVORA-IDENTITY-v1/payment-request/v1".utf8))253        let signature = try alice.sign(message, purpose: custom)254        #expect(signature.verify(message: message, signer: alice.publicIdentity, purpose: custom))255        #expect(!signature.verify(message: message, signer: alice.publicIdentity, purpose: .message))256        // relabelling the signature object does not help: the context is inside the signature257        let relabelled = IdentitySignature(signerFingerprint: signature.signerFingerprint, purpose: .message, mldsaSignature: signature.mldsaSignature, slhdsaSignature: nil)258        #expect(!relabelled.verify(message: message, signer: alice.publicIdentity, purpose: .message))259260        for bad in ["", "Upper", "with space", "é", String(repeating: "a", count: 65), "semi;colon"] {261            #expect(SignaturePurpose(bad) == nil)262        }263        #expect(SignaturePurpose(String(repeating: "a", count: 64)) != nil)264    }265266    @Test func signatureVerifiesWithCryptoKit() throws {267        // independent check of the signed bytes and context with the system ML-DSA-87268        let alice = People.alice269        let signature = try alice.sign(message)270        let key = try CryptoKit.MLDSA87.PublicKey(rawRepresentation: Data(alice.publicIdentity.mldsaPublicKey))271        let tbs = Bytes("QYVORA-IDENTITY-v1/tbs".utf8) + [0] + alice.fingerprint + message272        #expect(key.isValidSignature(Data(signature.mldsaSignature), for: Data(tbs), context: Data("QYVORA-IDENTITY-v1/message".utf8)))273        #expect(!key.isValidSignature(Data(signature.mldsaSignature), for: Data(message), context: Data("QYVORA-IDENTITY-v1/message".utf8)))274    }275276    @Test func dualSignature() throws {277        let alice = People.alice278        let dual = try alice.sign(message, purpose: .backup, dual: true)279        #expect(dual.isDual)280        #expect(dual.slhdsaSignature?.count == 49856)281        #expect(dual.verify(message: message, signer: alice.publicIdentity, purpose: .backup))282        #expect(dual.verify(message: message, signer: alice.publicIdentity, purpose: .backup, requireDual: true))283        #expect(!dual.verify(message: message + [1], signer: alice.publicIdentity, purpose: .backup))284        let encoded = dual.encoded()285        #expect(encoded.count == 4 + 1 + 1 + 32 + 1 + 6 + 2 + 4627 + 2 + 49856)286        #expect(try IdentitySignature(encoded: encoded) == dual)287288        // each half is required289        var slh = try #require(dual.slhdsaSignature)290        slh[40_000] ^= 0x01291        let badSLH = IdentitySignature(signerFingerprint: dual.signerFingerprint, purpose: .backup, mldsaSignature: dual.mldsaSignature, slhdsaSignature: slh)292        #expect(!badSLH.verify(message: message, signer: alice.publicIdentity, purpose: .backup))293        var dsa = dual.mldsaSignature294        dsa[10] ^= 0x01295        let badDSA = IdentitySignature(signerFingerprint: dual.signerFingerprint, purpose: .backup, mldsaSignature: dsa, slhdsaSignature: dual.slhdsaSignature)296        #expect(!badDSA.verify(message: message, signer: alice.publicIdentity, purpose: .backup))297298        // stripping the SLH-DSA half does not leave a valid single signature (the flags byte is signed)299        let stripped = IdentitySignature(signerFingerprint: dual.signerFingerprint, purpose: .backup, mldsaSignature: dual.mldsaSignature, slhdsaSignature: nil)300        #expect(!stripped.verify(message: message, signer: alice.publicIdentity, purpose: .backup))301        // nor can a second half be glued to a single signature302        let single = try alice.sign(message, purpose: .backup)303        let glued = IdentitySignature(signerFingerprint: single.signerFingerprint, purpose: .backup, mldsaSignature: single.mldsaSignature, slhdsaSignature: dual.slhdsaSignature)304        #expect(!glued.verify(message: message, signer: alice.publicIdentity, purpose: .backup))305    }306307    @Test func strictSignatureParsing() throws {308        let encoded = try People.alice.sign(message).encoded()309        #expect(throws: IdentityError.malformed) { _ = try IdentitySignature(encoded: encoded + [0]) }310        #expect(throws: IdentityError.malformed) { _ = try IdentitySignature(encoded: Bytes(encoded.dropLast())) }311        var bad = encoded312        bad[5] = 1  // announces an SLH-DSA signature that is not there313        #expect(throws: IdentityError.malformed) { _ = try IdentitySignature(encoded: bad) }314        bad[5] = 2315        #expect(throws: IdentityError.malformed) { _ = try IdentitySignature(encoded: bad) }316        bad = encoded317        bad[4] = 3318        #expect(throws: IdentityError.unsupportedVersion(3)) { _ = try IdentitySignature(encoded: bad) }319        bad = encoded320        bad[39] = 0x41  // upper-case letter in the purpose name321        #expect(throws: IdentityError.malformed) { _ = try IdentitySignature(encoded: bad) }322    }323}324325@Suite struct RotationTests {326    static let ab = try! RotationCertificate.issue(previous: People.alice, next: People.bob, at: Date(timeIntervalSince1970: 1_800_001_000), dual: false)327    static let bc = try! RotationCertificate.issue(previous: People.bob, next: People.carol, at: Date(timeIntervalSince1970: 1_800_002_000), dual: false)328329    @Test func chainVerification() throws {330        let a = People.alice.publicIdentity, b = People.bob.publicIdentity, c = People.carol.publicIdentity331        #expect(Self.ab.verify() && Self.bc.verify())332        #expect(!Self.ab.verify(requireDual: true))333        var chain = RotationChain()334        #expect(try chain.verify(from: a) == a)335        chain.append(Self.ab)336        #expect(try chain.verify(from: a) == b)337        chain.append(Self.bc)338        #expect(try chain.verify(from: a) == c)339        // a peer who already trusts B verifies the tail340        #expect(try RotationChain([Self.bc]).verify(from: b) == c)341342        let encoded = chain.encoded()343        let decoded = try RotationChain(encoded: encoded)344        #expect(decoded == chain)345        #expect(try decoded.verify(from: a) == c)346        #expect(try RotationCertificate(encoded: Self.ab.encoded()) == Self.ab)347        #expect(throws: IdentityError.malformed) { _ = try RotationChain(encoded: encoded + [0]) }348        #expect(throws: IdentityError.malformed) { _ = try RotationChain(encoded: Bytes(encoded.dropLast(3))) }349        #expect(throws: IdentityError.malformed) { _ = try RotationCertificate(encoded: Bytes(Self.ab.encoded().dropLast())) }350    }351352    @Test func forgedChainsAreRejected() throws {353        let a = People.alice.publicIdentity, b = People.bob.publicIdentity, c = People.carol.publicIdentity354        let mallory = People.mallory355        func rejected(_ certificates: [RotationCertificate], from root: PublicIdentity, _ label: String) {356            #expect(throws: IdentityError.brokenChain, "\(label)") { _ = try RotationChain(certificates).verify(from: root) }357        }358359        // Mallory claims to succeed Alice, signing both halves with her own keys360        let statement = RotationCertificate.statement(issuedAt: 1_800_001_500, previous: a, next: mallory.publicIdentity)361        let own = try mallory.sign(statement, purpose: .rotation)362        let takeover = RotationCertificate(issuedAt: 1_800_001_500, previous: a, next: mallory.publicIdentity, previousSignature: own, nextSignature: own)363        #expect(!takeover.verify())364        rejected([takeover], from: a, "takeover signed by the attacker")365366        // …or relabels her signature with Alice's fingerprint367        let relabelled = IdentitySignature(signerFingerprint: a.fingerprint, purpose: .rotation, mldsaSignature: own.mldsaSignature, slhdsaSignature: nil)368        rejected([RotationCertificate(issuedAt: 1_800_001_500, previous: a, next: mallory.publicIdentity, previousSignature: relabelled, nextSignature: own)], from: a, "relabelled signature")369370        // a genuine certificate whose successor was swapped371        rejected([RotationCertificate(issuedAt: Self.ab.issuedAt, previous: a, next: mallory.publicIdentity, previousSignature: Self.ab.previousSignature, nextSignature: Self.ab.nextSignature)], from: a, "successor swapped")372        // …or whose date was changed373        rejected([RotationCertificate(issuedAt: Self.ab.issuedAt + 1, previous: a, next: b, previousSignature: Self.ab.previousSignature, nextSignature: Self.ab.nextSignature)], from: a, "date changed")374        // the successor must prove possession of the new keys375        rejected([RotationCertificate(issuedAt: Self.ab.issuedAt, previous: a, next: b, previousSignature: Self.ab.previousSignature, nextSignature: Self.ab.previousSignature)], from: a, "no proof of possession")376377        // Mallory appends a valid certificate of her own to a genuine chain: it does not start where the chain ends378        let side = try RotationCertificate.issue(previous: mallory, next: People.carol, at: Date(timeIntervalSince1970: 1_800_003_000), dual: false)379        rejected([Self.ab, side], from: a, "foreign link")380381        rejected([Self.bc], from: a, "missing first link")382        rejected([Self.bc, Self.ab], from: a, "links out of order")383        rejected([Self.ab, Self.bc], from: c, "wrong root")384        rejected([Self.ab, Self.ab], from: a, "repeated link")385386        // going back in time, and returning to an earlier identity387        let early = try RotationCertificate.issue(previous: People.bob, next: People.carol, at: Date(timeIntervalSince1970: 1_800_000_500), dual: false)388        rejected([Self.ab, early], from: a, "time goes backwards")389        let back = try RotationCertificate.issue(previous: People.bob, next: People.alice, at: Date(timeIntervalSince1970: 1_800_002_500), dual: false)390        rejected([Self.ab, back], from: a, "loop")391        let selfSigned = try RotationCertificate.issue(previous: People.alice, next: People.alice, at: Date(timeIntervalSince1970: 1_800_002_500), dual: false)392        #expect(!selfSigned.verify())393        #expect(b != c)394    }395396    @Test func rotateProducesADualSignedSuccessor() throws {397        let (next, certificate) = try People.carol.rotate(at: Date(timeIntervalSince1970: 1_800_010_000))398        #expect(certificate.previous == People.carol.publicIdentity)399        #expect(certificate.next == next.publicIdentity)400        #expect(next.fingerprint != People.carol.fingerprint)401        #expect(certificate.previousSignature.isDual && certificate.nextSignature.isDual)402        #expect(certificate.verify(requireDual: true))403        #expect(try RotationChain([certificate]).verify(from: People.carol.publicIdentity, requireDual: true) == next.publicIdentity)404        let decoded = try RotationCertificate(encoded: certificate.encoded())405        #expect(decoded == certificate && decoded.verify(requireDual: true))406        // a chain that mixes in single-signed links fails when dual signatures are required407        #expect(throws: IdentityError.brokenChain) { _ = try RotationChain([RotationTests.ab]).verify(from: People.alice.publicIdentity, requireDual: true) }408    }409}410411@Suite struct HybridEnvelopeTests {412    let payload = Bytes("backup payload for the new iPhone".utf8)413    static let type = "qyvora/test-v1"414    static let envelope = try! HybridEnvelope.seal(415        Bytes("backup payload for the new iPhone".utf8), contentType: type, to: People.bob.publicIdentity, from: People.alice)416417    func rebuilt(418        _ e: HybridEnvelope, contentType: String? = nil, sender: PublicIdentity? = nil, recipient: Bytes? = nil, ephemeral: Bytes? = nil,419        kem: Bytes? = nil, nonce: Bytes? = nil, ciphertext: Bytes? = nil, signature: IdentitySignature? = nil420    ) -> HybridEnvelope {421        HybridEnvelope(422            contentType: contentType ?? e.contentType, sender: sender ?? e.sender, recipientFingerprint: recipient ?? e.recipientFingerprint,423            ephemeralX25519PublicKey: ephemeral ?? e.ephemeralX25519PublicKey, mlkemCiphertext: kem ?? e.mlkemCiphertext,424            nonce: nonce ?? e.nonce, ciphertext: ciphertext ?? e.ciphertext, signature: signature ?? e.signature)425    }426427    func flipped(_ bytes: Bytes, _ index: Int) -> Bytes {428        var b = bytes429        b[index] ^= 0x01430        return b431    }432433    @Test func roundTrip() throws {434        let e = Self.envelope435        #expect(e.sender == People.alice.publicIdentity)436        #expect(e.recipientFingerprint == People.bob.fingerprint)437        #expect(e.mlkemCiphertext.count == 1568 && e.ephemeralX25519PublicKey.count == 32 && e.nonce.count == 12)438        #expect(e.ciphertext.count == payload.count + 16)439        #expect(e.verifySignature())440        #expect(try e.open(with: People.bob) == payload)441        #expect(try e.open(with: People.bob, expectedSender: People.alice.publicIdentity, expectedContentType: Self.type) == payload)442443        let encoded = e.encoded()444        #expect(Bytes(encoded[0..<5]) == Bytes("QYEN".utf8) + [1])445        let decoded = try HybridEnvelope(encoded: encoded)446        #expect(decoded == e)447        #expect(try decoded.open(with: People.bob) == payload)448449        // every envelope uses fresh ephemeral material450        let second = try HybridEnvelope.seal(payload, contentType: Self.type, to: People.bob.publicIdentity, from: People.alice)451        #expect(second.ephemeralX25519PublicKey != e.ephemeralX25519PublicKey && second.mlkemCiphertext != e.mlkemCiphertext)452        #expect(second.nonce != e.nonce && second.ciphertext != e.ciphertext)453        #expect(try second.open(with: People.bob) == payload)454455        // empty payload456        let empty = try HybridEnvelope.seal([], contentType: Self.type, to: People.bob.publicIdentity, from: People.alice)457        #expect(try empty.open(with: People.bob) == [])458    }459460    @Test func wrongRecipientAndWrongSender() throws {461        let e = Self.envelope462        #expect(throws: IdentityError.wrongRecipient) { _ = try e.open(with: People.carol) }463        #expect(throws: IdentityError.wrongRecipient) { _ = try e.open(with: People.alice) }464        #expect(throws: IdentityError.unexpectedSender) { _ = try e.open(with: People.bob, expectedSender: People.carol.publicIdentity) }465        #expect(throws: IdentityError.malformed) { _ = try e.open(with: People.bob, expectedContentType: "qyvora/other") }466        // relabelling the envelope for Carol breaks the signature, and Carol's keys could not decrypt anyway467        let relabelled = rebuilt(e, recipient: People.carol.fingerprint)468        #expect(throws: IdentityError.invalidSignature) { _ = try relabelled.open(with: People.carol) }469        #expect(throws: IdentityError.decryptionFailed) { _ = try relabelled.decrypt(with: People.carol) }470        #expect(throws: IdentityError.malformed) { _ = try HybridEnvelope.seal(payload, contentType: "Bad Type", to: People.bob.publicIdentity, from: People.alice) }471    }472473    @Test func tamperingWithEachComponent() throws {474        let e = Self.envelope475        let bob = People.bob476        let cases: [(String, HybridEnvelope)] = [477            ("X25519 ephemeral key", rebuilt(e, ephemeral: flipped(e.ephemeralX25519PublicKey, 7))),478            ("ML-KEM ciphertext, first byte", rebuilt(e, kem: flipped(e.mlkemCiphertext, 0))),479            ("ML-KEM ciphertext, last byte", rebuilt(e, kem: flipped(e.mlkemCiphertext, 1567))),480            ("payload ciphertext", rebuilt(e, ciphertext: flipped(e.ciphertext, 3))),481            ("payload tag", rebuilt(e, ciphertext: flipped(e.ciphertext, e.ciphertext.count - 1))),482            ("nonce", rebuilt(e, nonce: flipped(e.nonce, 0))),483            ("content type", rebuilt(e, contentType: "qyvora/test-v2")),484        ]485        for (label, tampered) in cases {486            // the signature catches it first…487            #expect(throws: IdentityError.invalidSignature, "\(label)") { _ = try tampered.open(with: bob) }488            // …and without the signature the key schedule or the AEAD still refuses489            #expect(throws: IdentityError.decryptionFailed, "\(label)") { _ = try tampered.decrypt(with: bob) }490        }491492        // the signature itself493        let badSignature = IdentitySignature(494            signerFingerprint: e.signature.signerFingerprint, purpose: .envelope, mldsaSignature: flipped(e.signature.mldsaSignature, 50), slhdsaSignature: nil)495        #expect(throws: IdentityError.invalidSignature) { _ = try rebuilt(e, signature: badSignature).open(with: bob) }496        // a valid signature over something else497        let unrelated = try People.alice.sign(payload, purpose: .envelope)498        #expect(throws: IdentityError.invalidSignature) { _ = try rebuilt(e, signature: unrelated).open(with: bob) }499        let wrongPurpose = try People.alice.sign(e.signedBytes(), purpose: .message)500        #expect(throws: IdentityError.invalidSignature) { _ = try rebuilt(e, signature: wrongPurpose).open(with: bob) }501    }502503    @Test func anInterceptedEnvelopeCannotBeReattributed() throws {504        // Mallory replaces the sender and signs the envelope herself: the signature is valid, but the payload key505        // is bound to the original sender, so nothing decrypts under her name.506        let e = Self.envelope507        var stolen = rebuilt(e, sender: People.mallory.publicIdentity)508        stolen = rebuilt(stolen, signature: try People.mallory.sign(stolen.signedBytes(), purpose: .envelope))509        #expect(stolen.verifySignature())510        #expect(throws: IdentityError.decryptionFailed) { _ = try stolen.open(with: People.bob) }511        #expect(throws: IdentityError.unexpectedSender) { _ = try stolen.open(with: People.bob, expectedSender: People.alice.publicIdentity) }512    }513514    @Test func bothSharedSecretsEnterTheKey() {515        let r = People.bob.publicIdentity516        let x = Bytes(repeating: 1, count: 32), k = Bytes(repeating: 2, count: 32), fp = People.alice.fingerprint517        let eph = Bytes(repeating: 3, count: 32), ct = Bytes(repeating: 4, count: 1568)518        let base = HybridEnvelope.payloadKey(x25519Secret: x, mlkemSecret: k, senderFingerprint: fp, recipient: r, ephemeral: eph, mlkemCiphertext: ct, contentType: "a")519        let variants = [520            HybridEnvelope.payloadKey(x25519Secret: flipped(x, 0), mlkemSecret: k, senderFingerprint: fp, recipient: r, ephemeral: eph, mlkemCiphertext: ct, contentType: "a"),521            HybridEnvelope.payloadKey(x25519Secret: x, mlkemSecret: flipped(k, 31), senderFingerprint: fp, recipient: r, ephemeral: eph, mlkemCiphertext: ct, contentType: "a"),522            HybridEnvelope.payloadKey(x25519Secret: x, mlkemSecret: k, senderFingerprint: flipped(fp, 0), recipient: r, ephemeral: eph, mlkemCiphertext: ct, contentType: "a"),523            HybridEnvelope.payloadKey(x25519Secret: x, mlkemSecret: k, senderFingerprint: fp, recipient: People.carol.publicIdentity, ephemeral: eph, mlkemCiphertext: ct, contentType: "a"),524            HybridEnvelope.payloadKey(x25519Secret: x, mlkemSecret: k, senderFingerprint: fp, recipient: r, ephemeral: flipped(eph, 5), mlkemCiphertext: ct, contentType: "a"),525            HybridEnvelope.payloadKey(x25519Secret: x, mlkemSecret: k, senderFingerprint: fp, recipient: r, ephemeral: eph, mlkemCiphertext: flipped(ct, 9), contentType: "a"),526            HybridEnvelope.payloadKey(x25519Secret: x, mlkemSecret: k, senderFingerprint: fp, recipient: r, ephemeral: eph, mlkemCiphertext: ct, contentType: "b"),527        ]528        #expect(base.count == 32)529        #expect(Set(variants + [base]).count == 8)530531        // independent recomputation of the documented schedule with CryptoKit532        let label = Bytes("QYVORA-ENVELOPE-v1".utf8)533        let ikm = x + k + label + fp + r.fingerprint + r.x25519PublicKey + r.mlkemPublicKey + eph + ct534        let expected = CryptoKit.HKDF<CryptoKit.SHA256>.deriveKey(535            inputKeyMaterial: SymmetricKey(data: ikm), salt: label, info: Bytes("payload-key/a".utf8), outputByteCount: 32)536        #expect(expected.withUnsafeBytes { Bytes($0) } == base)537    }538539    @Test func corruptedEncodingsNeverOpen() throws {540        let encoded = Self.envelope.encoded()541        var offsets = Array(stride(from: 0, to: encoded.count, by: 61))542        offsets += [4, 5, 6, encoded.count - 1, encoded.count - 4627, encoded.count - 4700]543        for i in offsets {544            var bad = encoded545            bad[i] ^= UInt8(1) << UInt8(i % 8)546            do {547                let parsed = try HybridEnvelope(encoded: bad)548                _ = try parsed.open(with: People.bob, expectedSender: People.alice.publicIdentity)549                Issue.record("corruption at offset \(i) was accepted")550            } catch {551                // typed IdentityError: the corruption was refused552            }553        }554        for cut in [0, 3, 5, 100, encoded.count / 2, encoded.count - 1] {555            #expect(throws: IdentityError.self) { _ = try HybridEnvelope(encoded: Bytes(encoded[0..<cut])) }556        }557        #expect(throws: IdentityError.malformed) { _ = try HybridEnvelope(encoded: encoded + [0]) }558    }559560    @Test func dualSignedEnvelope() throws {561        let e = try HybridEnvelope.seal(payload, contentType: Self.type, to: People.carol.publicIdentity, from: People.bob, dualSignature: true)562        #expect(e.signature.isDual && e.verifySignature(requireDual: true))563        let decoded = try HybridEnvelope(encoded: e.encoded())564        #expect(try decoded.open(with: People.carol, expectedSender: People.bob.publicIdentity) == payload)565    }566}567568@Suite struct DetachedSigningAndTransferTests {569    @Test func identityAsDetachedSigner() throws {570        let alice = People.alice571        let message = SystemRandom.bytes(500)572        let signer: any DetachedSigner = IdentityDetachedSigner(alice)573        let verifier: any DetachedVerifier = IdentityDetachedVerifier()574        #expect(signer.signerEncoding == alice.publicIdentity.encoded())575        #expect(verifier.signerFingerprint(of: signer.signerEncoding) == alice.fingerprint)576        #expect(verifier.signerFingerprint(of: [1, 2, 3]) == nil)577578        let signature = try signer.detachedSignature(over: message, purpose: "backup")579        #expect(try IdentitySignature(encoded: signature).purpose == .backup)580        #expect(verifier.isValid(signature: signature, over: message, signerEncoding: signer.signerEncoding, purpose: "backup"))581        #expect(!verifier.isValid(signature: signature, over: message + [0], signerEncoding: signer.signerEncoding, purpose: "backup"))582        #expect(!verifier.isValid(signature: signature, over: message, signerEncoding: signer.signerEncoding, purpose: "message"))583        #expect(!verifier.isValid(signature: signature, over: message, signerEncoding: People.bob.publicIdentity.encoded(), purpose: "backup"))584        #expect(!verifier.isValid(signature: signature, over: message, signerEncoding: [], purpose: "backup"))585        #expect(!verifier.isValid(signature: Bytes(signature.dropLast()), over: message, signerEncoding: signer.signerEncoding, purpose: "backup"))586        #expect(!verifier.isValid(signature: [], over: message, signerEncoding: signer.signerEncoding, purpose: "backup"))587        #expect(!verifier.isValid(signature: signature, over: message, signerEncoding: signer.signerEncoding, purpose: "Not A Purpose"))588        #expect(throws: IdentityError.invalidPurpose) { _ = try signer.detachedSignature(over: message, purpose: "Not A Purpose") }589590        // a verifier that demands the SLH-DSA half591        let strict = IdentityDetachedVerifier(requireDual: true)592        #expect(!strict.isValid(signature: signature, over: message, signerEncoding: signer.signerEncoding, purpose: "backup"))593        let dual = try IdentityDetachedSigner(alice, dual: true).detachedSignature(over: message, purpose: "backup")594        #expect(strict.isValid(signature: dual, over: message, signerEncoding: signer.signerEncoding, purpose: "backup"))595        #expect(verifier.isValid(signature: dual, over: message, signerEncoding: signer.signerEncoding, purpose: "backup"))596    }597598    @Test func transferPackageRoundTrip() throws {599        let oldPhone = People.alice, newPhone = People.bob600        let backup = SystemRandom.bytes(3000)601        // the new phone shows its public identity; the old phone reads the text form602        let scanned = try PublicIdentity(text: newPhone.publicIdentity.text)603        let package = try TransferPackage.create(backup: backup, to: scanned, from: oldPhone)604        let opened = try TransferPackage.open(package, receiver: newPhone)605        #expect(opened.backup == backup)606        #expect(opened.sender == oldPhone.publicIdentity)607        #expect(try TransferPackage.open(package, receiver: newPhone, expectedSender: oldPhone.publicIdentity).backup == backup)608609        #expect(throws: IdentityError.unexpectedSender) { _ = try TransferPackage.open(package, receiver: newPhone, expectedSender: People.carol.publicIdentity) }610        #expect(throws: IdentityError.wrongRecipient) { _ = try TransferPackage.open(package, receiver: People.carol) }611        #expect(throws: IdentityError.malformed) { _ = try TransferPackage.open(Bytes(package.dropLast()), receiver: newPhone) }612        var bad = package613        bad[package.count - 4700 - 1000] ^= 1  // inside the encrypted payload614        #expect(throws: IdentityError.invalidSignature) { _ = try TransferPackage.open(bad, receiver: newPhone) }615616        // an envelope of another kind is not a transfer package617        let other = try HybridEnvelope.seal(backup, contentType: "qyvora/other-v1", to: newPhone.publicIdentity, from: oldPhone).encoded()618        #expect(throws: IdentityError.malformed) { _ = try TransferPackage.open(other, receiver: newPhone) }619    }620}621
Files main
Menu

Theme