SPB Git

Repository Public

generate.py 53.3 KB 856 lines python

1#!/usr/bin/env python32# =============================================================================3#                  SP BOUCHER | SOFTWARE & RESEARCH4#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5# =============================================================================6#7# Project          : QYVORA8# File             : security/audit/report/generate.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"""Report generator of the QYVORA security audit.4344Input: the results document written by the orchestrator (SECURITY_AUDIT_RESULTS.json).45Output, in security/reports/: SECURITY_AUDIT_REPORT.md, SECURITY_AUDIT_REPORT.html (self-contained),46SECURITY_AUDIT_REPORT.pdf and CRYPTOGRAPHIC_VALIDATION_REPORT.pdf (+ its HTML source).4748Every number printed in a report is read from the results document. The surrounding prose49(method, limits, recommendations) is fixed text of this file; it states what the audit is and is not.5051    python3 security/audit/report/generate.py [path/to/SECURITY_AUDIT_RESULTS.json]52"""5354from __future__ import annotations5556import html57import json58import shutil59import subprocess60import sys61from collections import OrderedDict, defaultdict62from pathlib import Path6364REPO = Path(__file__).resolve().parents[3]65import os  # noqa: E4026667REPORTS = Path(os.environ["QY_AUDIT_REPORTS"]).resolve() if os.environ.get("QY_AUDIT_REPORTS") else REPO / "security" / "reports"68SEVERITIES = ["critical", "high", "medium", "low", "info"]6970# --- document model -----------------------------------------------------------------------------71# A report is a list of blocks: ("h1"|"h2"|"h3"|"p"|"note"|"warn", text), ("list", [items]),72# ("table", [headers], [[cells]], optional {"class": ...}), ("kv", [(key, value)]), ("pagebreak",).737475def fmt_int(n) -> str:76    try:77        return f"{int(n):,}".replace(",", "\u202f")78    except (TypeError, ValueError):79        return str(n)808182def fmt_duration(seconds) -> str:83    try:84        s = float(seconds)85    except (TypeError, ValueError):86        return "—"87    if s < 60:88        return f"{s:.1f} s"89    if s < 3600:90        return f"{int(s // 60)} min {int(s % 60):02d} s"91    return f"{int(s // 3600)} h {int(s % 3600 // 60):02d} min"929394def short(text, n=220) -> str:95    text = " ".join(str(text or "").split())96    return text if len(text) <= n else text[: n - 1] + "…"979899class Doc:100    def __init__(self, title: str, subtitle: str):101        self.title, self.subtitle, self.blocks = title, subtitle, []102103    def add(self, *block):104        self.blocks.append(block)105106    def h1(self, t): self.add("h1", t)107    def h2(self, t): self.add("h2", t)108    def h3(self, t): self.add("h3", t)109    def p(self, t): self.add("p", t)110    def note(self, t): self.add("note", t)111    def warn(self, t): self.add("warn", t)112    def items(self, l): self.add("list", list(l))113    def kv(self, pairs): self.add("kv", list(pairs))114    def table(self, headers, rows, cls=""): self.add("table", list(headers), [list(map(str, r)) for r in rows], {"class": cls})115116117# --- shared content ------------------------------------------------------------------------------118119STATUS_LABEL = {"RUN": "RUN", "NOT RUN": "NOT RUN", "FAILED": "FAILED"}120121122def tools_by_name(doc: dict) -> dict:123    return OrderedDict((t["tool"], t) for t in doc["tools"])124125126def header_block(d: Doc, doc: dict, what: str) -> None:127    a, g = doc["audit"], doc["gate"]128    d.note(doc["statement"])129    d.kv([130        ("Product", f"{a['product']} — non-custodial iOS wallet (Bitcoin, Ethereum), cryptographic engine written in Swift"),131        ("Audited version", f"{a['wallet_version']} (build {a['wallet_build']}), from {a['version_source']}"),132        ("Git commit", f"{a['git_commit']} on {a['git_branch']} ({a['git_commit_date']})"133                       + (" — WORKING TREE NOT CLEAN: " + ", ".join(a["git_dirty_files"][:8]) + ("…" if len(a["git_dirty_files"]) > 8 else "") if a["git_dirty"] else " — clean working tree")),134        ("Date of the run (UTC)", a["date_utc"]),135        ("Kind of run", ("FULL" if a["mode"] == "full" else "QUICK (reduced case counts; no application binary, no MobSF, short fuzzing — not sufficient for a publication)")),136        ("Machine", f"{a['host']} ({a['machine']}), macOS {a['macos']}, {a['xcode']}, {a['swift']}"),137        ("Command", a["command"]),138        ("Duration", fmt_duration(a.get("duration_s"))),139        (what, ("PASSED" if g["passed"] else "FAILED") + f" — {len(g['blockers'])} blocking condition(s), {len(g['warnings'])} warning(s)"),140    ])141142143def findings_matrix(d: Doc, findings: list[dict]) -> None:144    statuses = ["open", "fixed", "accepted-risk", "false-positive"]145    rows = []146    for sev in SEVERITIES:147        subset = [f for f in findings if f.get("severity") == sev]148        rows.append([sev.capitalize()] + [fmt_int(sum(1 for f in subset if f.get("status") == s)) for s in statuses] + [fmt_int(len(subset))])149    rows.append(["Total"] + [fmt_int(sum(1 for f in findings if f.get("status") == s)) for s in statuses] + [fmt_int(len(findings))])150    d.table(["Severity", "Open", "Fixed", "Accepted risk", "False positive", "Total"], rows, "num")151152153def finding_rows(findings: list[dict]) -> list[list[str]]:154    rows = []155    for f in findings:156        cvss = f"{f['cvss_score']}" if f.get("cvss_score") not in (None, "") else "—"157        rows.append([f["id"], f.get("severity", ""), f.get("status", ""), cvss, short(f.get("title"), 150), short(f.get("location"), 70),158                     (f.get("fix_commit") or "—")])159    return rows160161162def finding_details(d: Doc, findings: list[dict]) -> None:163    for f in findings:164        d.h3(f"{f['id']} — {f.get('title', '')}")165        pairs = [("Severity / status", f"{f.get('severity')} / {f.get('status')}")]166        if f.get("cvss_vector"):167            pairs.append(("CVSS v3.1", f"{f.get('cvss_score')} — {f['cvss_vector']}"))168        ref = " · ".join(x for x in (f.get("cwe"), f.get("masvs")) if x)169        if ref:170            pairs.append(("References", ref))171        if f.get("location"):172            pairs.append(("Location", f["location"]))173        pairs.append(("Found by", f.get("tool", "") + (f" (rule {f['rule']})" if f.get("rule") else "")))174        if f.get("fix_commit"):175            pairs.append(("Fix commit", f["fix_commit"]))176        if f.get("regression_test"):177            pairs.append(("Regression test", f["regression_test"]))178        if f.get("triage"):179            pairs.append(("Triage", f["triage"]))180        if f.get("resolution_note"):181            pairs.append(("Note", f["resolution_note"]))182        d.kv(pairs)183        if f.get("description"):184            d.p(f["description"])185        if f.get("recommendation"):186            d.p("Recommendation / fix: " + f["recommendation"])187188189def aggregate(tests: list[dict], key) -> list[tuple]:190    """Sums cases/failed/not-run of test records by key(record)."""191    agg: dict = OrderedDict()192    for t in tests:193        k = key(t)194        a = agg.setdefault(k, {"records": 0, "cases": 0, "failed": 0, "not_run": 0})195        a["records"] += 1196        a["cases"] += t.get("cases", 0)197        a["failed"] += t.get("failed", 0)198        if t.get("skipped") and not t.get("cases"):199            a["not_run"] += 1200    return list(agg.items())201202203def verdict(a: dict) -> str:204    if a["failed"]:205        return "FAILED"206    if a["cases"] == 0:207        return "NOT RUN"208    return "passed" + (f" ({a['not_run']} check(s) not run)" if a["not_run"] else "")209210211def crypto_sections(d: Doc, doc: dict, detailed: bool) -> None:212    tools = tools_by_name(doc)213    audit = tools.get("swift-audit", {})214    tests = audit.get("tests", [])215    engine = tools.get("engine-tests", {})216    mode = doc["audit"]["mode"]217218    d.h2("Conformance to the standards: official test vectors")219    if audit.get("status") != "RUN":220        d.warn(f"The audit test package did not run ({audit.get('status', 'no result')}): {short(audit.get('reason'), 400)}. No vector result is reported.")221    conformance = [t for t in tests if t.get("area") == "conformance"]222    if conformance:223        d.p("Each line is a replay by the audit package (security/tests) of the vector files named in the source column, with the engine's "224            "deterministic entry points. A case passes when the engine's output is byte-identical to the expected output (or when the "225            "expected accept/reject decision is reproduced).")226        rows = []227        for (alg, ps, src), a in sorted(aggregate(conformance, lambda t: (t.get("algorithm") or "", t.get("parameter_set") or "", t.get("oracle") or ""))):228            rows.append([alg, ps or "—", src, fmt_int(a["cases"]), fmt_int(a["failed"]), verdict(a)])229        d.table(["Algorithm", "Parameter set", "Vector source", "Cases", "Failed", "Result"], rows, "num")230        d.p(f"Total: {fmt_int(sum(t.get('cases', 0) for t in conformance))} vector cases replayed, {fmt_int(sum(t.get('failed', 0) for t in conformance))} failed.")231        if detailed:232            d.h3("Detail by function")233            rows = [[t.get("algorithm"), t.get("parameter_set") or "—", t.get("name"), fmt_int(t.get("cases")), fmt_int(t.get("failed")),234                     "not run" if (t.get("skipped") and not t.get("cases")) else ("FAILED" if t.get("failed") else "passed")]235                    for t in sorted(conformance, key=lambda t: (t.get("algorithm") or "", t.get("parameter_set") or "", t.get("name") or ""))]236            d.table(["Algorithm", "Parameter set", "Function / variant", "Cases", "Failed", "Result"], rows, "num small")237    vec = tools.get("vectors")238    if vec:239        d.p(f"Integrity of the third-party vector files: {vec['status']}"240            + (f" — {fmt_int(vec['metrics'].get('files'))} files checked against the manifest, {fmt_int(vec['metrics'].get('mismatches'))} mismatch(es)." if vec["status"] == "RUN" else f" — {short(vec.get('reason'))}"))241242    wy = [t for t in tests if t.get("area") == "wycheproof"]243    d.h2("Wycheproof: edge cases and invalid inputs")244    if wy:245        d.p("Wycheproof vectors at the pinned revision (security/vectors/MANIFEST.json): signature malleability, invalid encodings, special "246            "curve points, tag and nonce edge cases, malformed keys and ciphertexts. 'Valid' vectors must be accepted with the expected "247            "output, 'invalid' ones rejected without trapping; 'acceptable' ones are tallied in the note.")248        rows = [[t.get("algorithm"), t.get("parameter_set") or "—", fmt_int(t.get("cases")), fmt_int(t.get("failed")), short(t.get("note"), 150)]249                for t in sorted(wy, key=lambda t: (t.get("algorithm") or "", t.get("parameter_set") or ""))]250        d.table(["Algorithm", "Parameter set", "Cases", "Failed", "File and notes"], rows, "num small")251        total = sum(t.get("cases", 0) for t in wy)252        d.p(f"Total: {fmt_int(total)} Wycheproof cases, {fmt_int(sum(t.get('failed', 0) for t in wy))} failed.")253    else:254        d.p("No Wycheproof record in this run.")255256    diff = [t for t in tests if t.get("area") == "differential"]257    d.h2("Differential testing against independent implementations")258    if diff:259        d.p("Random inputs (seeds logged in the results file) are given to the engine and to an independent implementation used in the test "260            "environment only; any difference is a failure. CryptoKit and CommonCrypto are Apple's; libsecp256k1, the Argon2 reference, "261            "pycryptodome, hashlib and the BIP reference scripts are third-party; the Rust library spb-quantum-crypto is the owner's own "262            "(experimental, not audited): agreement with it is a consistency check, not an external validation.")263        rows = []264        for (alg, ps, oracle), a in sorted(aggregate(diff, lambda t: (t.get("algorithm") or "", t.get("parameter_set") or "", t.get("oracle") or ""))):265            rows.append([alg, ps or "—", oracle or "—", fmt_int(a["cases"]), fmt_int(a["failed"]), verdict(a)])266        d.table(["Algorithm / operation", "Parameter set", "Reference", "Cases", "Mismatches", "Result"], rows, "num small")267        d.p(f"Total: {fmt_int(sum(t.get('cases', 0) for t in diff))} differential cases, {fmt_int(sum(t.get('failed', 0) for t in diff))} mismatch(es)"268            + (f"; {sum(1 for t in diff if t.get('skipped') and not t.get('cases'))} campaign(s) NOT RUN (reference missing on this machine)." if any(t.get('skipped') and not t.get('cases') for t in diff) else "."))269    else:270        d.p("No differential record in this run.")271272    prop = [t for t in tests if t.get("area") == "property"]273    d.h2("Properties and mathematical invariants")274    if prop:275        rows = [[t.get("algorithm"), t.get("parameter_set") or "—", short(t.get("name"), 170), fmt_int(t.get("cases")), fmt_int(t.get("failed")),276                 "not run" if (t.get("skipped") and not t.get("cases")) else ("FAILED" if t.get("failed") else "passed")]277                for t in sorted(prop, key=lambda t: (t.get("algorithm") or "~", t.get("parameter_set") or ""))]278        d.table(["Area", "Parameter set", "Property", "Cases", "Failed", "Result"], rows, "num small")279        d.p(f"Total: {fmt_int(sum(t.get('cases', 0) for t in prop))} property cases (exhaustive loops included), {fmt_int(sum(t.get('failed', 0) for t in prop))} failed.")280281    d.h2("Engine test suites")282    if engine:283        m = engine.get("metrics", {})284        if engine["status"] == "RUN":285            d.p(f"The engine's own suites (root Swift package, release build): {fmt_int(m.get('tests'))} test functions in {fmt_int(m.get('suites'))} suites, "286                f"{fmt_int(m.get('tests_failed'))} failed. They include the vectors embedded in the test sources (RFC 8439, RFC 5869, RFC 6979, RFC 9106, "287                "BIP-84, BIP-143, BIP-174, BIP-380, FIPS examples) and the regression tests of the fixed findings.")288            if detailed:289                suites = [t for t in engine.get("tests", []) if t.get("name", "").startswith("suite ")]290                rows = [[t["algorithm"], "passed" if not t.get("failed") else "FAILED"] for t in suites]291                half = (len(rows) + 1) // 2292                d.table(["Suite", "Result", "Suite", "Result"], [rows[i] + (rows[i + half] if i + half < len(rows) else ["", ""]) for i in range(half)], "small")293        else:294            d.warn(f"Engine tests: {engine['status']} — {short(engine.get('reason'), 400)}")295296    fuzz = tools.get("qyfuzz")297    d.h2("Fuzzing")298    if fuzz:299        m = fuzz.get("metrics", {})300        if fuzz["status"] == "RUN":301            d.p(short(fuzz.get("coverage"), 1200))302            d.kv([(k.replace("_", " "), fmt_int(v) if isinstance(v, (int, float)) and not isinstance(v, bool) else str(v))303                  for k, v in m.items() if not isinstance(v, (list, dict))])304            machines = m.get("machines") or []305            if machines:306                keys = [k for k in ("host", "cores", "workers", "seconds", "executions", "crashes", "hangs") if any(k in x for x in machines)]307                d.table([k.capitalize() for k in keys], [[fmt_int(x.get(k)) if isinstance(x.get(k), (int, float)) else str(x.get(k, "")) for k in keys] for x in machines], "num")308            if detailed and fuzz.get("tests"):309                rows = [[t.get("name"), fmt_int(t.get("cases")), fmt_int(t.get("failed")), short(t.get("note"), 110)] for t in fuzz["tests"]]310                d.table(["Target", "Executions", "Crashes", "Note"], rows, "num small")311        else:312            d.warn(f"Fuzzing: {fuzz['status']} — {short(fuzz.get('reason'), 400)}")313    campaigns = sorted((REPO / "security" / "fuzzing" / "campaigns").glob("*.json")) if (REPO / "security" / "fuzzing" / "campaigns").exists() else []314    if campaigns:315        rows = []316        for path in campaigns:317            try:318                c = json.loads(path.read_text())319            except ValueError:320                continue321            rows.append([path.name, str(c.get("host", "")), fmt_int(c.get("workers", "")), fmt_duration(c.get("seconds")),322                         fmt_int(c.get("executions", "")), fmt_int(c.get("crashes", "")), fmt_int(c.get("hangs", ""))])323        if rows:324            d.h3("Recorded long campaigns (security/fuzzing/campaigns)")325            d.p("Campaign summaries committed with the repository. They were produced by earlier runs of the fuzzer on cluster nodes; the commit they ran on is in each file.")326            d.table(["File", "Machine", "Workers", "Duration", "Executions", "Crashes", "Hangs"], rows, "num small")327    replay = [t for t in tests if t.get("area") == "fuzz"]328    if replay:329        d.p(f"Replay of the corpus and of past crash inputs by the test package: {fmt_int(sum(t.get('cases', 0) for t in replay))} inputs, "330            f"{fmt_int(sum(t.get('failed', 0) for t in replay))} failed.")331    san = tools.get("sanitizers")332    if san:333        d.h3("Sanitizers")334        if san["status"] == "RUN":335            d.p(short(san.get("coverage"), 900))336            if san.get("tests"):337                d.table(["Suite / sanitizer", "Cases", "Failed", "Note"],338                        [[t.get("name"), fmt_int(t.get("cases")), fmt_int(t.get("failed")), short(t.get("note"), 130)] for t in san["tests"]], "num small")339        else:340            d.p(f"Sanitizers: {san['status']} — {short(san.get('reason'), 300)}")341342    d.h2("Timing and side channels")343    mc = tools.get("ct-machine-code")344    if mc:345        d.h3("Machine code of the functions that process secrets")346        if mc["status"] == "RUN":347            d.p(short(mc.get("coverage"), 1200))348            rows = [[r["function"].rstrip("("), str(r.get("conditional_branches", "—")), str(r["max"]), r["status"], short(r["why"], 150)]349                    for r in mc["metrics"].get("rows", [])]350            d.table(["Function", "Conditional branches", "Reviewed maximum", "Status", "What the remaining branches test"], rows, "small")351        else:352            d.warn(f"Machine-code check: {mc['status']} — {short(mc.get('reason'), 300)}")353    mci = tools.get("ct-machine-code-ios")354    if mci:355        d.h3("Machine code of the iOS application binary")356        if mci["status"] == "RUN":357            d.p(short(mci.get("coverage"), 900))358            rows = [[r["function"].rstrip("("), str(r.get("conditional_branches", "—")), str(r["max"]), r["status"]] for r in mci["metrics"].get("rows", [])]359            d.table(["Function", "Conditional branches", "Reviewed maximum", "Status"], rows, "small")360        else:361            d.p(f"{mci['status']} — {short(mci.get('reason'), 300)}")362    du = tools.get("dudect-timing")363    if du:364        d.h3("Statistical timing test (dudect method)")365        if du["status"] in ("RUN", "FAILED") and du.get("tests"):366            m = du["metrics"]367            d.p(short(du.get("coverage"), 1500))368            d.kv([("Machine", f"{m.get('machine')} — {m.get('where')}"), ("Sample scale", str(m.get("scale"))), ("Seed", str(m.get("seed"))),369                  ("Threshold", f"|t| > {m.get('threshold')}, confirmed by a second run"),370                  ("Data-independent-timing flag (PSTATE.DIT)", f"supported: {m.get('dit_supported')}, set during the measurements: {m.get('dit_enabled')}"),371                  ("Exceeded once / confirmed", f"{', '.join(m.get('exceeded_once') or []) or 'none'} / {', '.join(m.get('confirmed') or []) or 'none'}")])372            if m.get("quick_mode_note"):373                d.warn(m["quick_mode_note"])374            rows = [[t["name"], short(t.get("parameter_set"), 70), fmt_int(t.get("cases")), f"{t.get('mean_a_ns')} / {t.get('mean_b_ns')}",375                     f"{t.get('t_raw'):+.2f}" if isinstance(t.get("t_raw"), (int, float)) else "—",376                     f"{abs(t.get('t_max')):.2f}" if isinstance(t.get("t_max"), (int, float)) else "—",377                     "informational" if t["name"].startswith("info-") else ("control" if t["name"].startswith("control-") else ("LEAK CONFIRMED" if t.get("failed") else "no evidence of leak"))]378                    for t in du["tests"]]379            d.table(["Target", "Classes (A / B)", "Measurements", "Mean ns (A / B)", "t (raw)", "max |t|", "Verdict"], rows, "num small")380            if du["status"] == "FAILED":381                d.warn("The controls of this run did not behave as expected: " + short(du.get("reason"), 300))382        else:383            d.warn(f"Timing test: {du['status']} — {short(du.get('reason'), 300)}")384385    reviews = doc.get("reviews", {})386    cp = reviews.get("crypto-primitives")387    if cp:388        d.h3("Source review for secret-dependent operations")389        entries = cp.get("entries", [])390        counts = defaultdict(int)391        for e in entries:392            counts[e.get("verdict", "?")] += 1393        d.p(f"Manual review of the primitives (security/audit/review/crypto-primitives.json): {fmt_int(len(entries))} constructs examined "394            "(branches, table lookups, divisions, early exits, comparisons on secret data). The review reads the source; the machine-code "395            "check and the timing test above are its complement — finding QYV-AUD-002 was invisible in the source.")396        d.table(["Verdict", "Constructs"], [[k, fmt_int(v)] for k, v in sorted(counts.items(), key=lambda kv: -kv[1])], "num")397        if detailed:398            rows = [[e.get("module", ""), f"{Path(e.get('file', '')).name}:{e.get('line', '')}", short(e.get("construct"), 120), e.get("verdict", ""), e.get("finding_id", "") or ""]399                    for e in entries]400            d.table(["Module", "Location", "Construct", "Verdict", "Finding"], rows, "small")401402    d.h2("Entropy and random numbers")403    hygiene = [t for t in tools.get("static-checks", {}).get("tests", []) if "entropy" in t.get("name", "")]404    for t in hygiene:405        d.p(f"Static check — {t['name']}: {'passed' if not t.get('failed') else 'FAILED'}. {short(t.get('note'), 500)}")406    ent = (cp or {}).get("entropy")407    if ent:408        if isinstance(ent, dict):409            d.kv([(k.replace("_", " "), short(v, 600)) for k, v in ent.items()])410        elif isinstance(ent, list):411            d.items([short(x, 600) for x in ent])412        else:413            d.p(short(ent, 1200))414    d.p("Every key, seed and nonce of the engine is drawn from SystemRandom (SecRandomCopyBytes); the static check fails if another generator "415        "appears in the sources. Statistical sanity of the operating-system generator is not tested: such tests cannot establish that a "416        "generator is unpredictable. AEAD nonces are random 96-bit values: with q seals under one key the probability of a repeated nonce is "417        "about q²/2⁹⁷ (2⁻³³ after 2³² seals); the engine does not count seals per key, the vault and backups use per-record or per-file keys.")418419    mh = reviews.get("memory-hygiene-crypto"), reviews.get("memory-hygiene-services")420    if any(mh):421        d.h2("Sensitive data in memory")422        d.p("Swift offers no guaranteed erasure: arrays are copied on write, values may live in registers and on the stack, and strings "423            "(passwords, recovery phrases typed by the user) cannot be wiped. The reviews list what is erased and what cannot be.")424        if mh[0]:425            d.kv([("Erased by the primitives", fmt_int(len(mh[0].get("erased", []))) + " groups of temporaries (seeds, hash states, key schedules, nonces)"),426                  ("Not erasable", fmt_int(len(mh[0].get("not_erased", []))) + " items (see findings QYV-CRY-003)")])427            if detailed:428                d.table(["Where", "What is not erased", "Residual risk"],429                        [[x.get("where", ""), short(x.get("what"), 200), short(x.get("residual_risk") or x.get("risk") or x.get("why") or "", 160)] for x in mh[0].get("not_erased", [])], "small")430        if mh[1]:431            entries = mh[1].get("entries", [])432            d.table(["Secret (service layer)", "Representation", "Wiping", "Residual risk"],433                    [[short(e.get("secret"), 60), short(e.get("representation"), 150), e.get("wiping", ""), e.get("residual_risk", "")] for e in entries], "small")434435436def limits_and_recommendations(d: Doc, doc: dict) -> None:437    g, s = doc["gate"], doc["summary"]438    d.h2("Limits of this audit")439    d.items([440        "Internal and automated: run by the project on its own machines with its own tools and tests. Nobody independent of the project has reviewed the cryptography, the protocol code or this audit engine.",441        "Tests show the presence of defects, not their absence. Passing every vector and differential test does not prove an implementation correct on all inputs, nor secure against side channels.",442        "Timing results are statistical evidence on one machine and one compiler build. Swift gives no constant-time guarantee; no power, electromagnetic or fault-injection analysis was made. Timing is measured on the macOS build of the package; the iOS application binary is only disassembled (branch counts), in full runs, not timed on a device.",443        "Fuzzing uses the project's own mutation engine with outcome-class feedback; it is not coverage-guided (the Xcode Swift toolchain refuses -sanitize=fuzzer). Parsers may have unreached states.",444        "Static tools have limited Swift support (Semgrep: experimental, single-file; mobsfscan: 24 rules; Dontrust: 2 Swift-scoped rules). Their silence proves little; their coverage statements are quoted in this report.",445        "MobSF analyses an unsigned archive statically: no dynamic analysis on a device, no jailbroken-device testing, no runtime instrumentation. Signed-build checks (entitlements as applied, provisioning) are not covered.",446        "The framework assessments (OWASP MASVS/MASTG, Coinspect) are self-assessments by source review; MASVS is not a certification scheme and no laboratory was involved.",447        "No real funds were used. Network code was tested with recorded and synthetic responses; live test-network checks are opt-in and outside the audit.",448        "Post-quantum algorithms protect the local vault, backups, transfers and the separate identity. Bitcoin and Ethereum transactions rely on secp256k1 and are not quantum-resistant; nothing in this audit changes that.",449    ])450    if s["tools_not_run"] or s["tools_failed"]:451        d.h3("Not run or failed in this run")452        d.table(["Tool", "Status", "Reason"],453                [[t["tool"], "NOT RUN", short(t["reason"], 260)] for t in s["tools_not_run"]] + [[t["tool"], "FAILED", short(t["reason"], 260)] for t in s["tools_failed"]], "small")454    d.h2("Release gate")455    d.p(g["meaning"])456    if g["blockers"]:457        d.table(["Blocking condition", "Detail"], [[b["rule"], short(b["detail"], 320)] for b in g["blockers"]], "small")458    else:459        d.p("No blocking condition at this commit for this kind of run.")460    if g["warnings"]:461        d.table(["Warning", "Detail"], [[w["rule"], short(w["detail"], 320)] for w in g["warnings"]], "small")462    d.h2("Recommendations before production")463    d.items([464        "Commission an independent cryptographic review of the engine (secp256k1, BIP-32/39, AES-GCM, ChaCha20-Poly1305, Argon2id, ML-KEM, ML-DSA, SLH-DSA) and of the vault and backup formats before any recommendation to use the wallet with real funds. Until then keep the mainnet gate and its per-transaction limits.",465        "Resolve or have the owner explicitly accept every open finding of medium severity; the accepted-risk and false-positive dispositions proposed by the audit agents in the triage files need the owner's confirmation.",466        "Run the full audit (`Scripts/security-audit.sh --full --nodes \"…\"`) on the final commit with a clean working tree, and commit the reports it produces.",467        "Set the processor's data-independent-timing flag around secret operations (QYV-CRY-004, QYV-AUD-003); it needs a small C or assembly shim in the engine, an owner decision.",468        "Repeat the audit after every compiler or Xcode update: the constant-time property of the compiled code depends on the optimiser (QYV-AUD-002).",469        "Complete the application-level items left open for the integrator (auto-lock wiring, fresh authentication for sensitive actions, screenshot and keyboard protections, privacy manifest, removal of QYInternalMainnet from public builds).",470        "Perform dynamic testing on a device (MASTG dynamic tests recorded as not assessed) and a signed-build verification before distribution.",471    ])472473474# --- the two reports ------------------------------------------------------------------------------475476def build_main(doc: dict) -> Doc:477    a, s, g = doc["audit"], doc["summary"], doc["gate"]478    tools = tools_by_name(doc)479    findings = doc["findings"]480    d = Doc("QYVORA — Security Audit Report", f"Version {a['wallet_version']} ({a['wallet_build']}) · commit {a['git_commit'][:12]} · {a['date_utc'][:10]} · {a['mode']} run")481    d.h1("1. Summary")482    header_block(d, doc, "Release gate")483    t = s["tests"]484    d.p(f"{len(s['tools_run'])} tools and check suites ran, {len(s['tools_not_run'])} did not run and {len(s['tools_failed'])} failed. "485        f"{fmt_int(t['cases'])} test cases were executed in {fmt_int(t['records'])} recorded checks. "486        f"{fmt_int(s['findings']['total'])} findings are recorded: {fmt_int(s['findings']['open'])} open, {fmt_int(s['findings']['fixed'])} fixed, "487        f"{fmt_int(s['findings']['accepted_risk'])} accepted risk, {fmt_int(s['findings']['false_positive'])} false positive.")488    findings_matrix(d, findings)489    rows = []490    for area, v in sorted(t["by_area"].items()):491        rows.append([area, fmt_int(v["records"]), fmt_int(v["cases"]), fmt_int(v["failed"]), fmt_int(v["not_run"])])492    d.h3("Checks executed, by area")493    d.table(["Area", "Recorded checks", "Cases", "Failed", "Checks not run"], rows, "num")494    d.p("'Failed' in the areas static, binary and framework counts rules or controls that reported something; what they reported is triaged "495        "in the findings. In the areas conformance, wycheproof, differential, property, fuzz, engine and timing a failed case blocks the release gate.")496497    d.h1("2. Scope and method")498    d.p("Scope: the Swift package at the repository root — cryptographic engine (QyvoraMath, QyvoraKeccak, QyvoraSymmetric, QyvoraMLKEM, "499        "QyvoraMLDSA, QyvoraSLHDSA, QyvoraSecp256k1, QyvoraCrypto), protocol and service modules (QyvoraCore, QyvoraBitcoin, QyvoraEthereum, "500        "QyvoraStorage, QyvoraNetworking, QyvoraVault, QyvoraIdentity, QyvoraRecovery, QyvoraQuantumShield, QyvoraMigration, QyvoraWallet, "501        "QyvoraUI) — and the iOS application (App/). The audit engine lives in security/ and re-runs with one command.")502    d.items([503        "Cryptography: replay of official vectors (NIST ACVP and CAVP, RFC, BIP, Wycheproof), differential tests against independent implementations, property and invariant tests, mutation fuzzing with crash capture, sanitizer builds, statistical timing tests and inspection of the compiled code, manual source review.",504        "Wallet and application: source review of key storage, authentication, backup, networking and transaction construction; OWASP MASVS v2 and MASTG, Coinspect Wallet Security Framework; static analysis (Semgrep with project rules, mobsfscan, repository checks, Dontrust); secret scanning of the tree and of the Git history (Gitleaks); static analysis of the compiled application (MobSF, own binary checks).",505        "Findings: one record per problem with root cause, severity (higher of the CVSS v3.1 band and the wallet-impact class of security/policies/severity-policy.md), location, status, fix commit and regression test. Tool findings are triaged in security/policies/triage.json with a written justification.",506        "Release gate (security/policies/release-gate.json): blocks on an unresolved critical or high finding, a failed cryptographic test, a fuzzing crash, a secret, a failed or missing required tool.",507        "No source code leaves the project's machines: Semgrep and mobsfscan run with the network denied, MobSF runs in a container without network on the project's server, rule packs and vectors are downloaded as public files only.",508    ])509510    d.h1("3. Tools and real coverage")511    rows = []512    for t_ in doc["tools"]:513        rows.append([t_["tool"], t_["status"], short(t_.get("version"), 60) or "—", fmt_duration(t_.get("duration_s")),514                     fmt_int(len(t_.get("findings", []))), short(t_.get("reason"), 140) if t_["status"] != "RUN" else ""])515    d.table(["Tool", "Status", "Version", "Duration", "Findings", "Reason when not run"], rows, "small")516    for t_ in doc["tools"]:517        if t_.get("coverage"):518            d.h3(t_["tool"])519            d.p(t_["coverage"])520            scalars = [(k.replace("_", " "), fmt_int(v) if isinstance(v, (int, float)) and not isinstance(v, bool) else short(v, 160))521                       for k, v in t_.get("metrics", {}).items() if not isinstance(v, (list, dict)) and v not in ("", None)]522            if scalars and t_["tool"] not in ("swift-audit", "engine-tests"):523                d.kv(scalars[:16])524525    d.h1("4. Cryptographic validation")526    d.p("The cryptographic engine is written from scratch; this part of the audit has priority. The complete tables are in CRYPTOGRAPHIC_VALIDATION_REPORT.pdf.")527    crypto_sections(d, doc, detailed=False)528529    d.h1("5. Wallet and application security")530    d.p("Post-quantum protection concerns local storage (vault), backups, device-to-device transfers and the separate identity. It is assessed "531        "separately from the security of Bitcoin and Ethereum transactions, which rest on secp256k1, on the protocols themselves and on the "532        "review-before-sign logic of the wallet service.")533    for name, label in (("wallet-audit", "Wallet audit (key storage, authentication, backup, network, transactions)"),534                        ("owasp-masvs", "OWASP MASVS v2"), ("owasp-mastg", "OWASP MASTG (iOS tests)"), ("coinspect-wsf", "Coinspect Wallet Security Framework")):535        r = tools.get(name)536        if not r:537            continue538        d.h2(label)539        if r["status"] != "RUN":540            d.warn(f"{r['status']} — {short(r.get('reason'), 300)}")541            continue542        m = r["metrics"]543        d.p(short(r.get("coverage"), 900))544        d.table(["Items", "Pass", "Partial", "Fail", "Not applicable", "Not assessed", "Stale evidence"],545                [[fmt_int(m.get("total")), fmt_int(m.get("pass")), fmt_int(m.get("partial")), fmt_int(m.get("fail")), fmt_int(m.get("not_applicable")),546                  fmt_int(m.get("not_assessed")), fmt_int(m.get("stale_evidence"))]], "num")547        items = m.get("items", [])548        shown = [i for i in items if i.get("verdict") in ("fail", "partial")] if name != "wallet-audit" else items549        if name == "owasp-masvs":550            shown = items551        if shown:552            rows = [[i.get("id", ""), short(i.get("title"), 90), i.get("verdict", ""), short(i.get("rationale"), 330)] for i in shown]553            d.table(["Item", "Title", "Verdict", "Rationale (abridged)"], rows, "small")554            if name in ("owasp-mastg", "coinspect-wsf"):555                d.p("Only the items rated fail or partial are listed; the complete mapping with evidence is in security/policies/ and in the results file.")556    dt = tools.get("dontrust")557    if dt:558        d.h2("Dontrust")559        d.p(f"{dt['status']} — {short(dt.get('coverage') or dt.get('reason'), 900)}")560    for name, label in (("static-checks", "Repository static checks"), ("binary-checks", "Binary checks of the compiled application")):561        r = tools.get(name)562        if not r:563            continue564        d.h2(label)565        if r["status"] != "RUN":566            d.p(f"{r['status']} — {short(r.get('reason'), 300)}")567            continue568        rows = [[short(t_.get("name"), 130), "not applicable" if (t_.get("skipped") and not t_.get("cases")) else ("FAILED" if t_.get("failed") else "passed"), short(t_.get("note"), 200)]569                for t_ in r.get("tests", [])]570        d.table(["Check", "Result", "Evidence"], rows, "small")571    mob = tools.get("mobsf")572    if mob:573        d.h2("MobSF (compiled application)")574        if mob["status"] == "RUN":575            d.p(short(mob.get("coverage"), 900))576            d.kv([(k.replace("_", " "), short(v, 160)) for k, v in mob["metrics"].items() if not isinstance(v, (list, dict))][:18])577        else:578            d.p(f"{mob['status']} — {short(mob.get('reason'), 300)}")579580    d.h1("6. Findings")581    real = [f for f in findings if f.get("status") != "false-positive"]582    fp = [f for f in findings if f.get("status") == "false-positive"]583    d.p(f"{fmt_int(len(real))} findings other than false positives. Identifiers QYV-* are entries of the findings register (security/audit/findings); "584        "identifiers QY-<TOOL>-* are tool results triaged in security/policies/triage.json.")585    d.table(["Id", "Severity", "Status", "CVSS", "Title", "Location", "Fix commit"], finding_rows(real), "small")586    d.h2("Fixes made")587    fixed = [f for f in findings if f.get("status") == "fixed"]588    if fixed:589        d.table(["Id", "Severity", "Title", "Fix commit", "Regression test"],590                [[f["id"], f["severity"], short(f["title"], 130), f.get("fix_commit") or "—", short(f.get("regression_test"), 150) or short(f.get("resolution_note"), 150)] for f in fixed], "small")591    else:592        d.p("No fixed finding recorded.")593    d.h2("Residual risks: open and accepted findings")594    residual = [f for f in findings if f.get("status") in ("open", "accepted-risk")]595    d.table(["Id", "Severity", "Status", "Title", "Recommendation (abridged)"],596            [[f["id"], f["severity"], f["status"], short(f["title"], 120), short(f.get("recommendation") or f.get("triage"), 240)] for f in residual], "small")597    d.h2("Details of the register findings")598    finding_details(d, [f for f in real if f["id"].startswith("QYV-")])599    if fp:600        d.h2("Tool results triaged as false positives")601        by_tool = defaultdict(int)602        for f in fp:603            by_tool[f.get("tool", "?")] += 1604        d.table(["Tool", "False positives"], [[k, fmt_int(v)] for k, v in sorted(by_tool.items())], "num")605        d.p("Each one carries its justification in the results file (field 'triage').")606607    d.h1("7. Limits, release gate and recommendations")608    limits_and_recommendations(d, doc)609610    d.h1("8. Reproduction")611    d.items([612        "Install the pinned tools: security/audit/install-tools.sh",613        "Quick audit: Scripts/security-audit.sh — full audit: Scripts/security-audit.sh --full --nodes \"M3U96a M3U96b\"",614        "Random campaigns are reproducible from the seeds recorded in SECURITY_AUDIT_RESULTS.json (QY_AUDIT_SEED / QY_AUDIT_REPLAY_SEED).",615        "Tool versions are pinned in security/policies/tools.json; vector files in security/vectors/MANIFEST.json.",616    ])617    return d618619620def build_crypto(doc: dict) -> Doc:621    a = doc["audit"]622    d = Doc("QYVORA — Cryptographic Validation Report", f"Version {a['wallet_version']} ({a['wallet_build']}) · commit {a['git_commit'][:12]} · {a['date_utc'][:10]} · {a['mode']} run")623    d.h1("1. Status")624    header_block(d, doc, "Release gate (whole audit)")625    d.p("This report gives the complete results of the cryptographic part of the audit: conformance to the standards with the official "626        "vectors, edge-case vectors, differential testing, mathematical invariants, fuzzing, timing and side-channel evidence, entropy and "627        "memory handling. Algorithms implemented from scratch in Swift: SHA-2, SHA-3/SHAKE/cSHAKE/KMAC, HMAC, HKDF, PBKDF2, RIPEMD-160, "628        "BLAKE2b, Argon2, AES-GCM, ChaCha20-Poly1305, secp256k1 (ECDSA, BIP-340), ML-KEM (FIPS 203), ML-DSA (FIPS 204), SLH-DSA (FIPS 205). "629        "X25519 is Apple CryptoKit's, used as the classical half of the hybrid exchange.")630    crypto = [f for f in doc["findings"] if f.get("area") in ("crypto", "fuzzing") or f["id"].startswith(("QYV-CRY", "QYV-AUD", "QYV-FUZ", "QYV-DIF", "QY-TIMING", "QY-CTMC"))]631    crypto = [f for f in crypto if f.get("status") != "false-positive"]632    d.h1("2. Results")633    crypto_sections(d, doc, detailed=True)634    d.h1("3. Cryptographic findings")635    if crypto:636        d.table(["Id", "Severity", "Status", "CVSS", "Title", "Location", "Fix commit"], finding_rows(crypto), "small")637        finding_details(d, crypto)638    else:639        d.p("No cryptographic finding recorded.")640    d.h1("4. Limits and recommendations")641    limits_and_recommendations(d, doc)642    return d643644645# --- renderers -----------------------------------------------------------------------------------646647def md_escape(text: str) -> str:648    return str(text).replace("|", "\\|").replace("\n", " ")649650651def render_md(d: Doc) -> str:652    out = [f"# {d.title}", "", f"_{d.subtitle}_", ""]653    for b in d.blocks:654        kind = b[0]655        if kind == "h1":656            out += ["", f"## {b[1]}", ""]657        elif kind == "h2":658            out += ["", f"### {b[1]}", ""]659        elif kind == "h3":660            out += ["", f"#### {b[1]}", ""]661        elif kind == "p":662            out += [b[1], ""]663        elif kind == "note":664            out += [f"> **Status.** {b[1]}", ""]665        elif kind == "warn":666            out += [f"> **Attention.** {b[1]}", ""]667        elif kind == "list":668            out += [f"- {i}" for i in b[1]] + [""]669        elif kind == "kv":670            out += ["| | |", "|---|---|"] + [f"| **{md_escape(k)}** | {md_escape(v)} |" for k, v in b[1]] + [""]671        elif kind == "table":672            headers, rows = b[1], b[2]673            if not rows:674                out += ["_(no row)_", ""]675                continue676            out += ["| " + " | ".join(md_escape(h) for h in headers) + " |", "|" + "---|" * len(headers)]677            out += ["| " + " | ".join(md_escape(c) for c in r) + " |" for r in rows] + [""]678    out += ["---", "", "_Generated by security/audit/report/generate.py from SECURITY_AUDIT_RESULTS.json. Internal automated technical audit — not an independent certification._", ""]679    return "\n".join(out)680681682CSS = """683:root { --bg:#14151a; --panel:#1c1e26; --line:#2c2f3b; --text:#e6e7ee; --muted:#9a9db0; --accent:#8a7dff; --accent2:#5aa0ff; --ok:#57c79a; --bad:#ff6b7d; --warn:#f0b35a; }684* { box-sizing:border-box; }685html { background:var(--bg); }686body { margin:0 auto; max-width:1180px; padding:40px 34px 80px; background:var(--bg); color:var(--text);687  font:15px/1.55 -apple-system, "SF Pro Text", "Helvetica Neue", Helvetica, Arial, sans-serif; }688header.cover { border-bottom:1px solid var(--line); padding-bottom:22px; margin-bottom:26px; }689header.cover .brand { letter-spacing:.32em; font-size:12px; color:var(--accent); font-weight:600; }690header.cover h1 { font-size:30px; margin:10px 0 6px; font-weight:650; letter-spacing:-.01em; }691header.cover .sub { color:var(--muted); font-size:14px; }692h2 { font-size:21px; margin:44px 0 12px; padding-top:18px; border-top:1px solid var(--line); font-weight:650; }693h3 { font-size:16.5px; margin:30px 0 8px; color:#cfd0ff; font-weight:600; }694h4 { font-size:14px; margin:22px 0 6px; color:var(--accent2); font-weight:600; }695p { margin:8px 0 12px; }696ul { margin:8px 0 14px; padding-left:22px; } li { margin:4px 0; }697.note, .warn { border-left:3px solid var(--accent); background:var(--panel); padding:12px 16px; margin:14px 0; border-radius:0 6px 6px 0; }698.warn { border-left-color:var(--warn); }699table { border-collapse:collapse; width:100%; margin:10px 0 18px; font-size:13.5px; }700th, td { text-align:left; vertical-align:top; padding:6px 9px; border-bottom:1px solid var(--line); overflow-wrap:anywhere; }701th { color:var(--muted); font-weight:600; font-size:12px; text-transform:uppercase; letter-spacing:.04em; border-bottom:1px solid #3a3d4d; }702table.small { font-size:12.5px; } table.small td, table.small th { padding:4px 7px; }703table.kv td:first-child { color:var(--muted); width:230px; white-space:nowrap; }704table.num td:not(:first-child) { font-variant-numeric:tabular-nums; }705.s-critical, .s-high, .v-FAILED, .v-fail { color:var(--bad); font-weight:600; }706.s-medium, .v-partial, .v-NOT { color:var(--warn); }707.s-fixed, .v-passed, .v-pass, .v-RUN, .v-PASSED { color:var(--ok); }708footer { margin-top:50px; padding-top:16px; border-top:1px solid var(--line); color:var(--muted); font-size:12.5px; }709code { font:12.5px ui-monospace, "SF Mono", Menlo, monospace; }710@page { size:A4; margin:16mm 14mm 18mm; @bottom-center { content:"QYVORA — internal technical audit, not an independent certification · page " counter(page) " / " counter(pages); font-size:8pt; color:#666; } }711@media print {712  :root { --bg:#fff; --panel:#f3f2fb; --line:#d6d6e2; --text:#16171d; --muted:#565a6e; --accent:#4b3fd6; --accent2:#2f62c9; --ok:#177a52; --bad:#b4233a; --warn:#8a5a00; }713  html, body { background:#fff; }714  body { max-width:none; padding:0; font-size:9.6pt; line-height:1.42; }715  header.cover h1 { font-size:20pt; } h2 { font-size:14pt; margin-top:22pt; break-after:avoid; } h3 { font-size:11.5pt; color:#3b32b0; break-after:avoid; } h4 { font-size:10pt; break-after:avoid; }716  table { font-size:8.2pt; } table.small { font-size:7.4pt; } th { font-size:7pt; }717  tr { break-inside:avoid; } .note, .warn { break-inside:avoid; }718}719"""720721VERDICT_WORDS = ("FAILED", "passed", "PASSED", "RUN", "NOT RUN", "fail", "pass", "partial", "critical", "high", "medium", "fixed", "LEAK CONFIRMED")722723724def cell_html(text: str) -> str:725    e = html.escape(str(text))726    t = str(text).strip()727    if t in ("critical", "high", "medium"):728        return f'<span class="s-{t}">{e}</span>'729    if t == "fixed":730        return f'<span class="s-fixed">{e}</span>'731    if t in ("FAILED", "fail", "LEAK CONFIRMED", "ABOVE THE REVIEWED MAXIMUM"):732        return f'<span class="v-FAILED">{e}</span>'733    if t in ("passed", "pass", "RUN", "PASSED", "ok", "no evidence of leak"):734        return f'<span class="v-passed">{e}</span>'735    if t in ("NOT RUN", "partial", "not run"):736        return f'<span class="v-NOT">{e}</span>'737    return e738739740def render_html(d: Doc) -> str:741    out = ['<!doctype html>', '<html lang="en"><head><meta charset="utf-8">', f"<title>{html.escape(d.title)}</title>",742           '<meta name="viewport" content="width=device-width, initial-scale=1">', f"<style>{CSS}</style></head><body>",743           f'<header class="cover"><div class="brand">QYVORA</div><h1>{html.escape(d.title.split("— ", 1)[-1])}</h1><div class="sub">{html.escape(d.subtitle)}</div></header>']744    for b in d.blocks:745        kind = b[0]746        if kind in ("h1", "h2", "h3"):747            tag = {"h1": "h2", "h2": "h3", "h3": "h4"}[kind]748            out.append(f"<{tag}>{html.escape(b[1])}</{tag}>")749        elif kind == "p":750            out.append(f"<p>{html.escape(b[1])}</p>")751        elif kind in ("note", "warn"):752            out.append(f'<div class="{kind}">{html.escape(b[1])}</div>')753        elif kind == "list":754            out.append("<ul>" + "".join(f"<li>{html.escape(i)}</li>" for i in b[1]) + "</ul>")755        elif kind == "kv":756            out.append('<table class="kv">' + "".join(f"<tr><td>{html.escape(str(k))}</td><td>{cell_html(v)}</td></tr>" for k, v in b[1]) + "</table>")757        elif kind == "table":758            headers, rows, opt = b[1], b[2], b[3]759            if not rows:760                out.append("<p><em>(no row)</em></p>")761                continue762            out.append(f'<table class="{opt.get("class", "")}"><thead><tr>' + "".join(f"<th>{html.escape(h)}</th>" for h in headers) + "</tr></thead><tbody>"763                       + "".join("<tr>" + "".join(f"<td>{cell_html(c)}</td>" for c in r) + "</tr>" for r in rows) + "</tbody></table>")764    out.append("<footer>Generated by security/audit/report/generate.py from SECURITY_AUDIT_RESULTS.json — every figure comes from that file. "765               "Internal automated technical audit; not an independent certification; no claim of absolute security.</footer></body></html>")766    return "\n".join(out)767768769def to_pdf(html_path: Path, pdf_path: Path) -> tuple[bool, str]:770    """Renders with a local tool: WeasyPrint, else headless Chrome/Chromium, else wkhtmltopdf. Nothing is sent anywhere."""771    weasy = shutil.which("weasyprint")772    if weasy:773        p = subprocess.run([weasy, "-q", str(html_path), str(pdf_path)], capture_output=True, text=True, timeout=900)774        if p.returncode == 0 and pdf_path.exists():775            version = subprocess.run([weasy, "--version"], capture_output=True, text=True).stdout.strip()776            return True, version or "WeasyPrint"777    for chrome in ("/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", "/Applications/Chromium.app/Contents/MacOS/Chromium",778                   shutil.which("chromium") or "", shutil.which("google-chrome") or ""):779        if chrome and Path(chrome).exists():780            p = subprocess.run([chrome, "--headless=new", "--disable-gpu", "--no-pdf-header-footer", f"--print-to-pdf={pdf_path}", html_path.as_uri()],781                               capture_output=True, text=True, timeout=900)782            if p.returncode == 0 and pdf_path.exists():783                return True, "headless Chrome"784    wk = shutil.which("wkhtmltopdf")785    if wk:786        p = subprocess.run([wk, "--quiet", "--print-media-type", str(html_path), str(pdf_path)], capture_output=True, text=True, timeout=900)787        if p.returncode == 0 and pdf_path.exists():788            return True, "wkhtmltopdf"789    return False, "no local PDF renderer found (install one: brew install weasyprint)"790791792def generate(doc: dict, out_dir: Path | None = None) -> list[dict]:793    out_dir = out_dir or REPORTS794    out_dir.mkdir(parents=True, exist_ok=True)795    written = []796    main_doc, crypto_doc = build_main(doc), build_crypto(doc)797    (out_dir / "SECURITY_AUDIT_REPORT.md").write_text(render_md(main_doc))798    written.append({"file": "SECURITY_AUDIT_REPORT.md", "status": "written"})799    main_html = out_dir / "SECURITY_AUDIT_REPORT.html"800    main_html.write_text(render_html(main_doc))801    written.append({"file": "SECURITY_AUDIT_REPORT.html", "status": "written"})802    crypto_html = out_dir / "CRYPTOGRAPHIC_VALIDATION_REPORT.html"803    crypto_html.write_text(render_html(crypto_doc))804    written.append({"file": "CRYPTOGRAPHIC_VALIDATION_REPORT.html", "status": "written"})805    for source, name in ((main_html, "SECURITY_AUDIT_REPORT.pdf"), (crypto_html, "CRYPTOGRAPHIC_VALIDATION_REPORT.pdf")):806        ok, how = to_pdf(source, out_dir / name)807        written.append({"file": name, "status": "written" if ok else "NOT WRITTEN", "renderer" if ok else "reason": how})808    return written809810811BEGIN_MARK = "<!-- BEGIN LAST AUDIT RUN (generated by security/audit/report/generate.py from SECURITY_AUDIT_RESULTS.json — do not edit by hand) -->"812END_MARK = "<!-- END LAST AUDIT RUN -->"813814815def update_docs(doc: dict) -> list[dict]:816    """Rewrites the generated "last audit run" block of SECURITY.md and docs/THREAT_MODEL.md from the results document."""817    a, g, s = doc["audit"], doc["gate"], doc["summary"]["findings"]818    matrix = s["by_severity_and_status"]819    open_crit, open_high = matrix.get("critical", {}).get("open", 0), matrix.get("high", {}).get("open", 0)820    block = "\n".join([821        BEGIN_MARK,822        f"**Last committed audit run.** {a['date_utc']} · QYVORA {a['wallet_version']} (build {a['wallet_build']}) · commit `{a['git_commit'][:12]}`"823        + (" (working tree not clean)" if a["git_dirty"] else "") + f" · {a['mode']} run on {a['host']} · release gate: "824        + ("**passed**" if g["passed"] else "**failed**") + f" ({len(g['blockers'])} blocking condition(s), {len(g['warnings'])} warning(s)) · findings: "825        f"{s['open']} open ({open_crit} critical, {open_high} high), {s['fixed']} fixed, {s['accepted_risk']} accepted risk. "826        "Internal automated technical audit — not an independent certification; no independent cryptographic review yet. "827        "Details: [`security/reports/SECURITY_AUDIT_REPORT.md`](security/reports/SECURITY_AUDIT_REPORT.md).",828        END_MARK,829    ])830    out = []831    targets = [(REPO / "SECURITY.md", "## What the post-quantum cryptography covers", block),832               (REPO / "docs" / "THREAT_MODEL.md", "### 8.2 Where the results are", block.replace("](security/reports/", "](../security/reports/"))]833    for path, anchor, text in targets:834        if not path.exists():835            out.append({"file": str(path.relative_to(REPO)), "status": "NOT WRITTEN", "reason": "file missing"})836            continue837        content = path.read_text()838        if BEGIN_MARK in content and END_MARK in content:839            start, end = content.index(BEGIN_MARK), content.index(END_MARK) + len(END_MARK)840            content = content[:start] + text + content[end:]841        elif anchor in content:842            i = content.index(anchor)843            content = content[:i] + text + "\n\n" + content[i:]844        else:845            out.append({"file": str(path.relative_to(REPO)), "status": "NOT WRITTEN", "reason": "anchor heading not found"})846            continue847        path.write_text(content)848        out.append({"file": str(path.relative_to(REPO)), "status": "updated"})849    return out850851852if __name__ == "__main__":853    path = Path(sys.argv[1]) if len(sys.argv) > 1 else REPORTS / "SECURITY_AUDIT_RESULTS.json"854    for item in generate(json.loads(path.read_text())):855        print(item)856
Files main
Menu

Theme