SPB Git

Repository Public

swift_tests.py 15.2 KB 264 lines python

1#!/usr/bin/env python32# =============================================================================3#                  SP BOUCHER | SOFTWARE & RESEARCH4#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5# =============================================================================6#7# Project          : QYVORA8# File             : security/audit/runners/swift_tests.py9# Module           : Security10# Repository       : https://git.spboucher.ai/qyvora11# Project Website  : Not specified12# Created          : 2026-12-0413# Last Modified    : 2026-12-0414#15# Author           : Simon-Pierre Boucher16# Position         : Professor of Finance17# Institution      : Université du Québec en Outaouais (UQO)18# Organization     : SP Boucher19# Website          : https://spboucher.ai20# Git              : https://git.spboucher.ai21#22# Preferred Contact: contact@spboucher.ai23# Development      : dev@spboucher.ai24# Support          : support@spboucher.ai25# Security/Admin   : admin@spboucher.ai26#27# Copyright (c) 202628# Simon-Pierre Boucher29# All rights reserved where applicable. This file is governed by the30# applicable project license, copyright notices and relevant law.31# Existing third-party rights and notices remain unaffected.32#33# License          : None specified (no license file in this repository)34#35# Do not embed credentials, private keys, access tokens,36# certificates or confidential personal information.37#38# =============================================================================39# END OF SP BOUCHER SOURCE HEADER40# =============================================================================4142"""Swift test runs of the audit: vector integrity, the engine's own test suites (root package) and43the audit package (conformance replay, Wycheproof, differential, property, fuzz-corpus replay).4445Counts come from what the test processes print and record: Swift Testing result lines for the46engine suites, and the JSON-lines records written by `AuditRecorder` for the audit package.47"""4849from __future__ import annotations5051import json52import os53import re54import sys55import time56from collections import OrderedDict57from pathlib import Path5859sys.path.insert(0, str(Path(__file__).resolve().parents[1]))6061from lib import build  # noqa: E40262from lib.common import FAILED, NOT_RUN, REPO, RUN, SECURITY, Context, finding, run_cmd, tool_result  # noqa: E4026364FULL_SLHDSA = Path.home() / "Desktop/Cluster/projets/SP/spb-quantum-crypto/tests/kat/acvp"6566RUN_LINE = re.compile(r"Test run with (\d+) tests? in (\d+) suites? (passed|failed) after ([\d.,]+) seconds(?: with (\d+) issues?)?")67TEST_LINE = re.compile(r"^[✔✘] Test (.+?) (passed|failed) after")68SUITE_LINE = re.compile(r"^[✔✘] Suite (.+?) (passed|failed) after")69ISSUE_LINE = re.compile(r"^✘ Test (.+?) recorded an issue at (\S+?):(\d+):\d+: (.*)")70ACVP_LINE = re.compile(r"^ACVP (.+?): (\d+)/(\d+)")717273def vectors(ctx: Context) -> dict:74    start = time.time()75    code, out, err, secs = run_cmd([sys.executable, "-I", str(SECURITY / "vectors" / "fetch.py"), "--verify"], timeout=300)76    try:77        summary = json.loads(out.strip().splitlines()[-1])78    except (ValueError, IndexError):79        summary = {}80    files, bad = summary.get("files", 0), summary.get("mismatches", -1)81    status = RUN if summary else FAILED82    findings = []83    if bad:84        findings.append(finding(85            id="QY-VECTORS-INTEGRITY", title="Stored test vectors do not match their manifest", severity="high", tool="vectors",86            area="supply-chain", cwe="CWE-494", location="security/vectors/MANIFEST.json",87            description="A third-party vector file differs from the SHA-256 recorded when it was fetched at the pinned revision: " + (out + err)[-600:],88            recommendation="Re-fetch with `python3 security/vectors/fetch.py` and review the difference before trusting any vector result."))89    return tool_result(90        tool="vectors", category="crypto", status=status, version="security/vectors/MANIFEST.json",91        reason="" if summary else (out + err)[-400:], command="python3 security/vectors/fetch.py --verify", duration_s=time.time() - start,92        coverage="SHA-256 of every third-party vector file (Wycheproof, BIP vectors) against the manifest written at fetch time. "93                 "The NIST ACVP/CAVP files committed with the engine tests carry their checksums in their own README files and are not re-hashed here.",94        metrics={"files": files, "mismatches": bad},95        tests=[{"area": "conformance", "name": "vector files match the manifest", "algorithm": "vector integrity", "parameter_set": "",96                "cases": files, "passed": files - max(bad, 0), "failed": max(bad, 0), "skipped": 0, "note": "SHA-256 of raw and stored content"}],97        findings=findings)9899100def _parse_swift_testing(text: str) -> dict:101    tests, suites, issues, acvp = OrderedDict(), OrderedDict(), [], []102    runs = []103    for line in text.splitlines():104        line = line.strip()105        m = RUN_LINE.search(line)106        if m:107            runs.append({"tests": int(m.group(1)), "suites": int(m.group(2)), "result": m.group(3), "issues": int(m.group(5) or 0)})108            continue109        m = TEST_LINE.match(line)110        if m:111            tests[m.group(1)] = m.group(2)112            continue113        m = SUITE_LINE.match(line)114        if m:115            suites[m.group(1)] = m.group(2)116            continue117        m = ISSUE_LINE.match(line)118        if m:119            issues.append({"test": m.group(1), "location": f"{m.group(2)}:{m.group(3)}", "message": m.group(4)[:400]})120            continue121        m = ACVP_LINE.match(line)122        if m:123            acvp.append({"label": m.group(1), "passed": int(m.group(2)), "total": int(m.group(3))})124    return {"runs": runs, "tests": tests, "suites": suites, "issues": issues, "acvp": acvp}125126127def engine_tests(ctx: Context) -> dict:128    """The engine's own suites (root package), release build, on this machine."""129    start = time.time()130    env = {}131    # The complete SLH-DSA ACVP files are replayed once, by the audit package (concurrently); the engine suites keep their committed set.132    if ctx.full:133        env["QYVORA_LDT"] = "1"134    cmd = ["swift", "test", "-c", "release", "--scratch-path", str(build.ENGINE_SCRATCH)]135    code, out, err, secs = run_cmd(cmd, cwd=REPO, timeout=4 * 3600, env=env)136    text = out + "\n" + err137    ctx.raw_path("engine-tests.log").write_text(text)138    parsed = _parse_swift_testing(text)139    total = sum(r["tests"] for r in parsed["runs"])140    failed_tests = [t for t, r in parsed["tests"].items() if r == "failed"]141    if not parsed["runs"]:142        errors = [l for l in text.splitlines() if "error:" in l][:12]143        return tool_result(tool="engine-tests", category="crypto", status=FAILED, version=build.swift_version(),144                           reason="no test run reported (build failure?): " + " | ".join(errors)[:1500], command=" ".join(cmd),145                           duration_s=time.time() - start, artifacts=["security/reports/raw/engine-tests.log"])146    # one record per suite147    per_suite: dict[str, list] = OrderedDict()148    suite_names = sorted(parsed["suites"], key=len, reverse=True)149    for name, status in parsed["suites"].items():150        per_suite[name] = [0, 0]151    tests = []152    for name, result in parsed["suites"].items():153        tests.append({"area": "engine", "name": "suite " + name, "algorithm": name, "parameter_set": "", "cases": 1,154                      "passed": 1 if result == "passed" else 0, "failed": 0 if result == "passed" else 1, "skipped": 0, "note": ""})155    findings = []156    for issue in parsed["issues"][:40]:157        findings.append(finding(158            title=f"Engine test failed: {issue['test']}", severity="high", tool="engine-tests", area="crypto", location=issue["location"],159            rule=issue["test"], description=issue["message"], cwe="CWE-1164",160            recommendation="A failing engine test blocks the release gate: fix the code or the test, never disable it.", evidence=issue["message"]))161    ok = code == 0 and not failed_tests and all(r["result"] == "passed" for r in parsed["runs"])162    return tool_result(163        tool="engine-tests", category="crypto", status=RUN, version=build.swift_version(), command=" ".join(cmd) + (" (QYVORA_LDT=1)" if ctx.full else ""),164        duration_s=time.time() - start,165        coverage="Every test target of the root Swift package (cryptographic engine, Bitcoin, Ethereum, vault, identity, recovery, "166                 "networking parsers, wallet service), release build, macOS. Includes the vectors embedded in the test sources (RFC 8439, "167                 "RFC 5869, RFC 6979, RFC 9106, BIP-84, BIP-143, BIP-174, BIP-380, FIPS examples) and the regression tests of the fixed findings. "168                 + ("Large-data (LDT) hash vectors included. " if ctx.full else "Large-data hash vectors are replayed in full mode only. ")169                 + "Live-network tests are opt-in and are not run by the audit.",170        metrics={"tests": total, "tests_failed": len(failed_tests), "suites": len(parsed["suites"]),171                 "suites_failed": sum(1 for r in parsed["suites"].values() if r == "failed"), "test_processes": len(parsed["runs"]),172                 "exit_code": code, "all_passed": ok, "failed_tests": failed_tests[:50], "acvp_lines": parsed["acvp"]},173        tests=tests + [{"area": "engine", "name": "engine test functions", "algorithm": "all engine suites", "parameter_set": "",174                        "cases": total, "passed": total - len(failed_tests), "failed": len(failed_tests), "skipped": 0,175                        "note": "Swift Testing test functions (a parameterised function counts once)"}],176        findings=findings, artifacts=["security/reports/raw/engine-tests.log"])177178179def swift_audit(ctx: Context) -> dict:180    """The audit package: conformance replay, Wycheproof, differential, property and fuzz-corpus replay tests."""181    start = time.time()182    out_dir = ctx.raw_path("swift-audit")183    out_dir.mkdir(parents=True, exist_ok=True)184    records_file = out_dir / "records.jsonl"185    if records_file.exists():186        records_file.unlink()187    env = {"QY_AUDIT_OUT": str(out_dir), "QY_AUDIT_MODE": ctx.mode, "QY_AUDIT_REPO": str(REPO)}188    if os.environ.get("QY_AUDIT_SEED"):189        env["QY_AUDIT_SEED"] = os.environ["QY_AUDIT_SEED"]190    cmd = ["swift", "test", "-c", "release", "--package-path", str(build.AUDIT_PACKAGE), "--scratch-path", str(build.AUDIT_SCRATCH)]191    code, out, err, secs = run_cmd(cmd, cwd=REPO, timeout=8 * 3600, env=env)192    text = out + "\n" + err193    ctx.raw_path("swift-audit.log").write_text(text)194    parsed = _parse_swift_testing(text)195    records = []196    if records_file.exists():197        for line in records_file.read_text().splitlines():198            try:199                records.append(json.loads(line))200            except ValueError:201                pass202    if not parsed["runs"] and not records:203        errors = [l for l in text.splitlines() if "error:" in l][:12]204        return tool_result(tool="swift-audit", category="crypto", status=FAILED, version=build.swift_version(),205                           reason="the audit package did not build or run: " + " | ".join(errors)[:1500], command=" ".join(cmd),206                           duration_s=time.time() - start, artifacts=["security/reports/raw/swift-audit.log"])207    by_area: dict[str, dict] = {}208    for r in records:209        a = by_area.setdefault(r.get("area", "?"), {"records": 0, "cases": 0, "failed": 0, "not_run": 0})210        a["records"] += 1211        a["cases"] += r.get("cases", 0)212        a["failed"] += r.get("failed", 0)213        if r.get("skipped") and not r.get("cases"):214            a["not_run"] += 1215    failed_functions = [t for t, r in parsed["tests"].items() if r == "failed"]216    findings = []217    for r in records:218        if r.get("failed"):219            findings.append(finding(220                title=f"{r.get('area')} check failed: {r.get('algorithm')} {r.get('parameter_set')} — {r.get('name')}", severity="high",221                tool="swift-audit", area="crypto", cwe="CWE-327", masvs="MASVS-CRYPTO-1", rule=f"{r.get('area')}:{r.get('name')}",222                location="security/tests", description=f"{r.get('failed')} of {r.get('cases')} cases failed"223                + (f" (seed {r.get('seed')}, reproduce with QY_AUDIT_SEED)" if r.get("seed") else "") + f". Oracle: {r.get('oracle') or 'n/a'}.",224                recommendation="Reproduce, decide which side is right against the standard, fix the engine with a regression test.",225                evidence=json.dumps(r)))226    recorded_issue_tests = set()227    for issue in parsed["issues"]:228        if issue["test"] in recorded_issue_tests or len(findings) > 60:229            continue230        recorded_issue_tests.add(issue["test"])231        if not any(issue["test"].split("(")[0] in f["evidence"] for f in findings):232            findings.append(finding(233                title=f"Audit test failed: {issue['test']}", severity="high", tool="swift-audit", area="crypto", location=issue["location"],234                rule=issue["test"], description=issue["message"], recommendation="Investigate: an audit test failure blocks the release gate.",235                evidence=issue["message"]))236    not_run = [f"{r.get('name')}: {r.get('note')}" for r in records if r.get("skipped") and not r.get("cases")]237    total_functions = sum(r["tests"] for r in parsed["runs"])238    return tool_result(239        tool="swift-audit", category="crypto", status=RUN, version=build.swift_version(),240        command=" ".join(cmd) + f" (QY_AUDIT_MODE={ctx.mode})", duration_s=time.time() - start,241        coverage="Audit-specific executable tests (security/tests): replay of the NIST ACVP/CAVP files with counts per parameter set, "242                 "Wycheproof vectors at the pinned revision, differential tests against independent implementations (CryptoKit, CommonCrypto, "243                 "the Rust library spb-quantum-crypto, libsecp256k1 and other Python references — test environment only), property and "244                 "invariant tests, and replay of the fuzzing corpus and of past crash inputs. Random cases are generated from logged seeds.",245        metrics={"mode": ctx.mode, "test_functions": total_functions, "test_functions_failed": len(failed_functions),246                 "records": len(records), "cases": sum(r.get("cases", 0) for r in records), "cases_failed": sum(r.get("failed", 0) for r in records),247                 "by_area": by_area, "not_run": not_run, "exit_code": code, "failed_functions": failed_functions[:50]},248        tests=[{"area": r.get("area", ""), "name": r.get("name", ""), "algorithm": r.get("algorithm", ""),249                "parameter_set": r.get("parameter_set", ""), "oracle": r.get("oracle", ""), "cases": r.get("cases", 0),250                "passed": r.get("passed", 0), "failed": r.get("failed", 0), "skipped": r.get("skipped", 0), "seed": r.get("seed"),251                "note": r.get("note", "")} for r in records],252        findings=findings, artifacts=["security/reports/raw/swift-audit.log", "security/reports/raw/swift-audit/records.jsonl"])253254255def run(ctx: Context) -> list[dict]:256    return [vectors(ctx), engine_tests(ctx), swift_audit(ctx)]257258259if __name__ == "__main__":260    context = Context("full" if "--full" in sys.argv else "quick")261    which = [a for a in sys.argv[1:] if not a.startswith("--")]262    table = {"vectors": vectors, "engine": engine_tests, "audit": swift_audit}263    print(json.dumps([table[w](context) for w in (which or table)], indent=2))264
Files main
Menu

Theme