SPB Git

Repository Public

AuditSupport.swift 13.3 KB 306 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : security/tests/Sources/AuditSupport/AuditSupport.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 Foundation42import QyvoraMath4344// Shared support of the audit tests: where the repository is, a result recorder that the45// orchestrator reads, a seeded deterministic generator for reproducible random cases, vector46// loading (gzip + JSON) and helpers to call the external oracles.4748public enum AuditPaths {49    /// Repository root, derived from this file's location (security/tests/Sources/AuditSupport/…).50    public static let repo: URL = {51        if let env = ProcessInfo.processInfo.environment["QY_AUDIT_REPO"] { return URL(fileURLWithPath: env) }52        var u = URL(fileURLWithPath: #filePath)53        for _ in 0..<5 { u.deleteLastPathComponent() }54        return u55    }()5657    public static var security: URL { repo.appendingPathComponent("security") }58    public static var vectors: URL { security.appendingPathComponent("vectors") }59    public static var fuzzing: URL { security.appendingPathComponent("fuzzing") }6061    /// Directory receiving the machine-readable records of a run (`QY_AUDIT_OUT`, else a scratch directory).62    public static let out: URL = {63        let env = ProcessInfo.processInfo.environment["QY_AUDIT_OUT"]64        let u = env.map { URL(fileURLWithPath: $0) } ?? URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("qy-audit-out")65        try? FileManager.default.createDirectory(at: u, withIntermediateDirectories: true)66        return u67    }()6869    /// Engine vector directory of a root test target, e.g. `engineVectors("QyvoraMLKEM")`.70    public static func engineVectors(_ module: String) -> URL {71        repo.appendingPathComponent("Tests/\(module)Tests/Vectors")72    }73}7475/// `full` when the orchestrator runs with `--full` (QY_AUDIT_MODE=full); the quick mode uses smaller case counts.76public enum AuditMode {77    public static let isFull = ProcessInfo.processInfo.environment["QY_AUDIT_MODE"] == "full"78    /// Number of random cases: `quick` in quick mode, `full` in full mode; QY_AUDIT_SCALE multiplies both.79    public static func cases(quick: Int, full: Int) -> Int {80        let scale = Double(ProcessInfo.processInfo.environment["QY_AUDIT_SCALE"] ?? "") ?? 1.081        return max(1, Int(Double(isFull ? full : quick) * scale))82    }83}8485/// Appends one JSON line per executed check to `$QY_AUDIT_OUT/records.jsonl`.86/// The orchestrator sums these lines: every count in the reports comes from here.87public enum AuditRecorder {88    private static let lock = NSLock()89    private static let url = AuditPaths.out.appendingPathComponent("records.jsonl")9091    /// - Parameters:92    ///   - area: conformance | wycheproof | differential | property | fuzz | timing | hygiene93    ///   - name: short stable identifier of the check94    ///   - cases: number of cases executed; `failed`: number that did not match95    ///   - seed: seed of the random generator when the cases are random (logged for reproduction)96    public static func record(97        area: String, name: String, algorithm: String = "", parameterSet: String = "", oracle: String = "",98        cases: Int, failed: Int, skipped: Int = 0, seed: UInt64? = nil, note: String = ""99    ) {100        var obj: [String: Any] = [101            "area": area, "name": name, "algorithm": algorithm, "parameter_set": parameterSet,102            "oracle": oracle, "cases": cases, "passed": cases - failed, "failed": failed,103            "skipped": skipped, "note": note,104        ]105        if let seed { obj["seed"] = String(seed) }106        guard let data = try? JSONSerialization.data(withJSONObject: obj, options: [.sortedKeys]) else { return }107        lock.lock()108        defer { lock.unlock() }109        if !FileManager.default.fileExists(atPath: url.path) { FileManager.default.createFile(atPath: url.path, contents: nil) }110        if let h = try? FileHandle(forWritingTo: url) {111            _ = try? h.seekToEnd()112            try? h.write(contentsOf: data + Data([0x0a]))113            try? h.close()114        }115    }116117    /// A check that could not run (missing optional oracle or vector file): recorded, never counted as passed.118    public static func notRun(area: String, name: String, reason: String) {119        record(area: area, name: name, cases: 0, failed: 0, skipped: 1, note: "NOT RUN: " + reason)120    }121}122123/// Seed of a random campaign, drawn from the system and logged with the result.124/// Reproduction: `QY_AUDIT_REPLAY_SEED=<seed of the record>` together with `--filter <test>` replays one campaign125/// exactly (the value is used as is); `QY_AUDIT_SEED=<n>` makes a whole run deterministic (each campaign derives126/// its own seed from n and its label).127public enum AuditSeed {128    public static func make(_ label: String) -> UInt64 {129        if let s = ProcessInfo.processInfo.environment["QY_AUDIT_REPLAY_SEED"], let v = UInt64(s) { return v }130        if let s = ProcessInfo.processInfo.environment["QY_AUDIT_SEED"], let v = UInt64(s) {131            return v &+ fnv(label)132        }133        var g = SystemRandomNumberGenerator()  // test environment only: picks a seed, which is then logged134        return g.next()135    }136137    private static func fnv(_ s: String) -> UInt64 {138        var h: UInt64 = 0xcbf2_9ce4_8422_2325139        for b in s.utf8 { h = (h ^ UInt64(b)) &* 0x100_0000_01b3 }140        return h141    }142}143144/// xoshiro256** seeded through SplitMix64: deterministic test-case generator (never a key source).145public struct AuditRNG: RandomNumberGenerator, Sendable {146    private var s: (UInt64, UInt64, UInt64, UInt64)147    public let seed: UInt64148149    public init(seed: UInt64) {150        self.seed = seed151        var z = seed152        func split(_ z: inout UInt64) -> UInt64 {153            z &+= 0x9e37_79b9_7f4a_7c15154            var x = z155            x = (x ^ (x >> 30)) &* 0xbf58_476d_1ce4_e5b9156            x = (x ^ (x >> 27)) &* 0x94d0_49bb_1331_11eb157            return x ^ (x >> 31)158        }159        s = (split(&z), split(&z), split(&z), split(&z))160    }161162    public mutating func next() -> UInt64 {163        let result = ((s.1 &* 5) << 7 | (s.1 &* 5) >> 57) &* 9164        let t = s.1 << 17165        s.2 ^= s.0166        s.3 ^= s.1167        s.1 ^= s.2168        s.0 ^= s.3169        s.2 ^= t170        s.3 = (s.3 << 45) | (s.3 >> 19)171        return result172    }173174    public mutating func bytes(_ count: Int) -> Bytes {175        var out = Bytes()176        out.reserveCapacity(count)177        while out.count < count {178            var v = next()179            for _ in 0..<8 where out.count < count {180                out.append(UInt8(truncatingIfNeeded: v))181                v >>= 8182            }183        }184        return out185    }186187    public mutating func int(_ range: ClosedRange<Int>) -> Int { Int.random(in: range, using: &self) }188    public mutating func bool() -> Bool { next() & 1 == 1 }189    public mutating func pick<T>(_ a: [T]) -> T { a[int(0...(a.count - 1))] }190}191192public enum AuditVectors {193    public struct LoadError: Error, CustomStringConvertible {194        public let description: String195        public init(_ d: String) { description = d }196    }197198    /// RFC 1952 gzip container around a DEFLATE stream handed to Foundation.199    public static func gunzip(_ data: Data) throws -> Data {200        let b = [UInt8](data)201        guard b.count > 18, b[0] == 0x1f, b[1] == 0x8b, b[2] == 8 else { throw LoadError("not a gzip file") }202        let flags = b[3]203        var i = 10204        if flags & 0x04 != 0 { i += 2 + Int(b[i]) + Int(b[i + 1]) << 8 }205        if flags & 0x08 != 0 {206            while b[i] != 0 { i += 1 }207            i += 1208        }209        if flags & 0x10 != 0 {210            while b[i] != 0 { i += 1 }211            i += 1212        }213        if flags & 0x02 != 0 { i += 2 }214        return try (Data(b[i..<(b.count - 8)]) as NSData).decompressed(using: .zlib) as Data215    }216217    /// Parses a `.json` or `.json.gz` file.218    public static func json(_ url: URL) throws -> Any {219        var data = try Data(contentsOf: url)220        if url.pathExtension == "gz" { data = try gunzip(data) }221        return try JSONSerialization.jsonObject(with: data)222    }223224    /// `testGroups` of an ACVP internalProjection file.225    public static func acvpGroups(_ url: URL) throws -> [[String: Any]] {226        guard let root = try json(url) as? [String: Any], let g = root["testGroups"] as? [[String: Any]] else {227            throw LoadError("unexpected JSON layout in \(url.lastPathComponent)")228        }229        return g230    }231}232233extension Dictionary where Key == String, Value == Any {234    public func hex(_ key: String) -> Bytes? {235        guard let s = self[key] as? String else { return nil }236        return Hex.decode(s)237    }238    public func str(_ key: String) -> String { self[key] as? String ?? "" }239    public func flag(_ key: String) -> Bool { self[key] as? Bool ?? false }240    public func integer(_ key: String) -> Int? { self[key] as? Int }241    public var acvpTests: [[String: Any]] { self["tests"] as? [[String: Any]] ?? [] }242}243244/// External oracles (test environment only).245public enum Oracle {246    /// Python of the audit virtual environment (`security/.tools/venv`), created by `security/audit/install-tools.sh`.247    public static var python: URL? {248        let u = AuditPaths.security.appendingPathComponent(".tools/venv/bin/python3")249        return FileManager.default.isExecutableFile(atPath: u.path) ? u : nil250    }251252    /// The `spbqc` command-line tool of the owner's Rust library spb-quantum-crypto (`QY_SPBQC`, else the audit copy).253    public static var spbqc: URL? {254        let candidates = [255            ProcessInfo.processInfo.environment["QY_SPBQC"],256            AuditPaths.security.appendingPathComponent(".tools/bin/spbqc").path,257        ].compactMap { $0 }258        return candidates.first { FileManager.default.isExecutableFile(atPath: $0) }.map { URL(fileURLWithPath: $0) }259    }260261    public struct Failure: Error, CustomStringConvertible {262        public let description: String263    }264265    /// Runs a process with `input` on stdin and returns stdout.266    public static func run(_ exe: URL, _ args: [String], input: Data = Data()) throws -> Data {267        let p = Process()268        p.executableURL = exe269        p.arguments = args270        let inPipe = Pipe(), outPipe = Pipe(), errPipe = Pipe()271        p.standardInput = inPipe272        p.standardOutput = outPipe273        p.standardError = errPipe274        try p.run()275        let writer = Thread { [input] in276            inPipe.fileHandleForWriting.write(input)277            try? inPipe.fileHandleForWriting.close()278        }279        writer.start()280        nonisolated(unsafe) var errData = Data()281        let errReader = Thread { errData = errPipe.fileHandleForReading.readDataToEndOfFile() }282        errReader.start()283        let out = outPipe.fileHandleForReading.readDataToEndOfFile()284        p.waitUntilExit()285        while !errReader.isFinished { usleep(1000) }286        guard p.terminationStatus == 0 else {287            throw Failure(description: "\(exe.lastPathComponent) \(args.joined(separator: " ")) exited \(p.terminationStatus): "288                + (String(data: errData.prefix(2000), encoding: .utf8) ?? ""))289        }290        return out291    }292293    /// Batch call of the Python oracle script `security/tests/oracles/oracle.py`:294    /// `cases` is a JSON array of objects, the answer is a JSON array of the same length.295    public static func pythonBatch(op: String, cases: [[String: Any]]) throws -> [[String: Any]] {296        guard let py = python else { throw Failure(description: "audit Python environment missing (run security/audit/install-tools.sh)") }297        let script = AuditPaths.security.appendingPathComponent("tests/oracles/oracle.py").path298        let input = try JSONSerialization.data(withJSONObject: cases)299        let out = try run(py, ["-I", script, op], input: input)300        guard let arr = try JSONSerialization.jsonObject(with: out) as? [[String: Any]], arr.count == cases.count else {301            throw Failure(description: "oracle \(op): malformed answer")302        }303        return arr304    }305}306
Files main
Menu

Theme