SPB Git

Repository Public

VectorTests.swift 18.3 KB 233 lines swift

1// Cross-implementation vectors: everything packages/protocol/test/vectors.test.ts asserts, plus byte-for-byte2// re-sealing of every deterministic value, plus the reverse-direction vector file written by Swift.3import CryptoKit4import XCTest5@testable import SharedVaultKit67final class VectorTests: XCTestCase {8    /// Asserts on a vector file exactly what the TypeScript test asserts (and re-seals deterministic values).9    static func verify(_ v: JSONValue, name: String) throws {10        let accountId = try v.str("ids", "accountId"), deviceId = try v.str("ids", "deviceId")11        let u = SPV1.unb64u12        let ark = try u(try v.str("secrets", "ark")), rkExpected = try v.str("secrets", "rk"), vk = try u(try v.str("secrets", "vk"))1314        // contexts and HKDF15        for c in try v.value("ctx").arrayValue ?? [] {16            let fields = try (c.value("fields").arrayValue ?? []).map { f -> String in17                guard let s = f.stringValue else { throw VaultError.invalidJSON("ctx field must be a string") }18                return s19            }20            XCTAssertEqual(SPV1.hex(try SPV1.ctx(try c.str("label"), fields: fields)), try c.str("hex"), "\(name): ctx")21        }22        XCTAssertEqual(SPV1.hex(try SPV1.ctx("record", "v", "r", "item", 3, 1)), SPV1.hex(try SPV1.ctx("record", fields: ["v", "r", "item", "3", "1"])))23        XCTAssertEqual(SPV1.b64u(SPV1.hkdf(ikm: try u(try v.str("hkdf", "ikm")), salt: try u(try v.str("hkdf", "salt")), info: try u(try v.str("hkdf", "info")))), try v.str("hkdf", "out"), "\(name): hkdf")2425        // keyset, device certificate, ARK envelope26        let keyset = KeysetBlob(nonce: try v.str("keyset", "nonce"), ct: try v.str("keyset", "ct"))27        let account = try SPV1.openKeyset(ark: ark, accountId: accountId, blob: keyset)28        XCTAssertEqual(SPV1.b64u(account.sigPub), try v.str("account", "sigPub"))29        XCTAssertEqual(SPV1.b64u(account.encPub), try v.str("account", "encPub"))30        XCTAssertEqual(try SPV1.accountFingerprint(sigPub: account.sigPub, encPub: account.encPub), try v.str("account", "fingerprint"))31        XCTAssertEqual(SPV1.b64u(account.sig.x963Representation), try v.str("account", "sigPriv"))32        XCTAssertEqual(SPV1.b64u(account.enc.x963Representation), try v.str("account", "encPriv"))33        let accountSigPub = try u(try v.str("account", "sigPub"))34        let device = try v.value("device").decode(DevicePublic.self)35        XCTAssertTrue(SPV1.verifyDeviceCert(accountSigPub: accountSigPub, accountId: accountId, device: device), "\(name): device cert")36        var wrongDevice = device37        wrongDevice.deviceId = accountId38        XCTAssertFalse(SPV1.verifyDeviceCert(accountSigPub: accountSigPub, accountId: accountId, device: wrongDevice))39        let dev = DeviceKeys(enc: try SoftwareKEMKey(x963Representation: try u(try v.str("device", "encPriv"))),40                             sig: try SoftwareSigningKey(x963Representation: try u(try v.str("device", "sigPriv"))))41        XCTAssertEqual(dev.encPub, device.encPub)42        XCTAssertEqual(dev.sigPub, device.sigPub)43        XCTAssertEqual(try SPV1.unwrapArk(device: dev, accountId: accountId, deviceId: deviceId, envelope: try v.str("device", "arkEnvelope")), ark)44        assertThrows(.authenticationFailed, try SPV1.unwrapArk(device: dev, accountId: accountId, deviceId: accountId, envelope: try v.str("device", "arkEnvelope")))4546        // deterministic: keyset re-sealed with the vector's nonce47        let keysetPt = SPV1.keysetPlaintext(account)48        XCTAssertEqual(try SPV1.sealKeysetRaw(ark: ark, accountId: accountId, plaintext: keysetPt, nonce: try u(keyset.nonce)), keyset, "\(name): keyset re-seal")4950        // recovery51        let rk = try SPV1.decodeRecoveryKey(try v.str("recovery", "text"))52        XCTAssertEqual(SPV1.b64u(rk), rkExpected)53        XCTAssertEqual(try SPV1.encodeRecoveryKey(rk), try v.str("recovery", "text"))54        XCTAssertEqual(try SPV1.recoveryAuthHash(rk: rk, accountId: accountId), try v.str("recovery", "authHash"))55        let epoch = try v.int("recovery", "epoch"), recEnv = try v.str("recovery", "envelope")56        XCTAssertEqual(try SPV1.openRecoveryEnvelope(rk: rk, accountId: accountId, epoch: epoch, envelope: recEnv), ark)57        assertThrows(.authenticationFailed, try SPV1.openRecoveryEnvelope(rk: rk, accountId: accountId, epoch: epoch + 1, envelope: recEnv))58        XCTAssertEqual(try SPV1.sealRecoveryEnvelope(rk: rk, accountId: accountId, epoch: epoch, ark: ark, nonce: Data(try u(recEnv).prefix(12))), recEnv, "\(name): recovery re-seal")5960        // record61        let ref = try v.value("record", "ref").decode(RecordRef.self)62        let envelope = try Envelope(jsonValue: try v.value("record", "envelope"))63        XCTAssertEqual(envelope, try v.value("record", "envelope").decode(Envelope.self))64        let plaintext = try v.value("record", "plaintext")65        XCTAssertEqual(try SPV1.openRecordJSON(keyFor: { _ in vk }, ref: ref, envelope: envelope), plaintext, "\(name): record")66        let raw = try SPV1.openRecordData(keyFor: { $0 == envelope.kid ? vk : nil }, ref: ref, envelope: envelope)67        XCTAssertEqual(raw, plaintext.serialized(), "\(name): raw record plaintext is JSON.stringify(plaintext), padding removed")68        XCTAssertNotEqual(raw.last, 0x20)69        let item = try SPV1.openRecord(Item.self, keyFor: { _ in vk }, ref: ref, envelope: envelope)70        XCTAssertEqual(item.title, try plaintext.str("title"))71        XCTAssertEqual(try v.int("record", "kid"), envelope.kid)72        let resealed = try SPV1.sealRecord(vk: vk, kid: envelope.kid, ref: ref, value: plaintext, salt: try u(envelope.salt), nonce: try u(envelope.nonce))73        XCTAssertEqual(resealed, envelope, "\(name): record re-seal")7475        // grant76        let grant = try v.value("grant").decode(VaultGrant.self)77        XCTAssertEqual(try SPV1.acceptVaultGrant(member: account, grant: grant, granterSigPub: accountSigPub), vk)7879        // chunk80        let chunk = try v.value("chunk")81        XCTAssertEqual(SPV1.b64u(try SPV1.openChunk(key: try u(try chunk.str("key")), prefix: try u(try chunk.str("prefix")), id: try chunk.str("id"),82                                                    index: try chunk.int("index"), total: try chunk.int("total"), data: try u(try chunk.str("sealed")))), try chunk.str("plaintext"))83        XCTAssertEqual(SPV1.b64u(try SPV1.sealChunk(key: try u(try chunk.str("key")), prefix: try u(try chunk.str("prefix")), id: try chunk.str("id"),84                                                    index: try chunk.int("index"), total: try chunk.int("total"), data: try u(try chunk.str("plaintext")))), try chunk.str("sealed"), "\(name): chunk re-seal")8586        // pairing87        let pairingId = try v.str("pairing", "pairingId"), secret = try u(try v.str("pairing", "secret"))88        XCTAssertEqual(try SPV1.pairingTag(secret: secret, pairingId: pairingId, encPub: device.encPub, sigPub: device.sigPub), try v.str("pairing", "tag"))89        XCTAssertTrue(SPV1.verifyPairingTag(secret: secret, pairingId: pairingId, encPub: device.encPub, sigPub: device.sigPub, tag: try v.str("pairing", "tag")))90        XCTAssertEqual(try SPV1.pairingSas(pairingId: pairingId, encPub: device.encPub, sigPub: device.sigPub), try v.str("pairing", "sas"))91        let decoded = try SPV1.decodePairingCode(try v.str("pairing", "code"))92        XCTAssertEqual(decoded.pairingId, pairingId)93        XCTAssertEqual(decoded.secret, secret)94        XCTAssertEqual(SPV1.encodePairingCode(pairingId: pairingId, secret: secret), try v.str("pairing", "code"))9596        // relay97        let box = try v.value("relay", "box").decode(RelayBox.self)98        XCTAssertEqual(try SPV1.openRelayJSON(recipient: account, shareId: try v.str("relay", "shareId"), senderId: accountId, recipientId: accountId, senderSigPub: accountSigPub, box: box), try v.value("relay", "plaintext"))99100        // link101        let linkSecret = try u(try v.str("link", "secret")), shareId = try v.str("link", "shareId"), linkBox = try v.str("link", "box")102        XCTAssertEqual(try SPV1.openLinkJSON(secret: linkSecret, shareId: shareId, box: linkBox), try v.value("link", "plaintext"))103        XCTAssertEqual(try SPV1.linkKeys(secret: linkSecret, shareId: shareId).authHash, try v.str("link", "authHash"))104        XCTAssertEqual(try SPV1.sealLink(secret: linkSecret, shareId: shareId, value: try v.value("link", "plaintext"), nonce: Data(try u(linkBox).prefix(12))), linkBox, "\(name): link re-seal")105106        // totp107        for t in try v.value("totp").arrayValue ?? [] {108            guard let alg = TotpAlgorithm(rawValue: try t.str("algorithm")), let atMs = t["atMs"]?.doubleValue else { throw VaultError.invalidJSON("totp vector") }109            let p = TotpParams(secret: try u(try t.str("secret")), digits: try t.int("digits"), period: try t.int("period"), algorithm: alg)110            XCTAssertEqual(try SPV1.totp(p, atMs: atMs).code, try t.str("code"), "\(name): totp \(alg.rawValue)")111        }112    }113114    func testTypeScriptVectors() throws {115        let v = try loadJSON(Paths.vectorsDir.appendingPathComponent("spv1.json"))116        XCTAssertEqual(try v.str("spec"), "SPV1")117        XCTAssertEqual(try v.str("generatedBy"), "typescript")118        try VectorTests.verify(v, name: "spv1.json")119    }120121    /// Builds a vector file with exactly the structure of spv1.json from freshly generated throwaway keys.122    static func makeSwiftVectors() throws -> JSONValue {123        let b = pattern, b64 = SPV1.b64u124        let accountId = "a1a1a1a1-1111-4111-8111-111111111111", deviceId = "b2b2b2b2-2222-4222-8222-222222222222"125        let vaultId = "c3c3c3c3-3333-4333-8333-333333333333", recordId = "d4d4d4d4-4444-4444-8444-444444444444"126        let ark = b(32, 101), rk = b(32, 102), vk = b(32, 103)127128        let account = SPV1.generateAccountKeys()129        let devEnc = SoftwareKEMKey(), devSig = SoftwareSigningKey()130        let encPub = b64(devEnc.publicKey), sigPub = b64(devSig.publicKey), createdAt = "2026-11-19T00:00:00.000Z"131        let item: JSONValue = ["type": "login", "title": "Exemple Swift — été 🔐", "fields": ["username": "alice", "password": "not-a-real-password"],132                               "urls": [["url": "https://example.com", "match": "domain"]]]133        let ref = RecordRef(vaultId: vaultId, recordId: recordId, type: .item, rev: 3)134        let grant = try SPV1.grantVaultKey(granter: account, granterAccountId: accountId, vk: vk, vaultId: vaultId, epoch: 1, memberAccountId: accountId, memberEncPub: account.encPub, role: .owner)135        let chunkId = "e5e5e5e5-5555-4555-8555-555555555555", chunkPt = SPV1.utf8("attachment body from swift")136        let att = try SPV1.sealChunk(key: b(32, 109), prefix: b(8, 110), id: chunkId, index: 0, total: 1, data: chunkPt)137        let pairSecret = b(16, 111), pairingId = "f6f6f6f6-6666-4666-8666-666666666666"138        let relayShare = "a7a7a7a7-7777-4777-8777-777777777777", relayPt: JSONValue = ["hello": "relay from swift"]139        let relay = try SPV1.sealRelay(sender: account, shareId: relayShare, senderId: accountId, recipientId: accountId, recipientEncPub: account.encPub, value: relayPt)140        let linkSecret = b(32, 112), linkShare = "b8b8b8b8-8888-4888-8888-888888888888", linkPt: JSONValue = ["hello": "link from swift"]141        let envelope = try SPV1.sealRecord(vk: vk, kid: 1, ref: ref, value: item, salt: b(32, 106), nonce: b(12, 107))142        let keyset = try SPV1.sealKeysetRaw(ark: ark, accountId: accountId, plaintext: SPV1.keysetPlaintext(account), nonce: b(12, 104))143144        func totpVector(_ secret: String, _ alg: TotpAlgorithm, _ atMs: Double) throws -> JSONValue {145            let code = try SPV1.totp(TotpParams(secret: SPV1.utf8(secret), digits: 8, period: 30, algorithm: alg), atMs: atMs).code146            return ["secret": .string(b64(SPV1.utf8(secret))), "algorithm": .string(alg.rawValue), "digits": 8, "period": 30, "atMs": .number(atMs), "code": .string(code)]147        }148149        return [150            "spec": "SPV1", "suite": 1, "generatedBy": "swift",151            "ctx": [152                ["label": "record", "fields": [.string(vaultId), .string(recordId), "item", "3", "1"], "hex": .string(SPV1.hex(try SPV1.ctx("record", vaultId, recordId, "item", 3, 1)))],153                ["label": "é", "fields": ["", "ü"], "hex": .string(SPV1.hex(try SPV1.ctx("é", "", "ü")))],154            ],155            "hkdf": ["ikm": .string(b64(ark)), "salt": "", "info": .string(b64(try SPV1.ctx("keyset-key", accountId))),156                     "out": .string(b64(SPV1.hkdf(ikm: ark, salt: Data(), info: try SPV1.ctx("keyset-key", accountId))))],157            "ids": ["accountId": .string(accountId), "deviceId": .string(deviceId), "vaultId": .string(vaultId), "recordId": .string(recordId)],158            "secrets": ["ark": .string(b64(ark)), "rk": .string(b64(rk)), "vk": .string(b64(vk))],159            "account": ["sigPriv": .string(b64(account.sig.x963Representation)), "encPriv": .string(b64(account.enc.x963Representation)),160                        "sigPub": .string(b64(account.sigPub)), "encPub": .string(b64(account.encPub)),161                        "fingerprint": .string(try SPV1.accountFingerprint(sigPub: account.sigPub, encPub: account.encPub))],162            "keyset": ["nonce": .string(keyset.nonce), "ct": .string(keyset.ct)],163            "device": ["deviceId": .string(deviceId), "encPub": .string(encPub), "sigPub": .string(sigPub), "createdAt": .string(createdAt),164                       "encPriv": .string(b64(devEnc.x963Representation)), "sigPriv": .string(b64(devSig.x963Representation)),165                       "cert": .string(try SPV1.signDeviceCert(account: account, accountId: accountId, deviceId: deviceId, encPub: encPub, sigPub: sigPub, createdAt: createdAt)),166                       "arkEnvelope": .string(try SPV1.wrapArkForDevice(ark: ark, accountId: accountId, deviceId: deviceId, devEncPub: devEnc.publicKey))],167            "recovery": ["text": .string(try SPV1.encodeRecoveryKey(rk)), "epoch": 1, "authHash": .string(try SPV1.recoveryAuthHash(rk: rk, accountId: accountId)),168                         "envelope": .string(try SPV1.sealRecoveryEnvelope(rk: rk, accountId: accountId, epoch: 1, ark: ark, nonce: b(12, 105)))],169            "record": ["ref": ["vaultId": .string(vaultId), "recordId": .string(recordId), "type": "item", "rev": 3], "kid": 1, "plaintext": item, "envelope": envelope.jsonValue],170            "grant": ["vaultId": .string(grant.vaultId), "epoch": .number(Double(grant.epoch)), "memberAccountId": .string(grant.memberAccountId), "role": .string(grant.role.rawValue),171                      "envelope": .string(grant.envelope), "granterAccountId": .string(grant.granterAccountId), "sig": .string(grant.sig)],172            "chunk": ["key": .string(b64(b(32, 109))), "prefix": .string(b64(b(8, 110))), "id": .string(chunkId), "index": 0, "total": 1,173                      "plaintext": .string(b64(chunkPt)), "sealed": .string(b64(att))],174            "pairing": ["pairingId": .string(pairingId), "secret": .string(b64(pairSecret)),175                        "tag": .string(try SPV1.pairingTag(secret: pairSecret, pairingId: pairingId, encPub: encPub, sigPub: sigPub)),176                        "sas": .string(try SPV1.pairingSas(pairingId: pairingId, encPub: encPub, sigPub: sigPub)),177                        "code": .string(SPV1.encodePairingCode(pairingId: pairingId, secret: pairSecret))],178            "relay": ["shareId": .string(relayShare), "box": ["ct": .string(relay.ct), "sig": .string(relay.sig)], "plaintext": relayPt],179            "link": ["secret": .string(b64(linkSecret)), "shareId": .string(linkShare), "authHash": .string(try SPV1.linkKeys(secret: linkSecret, shareId: linkShare).authHash),180                     "box": .string(try SPV1.sealLink(secret: linkSecret, shareId: linkShare, value: linkPt, nonce: b(12, 113))), "plaintext": linkPt],181            "totp": [ // RFC 6238 appendix B, codes computed by Swift182                try totpVector("12345678901234567890", .sha1, 59000),183                try totpVector("12345678901234567890123456789012", .sha256, 1_111_111_109_000),184                try totpVector("1234567890123456789012345678901234567890123456789012345678901234", .sha512, 20_000_000_000_000),185            ],186        ]187    }188189    /// Structure check: the Swift vector file has exactly the same keys (recursively) as spv1.json.190    static func shape(_ v: JSONValue) -> String {191        switch v {192        case .null: return "null"193        case .bool: return "bool"194        case .number: return "number"195        case .string: return "string"196        case .array(let a): return "[" + (a.first.map(shape) ?? "") + "]"197        case .object(let o): return "{" + o.pairs.map { "\($0.key):\(shape($0.value))" }.joined(separator: ",") + "}"198        }199    }200201    /// Generates Swift vectors, verifies them in Swift, checks they have the structure of spv1.json and, when202    /// SPV_WRITE_VECTORS=1, writes packages/crypto-test-vectors/spv1-swift.json for the TypeScript test to verify.203    func testSwiftVectorsRoundTripAndWrite() throws {204        let v = try VectorTests.makeSwiftVectors()205        let text = v.serializedString(indent: 1) + "\n"206        let reparsed = try JSONValue.parse(text)207        XCTAssertEqual(reparsed, v)208        try VectorTests.verify(reparsed, name: "swift (in memory)")209        let ts = try loadJSON(Paths.vectorsDir.appendingPathComponent("spv1.json"))210        func strip(_ x: JSONValue) -> JSONValue { // record.plaintext is free-form211            guard var o = x.objectValue, var rec = o["record"]?.objectValue else { return x }212            rec["plaintext"] = .null; o["record"] = .object(rec); return .object(o)213        }214        XCTAssertEqual(VectorTests.shape(strip(reparsed)), VectorTests.shape(strip(ts)), "spv1-swift.json must have exactly the structure (and key order) of spv1.json")215        XCTAssertEqual(try v.str("totp", "0", "code"), "94287082")216217        if ProcessInfo.processInfo.environment["SPV_WRITE_VECTORS"] == "1" {218            let url = Paths.vectorsDir.appendingPathComponent("spv1-swift.json")219            try Data(text.utf8).write(to: url, options: .atomic)220            print("spv1-swift.json written to \(url.path)")221        }222    }223224    /// If a Swift vector file is already on disk, it must verify too.225    func testSwiftVectorFileOnDisk() throws {226        let url = Paths.vectorsDir.appendingPathComponent("spv1-swift.json")227        guard FileManager.default.fileExists(atPath: url.path) else { throw XCTSkip("spv1-swift.json not generated yet (run with SPV_WRITE_VECTORS=1)") }228        let v = try loadJSON(url)229        XCTAssertEqual(try v.str("generatedBy"), "swift")230        try VectorTests.verify(v, name: "spv1-swift.json")231    }232}233
Files main
Menu

Theme