SPB Git

Repository Public

ParityTests.swift 11.4 KB 202 lines swift

1// Replays Fixtures/parity.json (generated by Tests/Tools/generate-parity.ts from the TypeScript reference) and2// requires identical results from Swift for every non-cryptographic module.3import XCTest4@testable import SharedVaultKit56final class ParityTests: XCTestCase {7    static let fixture: JSONValue? = try? loadJSON(Paths.fixtures.appendingPathComponent("parity.json"))8    func section(_ name: String) throws -> [JSONValue] { try XCTUnwrap(try XCTUnwrap(ParityTests.fixture)[name]?.arrayValue, "missing \(name)") }9    func isError(_ v: JSONValue?) -> Bool { v?["error"] == .bool(true) }1011    func originJSON(_ o: Origin?) -> JSONValue {12        guard let o else { return .null }13        return ["scheme": .string(o.scheme), "host": .string(o.host), "port": .string(o.port), "domain": o.domain.map { .string($0) } ?? .null,14                "display": .string(o.display), "mixedScript": .bool(o.mixedScript)]15    }1617    func testParseOrigin() throws {18        var failures = 019        for c in try section("origins") {20            let input = try c.str("input")21            let expected: JSONValue = isError(c["out"]) ? .null : (c["out"] ?? .null)22            let got = originJSON(SPV1.parseOrigin(input))23            if got != expected { failures += 1; XCTFail("parseOrigin(\(input.debugDescription)): swift \(got.serializedString()) ts \(expected.serializedString())") }24        }25        XCTAssertEqual(failures, 0)26    }2728    func testMatchUrl() throws {29        let cases = try section("match")30        XCTAssertGreaterThan(cases.count, 1000)31        for c in cases {32            let saved = ItemUrl(url: try c.str("saved", "url"), match: try XCTUnwrap(UrlMatch(rawValue: try c.str("saved", "match"))))33            let page = try c.str("page")34            let expected = isError(c["out"]) ? "no" : try c.str("out")35            XCTAssertEqual(SPV1.matchUrl(saved: saved, pageUrl: page).rawValue, expected, "matchUrl(\(saved.url) [\(saved.match.rawValue)], \(page))")36        }37    }3839    func testSkeletonAndLookalike() throws {40        for c in try section("skeleton") { XCTAssertEqual(SPV1.skeleton(try c.str("input")), try c.str("out"), c.text("input")) }41        for c in try section("lookalike") {42            let saved = (c["saved"]?.arrayValue ?? []).compactMap(\.stringValue)43            let got = SPV1.lookalike(pageUrl: try c.str("page"), savedDomains: saved)44            let gotJSON: JSONValue = got.map { ["page": .string($0.page), "resembles": .string($0.resembles), "reason": .string($0.reason.rawValue)] } ?? .null45            XCTAssertEqual(gotJSON, c["out"] ?? .null, c.text("page"))46        }47    }4849    func testEstimateBitsAndBreach() throws {50        for c in try section("estimateBits") { XCTAssertEqual(SPV1.estimateBits(try c.str("pw")), try c.int("bits"), c.text("pw")) }51        for c in try section("breach") {52            let b = SPV1.breachPrefix(try c.str("pw"))53            XCTAssertEqual(b.prefix, try c.str("prefix")); XCTAssertEqual(b.suffix, try c.str("suffix"))54        }55        let b = SPV1.breachPrefix("password")56        XCTAssertEqual(b.prefix + b.suffix, "5BAA61E4C9B93F3F0682250B6CF8331B7EE68FD8")57        XCTAssertEqual(SPV1.breachCount(rangeBody: "0018A45C4D1DEF81644B54AB7F969B88D65:1\r\n\(b.suffix):9545824\r\nFFFF:3", suffix: b.suffix), 9_545_824)58        XCTAssertEqual(SPV1.breachCount(rangeBody: "AAAA:1\nBBBB:2\n", suffix: "CCCC"), 0)59        XCTAssertEqual(SPV1.breachCount(rangeBody: "AAAA:x\nBBBB\n", suffix: "AAAA"), 0)60        for c in try section("pad") { XCTAssertEqual(try SPV1.pad(Data(repeating: 0x78, count: try c.int("n"))).count, try c.int("len")) }61    }6263    func testGeneratorDeterministicParity() throws {64        let fx = try XCTUnwrap(ParityTests.fixture)65        let rnd = XorShift(seed: UInt32(try fx.int("uniform", "seed")))66        let ns = try fx.value("uniform", "n").arrayValue ?? [], outs = try fx.value("uniform", "out").arrayValue ?? []67        for (n, expected) in zip(ns, outs) {68            let got = try (0..<20).map { _ in try SPV1.uniform(try XCTUnwrap(n.intValue), rnd: rnd.bytes) }69            XCTAssertEqual(got, (expected.arrayValue ?? []).compactMap(\.intValue), "uniform(\(n.intValue ?? -1))")70        }71        for c in try section("passwords") {72            let o = try c.value("options").decode(PasswordOptions.self)73            XCTAssertEqual(try SPV1.generatePassword(o, rnd: XorShift(seed: UInt32(try c.int("seed"))).bytes), try c.str("out"))74            XCTAssertEqual(SPV1.passwordEntropyBits(o), try XCTUnwrap(c["bits"]?.doubleValue), accuracy: 1e-9)75        }76        for c in try section("passphrases") {77            let o = try c.value("options").decode(PassphraseOptions.self)78            XCTAssertEqual(try SPV1.generatePassphrase(o, rnd: XorShift(seed: UInt32(try c.int("seed"))).bytes), try c.str("out"))79            XCTAssertEqual(SPV1.passphraseEntropyBits(o), try XCTUnwrap(c["bits"]?.doubleValue), accuracy: 1e-9)80        }81    }8283    func testNormalizeItem() throws {84        for c in try section("normalize") {85            let item = try SPV1.normalizeItem(try c.value("input"))86            XCTAssertEqual(item.jsonValue, try c.value("out"), "normalizeItem(\(c.text("input").prefix(80)))")87            // the three decoding paths agree88            XCTAssertEqual(try Item(json: try c.value("input").serialized()), item)89            XCTAssertEqual(try JSONDecoder().decode(Item.self, from: try c.value("input").serialized()), item)90            // idempotent, and Codable round trip91            XCTAssertEqual(item.normalized(), item)92            XCTAssertEqual(try JSONDecoder().decode(Item.self, from: try JSONEncoder().encode(item)), item)93        }94    }9596    func testTemplates() throws {97        let cases = try section("primarySecret")98        XCTAssertEqual(cases.count, ItemType.allCases.count)99        for c in cases {100            let type = try XCTUnwrap(ItemType(rawValue: try c.str("type")))101            let t = try XCTUnwrap(TEMPLATES[type])102            XCTAssertEqual(t.label, try c.str("template", "label"))103            XCTAssertEqual(t.section.rawValue, try c.str("template", "section"))104            let fields = try c.value("template", "fields").arrayValue ?? []105            XCTAssertEqual(t.fields.count, fields.count)106            for (f, e) in zip(t.fields, fields) {107                XCTAssertEqual(f.key, try e.str("key")); XCTAssertEqual(f.label, try e.str("label")); XCTAssertEqual(f.kind.rawValue, try e.str("kind"))108            }109        }110    }111112    func testCsvParsing() throws {113        for c in try section("csv") {114            let rows = try SPV1.parseCsv(try c.str("text"))115            let expected = (c["rows"]?.arrayValue ?? []).map { ($0.arrayValue ?? []).compactMap(\.stringValue) }116            XCTAssertEqual(rows, expected, c.text("text").debugDescription)117        }118        XCTAssertTrue(isError(try XCTUnwrap(ParityTests.fixture)["csvError"]))119        XCTAssertThrowsError(try SPV1.parseCsv("a,\"unterminated"))120    }121122    func importJSON(_ r: ImportResult) -> JSONValue {123        ["format": .string(r.format.rawValue), "items": .array(r.items.map { i in var x = i; x.createdAt = ""; x.updatedAt = ""; return x.jsonValue }),124         "skipped": .number(Double(r.skipped)), "warnings": .array(r.warnings.map { .string($0) })]125    }126127    func testImports() throws {128        for c in try section("imports") {129            let text = try c.str("text")130            if isError(c["out"]) { XCTAssertThrowsError(try SPV1.importCsv(text)); continue }131            XCTAssertEqual(importJSON(try SPV1.importCsv(text)), try c.value("out"), text.prefix(60).debugDescription)132            XCTAssertEqual(importJSON(try SPV1.importAny(fileName: "export.csv", text: text)), try c.value("out"))133        }134        let bw = try XCTUnwrap(ParityTests.fixture).value("bitwarden")135        XCTAssertEqual(importJSON(try SPV1.importBitwardenJson(try bw.str("text"))), try bw.value("out"))136        XCTAssertEqual(importJSON(try SPV1.importAny(fileName: "x.JSON", text: try bw.str("text"))), try bw.value("out"))137        XCTAssertEqual(importJSON(try SPV1.importAny(fileName: "noext", text: "  \n" + (try bw.str("text")))), try bw.value("out"))138    }139140    func testTotpParsing() throws {141        for c in try section("totpParse") {142            let input = try c.str("input")143            if isError(c["out"]) { XCTAssertThrowsError(try SPV1.parseTotp(input), input); continue }144            let p = try SPV1.parseTotp(input)145            let got: JSONValue = ["secret": .string(SPV1.b64u(p.secret)), "digits": .number(Double(p.digits)), "period": .number(Double(p.period)), "algorithm": .string(p.algorithm.rawValue),146                                  "issuer": p.issuer.map { .string($0) } ?? .null, "account": p.account.map { .string($0) } ?? .null]147            XCTAssertEqual(got, try c.value("out"), input)148        }149    }150151    func testRecoveryKeyDecodingParity() throws {152        for c in try section("recovery") {153            let text = try c.str("text")154            let got = (try? SPV1.decodeRecoveryKey(text)).map(SPV1.b64u)155            XCTAssertEqual(got, c["rk"]?.stringValue, text)156        }157    }158159    func findingJSON(_ f: Finding) -> JSONValue {160        switch f {161        case .weak(let id, let bits): return ["kind": "weak", "id": .string(id), "bits": .number(Double(bits))]162        case .reused(let ids): return ["kind": "reused", "ids": .array(ids.map { .string($0) })]163        case .duplicate(let ids): return ["kind": "duplicate", "ids": .array(ids.map { .string($0) })]164        case .insecureUrl(let id): return ["kind": "insecure-url", "id": .string(id)]165        case .expiring(let id, let expiresAt, let expired): return ["kind": "expiring", "id": .string(id), "expiresAt": .string(expiresAt), "expired": .bool(expired)]166        case .rotationDue(let id, let dueAt): return ["kind": "rotation-due", "id": .string(id), "dueAt": .string(dueAt)]167        case .breached(let id, let count): return ["kind": "breached", "id": .string(id), "count": .number(Double(count))]168        }169    }170171    func testAnalyze() throws {172        let a = try XCTUnwrap(ParityTests.fixture).value("analyze")173        let items = try (a["items"]?.arrayValue ?? []).map { (id: try $0.str("id"), item: try SPV1.normalizeItem(try $0.value("item"))) }174        let findings = SPV1.analyze(items, nowMs: try XCTUnwrap(a["now"]?.doubleValue))175        XCTAssertEqual(JSONValue.array(findings.map(findingJSON)).serializedString(), try a.value("out").serializedString())176        XCTAssertEqual(findings.map(\.kind), (a["out"]?.arrayValue ?? []).compactMap { $0["kind"]?.stringValue })177    }178179    func testSearch() throws {180        for c in try section("search") {181            let item = try SPV1.normalizeItem(try c.value("item"))182            let text = SPV1.searchText(item)183            XCTAssertEqual(text, try c.str("text"))184            for h in c["hits"]?.arrayValue ?? [] { XCTAssertEqual(SPV1.matchesQuery(haystack: text, query: try h.str("q")), h["hit"]?.boolValue, h.text("q")) }185        }186    }187188    func testJSONSerializationMatchesJSONStringify() throws {189        for c in try section("jsonStrings") {190            let v: JSONValue = ["k": .string(try c.str("s")), "n": [1, -2, 0, 1.5, true, nil]]191            XCTAssertEqual(v.serializedString(), try c.str("json"))192            XCTAssertEqual(try JSONValue.parse(try c.str("json")), v)193        }194    }195196    func testExportCsv() throws {197        let e = try XCTUnwrap(ParityTests.fixture).value("exportCsv")198        let items = try (e["items"]?.arrayValue ?? []).map { try SPV1.normalizeItem($0) }199        XCTAssertEqual(SPV1.exportCsv(items), try e.str("out"))200    }201}202
Files main
Menu

Theme