Repository Public
1#!/usr/bin/env python32# =============================================================================3# SP BOUCHER | SOFTWARE & RESEARCH4# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5# =============================================================================6#7# Project : QYVORA8# File : security/audit/runners/frameworks.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"""Framework assessments of the QYVORA audit: Coinspect Wallet Security Framework (WSC + WSB),43OWASP MASVS v2 with the MASTG iOS tests, the wallet audit of the owner's brief, and Dontrust.4445The assessments live in `security/policies/*.json`. They are written by a reviewer who read the46code; this runner does not trust them blindly. At every run it4748 1. verifies each evidence reference (`path:line` + the text expected there; the reference follows49 the text when it moved inside its file): evidence whose text is gone downgrades its item to50 `not-assessed` and is counted as stale;51 2. evaluates the automated checks attached to an item (regular expressions over the sources,52 property-list keys): a check that is not met changes the verdict and produces a finding,53 unless it tracks a gap already recorded as a finding (then it reports whether the gap is54 still there);55 3. counts the verdicts. Every number in the reports comes from this count.5657Dontrust (https://github.com/HodleHub/dontrust, pinned commit, MIT) is a local, regex-based source58auditor for wallets. It is installed under `security/.tools/dontrust` by59`python3 security/audit/runners/frameworks.py --install-dontrust` (download of the pinned commit,60SHA-256 of every file checked against `security/policies/dontrust.json`, lock-file install without61install scripts) and run on a copy of the wallet sources. It only reads files; nothing leaves the62machine. When it is not installed the result is NOT RUN, never a pass.6364Standalone: python3 security/audit/runners/frameworks.py [--install-dontrust] [--json]65"""6667from __future__ import annotations6869import fnmatch70import hashlib71import io72import json73import plistlib74import re75import shutil76import sys77import tarfile78import tempfile79import time80import urllib.request81from pathlib import Path8283sys.path.insert(0, str(Path(__file__).resolve().parents[1]))84from lib.common import (FAILED, NOT_RUN, POLICIES, REPO, RUN, TOOLS_HOME, Context, finding, # noqa: E40285 load_json, not_run, rel, run_cmd, tool_result, write_json)8687VERDICTS = ["pass", "fail", "partial", "not-applicable", "not-assessed"]88SEVERITY_RANK = {"info": 0, "low": 1, "medium": 2, "high": 3, "critical": 4}89EVIDENCE_WINDOW = 6 # lines searched around the recorded line for the expected text9091FRAMEWORKS = [92 # (tool name, policy file, list key)93 ("coinspect-wsf", "coinspect-wsf.json"),94 ("owasp-masvs", "masvs-v2.json"),95 ("owasp-mastg", "mastg-tests.json"),96 ("wallet-audit", "wallet-audit.json"),97]9899100# --------------------------------------------------------------------------------------------101# Evidence and checks102# --------------------------------------------------------------------------------------------103104_file_cache: dict[str, list[str] | None] = {}105106107def _lines(path: str) -> list[str] | None:108 if path not in _file_cache:109 p = REPO / path110 try:111 _file_cache[path] = p.read_text(errors="replace").splitlines() if p.is_file() else None112 except OSError:113 _file_cache[path] = None114 return _file_cache[path]115116117def verify_evidence(ev) -> tuple[bool, str, str]:118 """An evidence entry is a string or {"ref": "path:line", "contains": "text"}.119120 The text is the evidence; the line number is where it was when the assessment was written.121 Returns (valid, problem, current reference). When the text has moved inside its file the122 reference follows it; when the text is gone the evidence is stale. Strings that are not a123 `path:line` reference (test names, "runner:<tool> …" pointers) are kept as they are."""124 ref = ev if isinstance(ev, str) else ev.get("ref", "")125 contains = None if isinstance(ev, str) else ev.get("contains")126 m = re.match(r"^([A-Za-z0-9_.+/@ -]+\.[A-Za-z0-9]+):(\d+)$", ref)127 if not m:128 return True, "", ref129 path, line = m.group(1), int(m.group(2))130 lines = _lines(path)131 if lines is None:132 return False, f"{path}: file missing", ref133 if not contains:134 if line < 1 or line > len(lines):135 return False, f"{ref}: line beyond end of file ({len(lines)} lines)", ref136 return True, "", ref137 lo, hi = max(0, line - 1 - EVIDENCE_WINDOW), min(len(lines), line + EVIDENCE_WINDOW)138 if any(contains in text for text in lines[lo:hi]):139 return True, "", ref140 for n, text in enumerate(lines, 1):141 if contains in text:142 return True, "", f"{path}:{n}"143 return False, f"{ref}: the expected text is no longer in the file", ref144145146def _glob_files(globs: list[str], exclude: list[str]) -> list[Path]:147 out: list[Path] = []148 for g in globs:149 for p in sorted(REPO.glob(g)):150 r = rel(p)151 if p.is_file() and not any(fnmatch.fnmatch(r, e) for e in exclude):152 out.append(p)153 return out154155156def run_check(check: dict) -> dict:157 """Evaluates one automated check. Returns {met, detail, locations}."""158 kind = check.get("type", "grep")159 expect = check.get("expect", "present")160 if kind == "grep":161 files = _glob_files(check["globs"], check.get("exclude", []))162 rx = re.compile(check["pattern"])163 hits: list[str] = []164 for f in files:165 try:166 for n, text in enumerate(f.read_text(errors="replace").splitlines(), 1):167 if rx.search(text):168 hits.append(f"{rel(f)}:{n}")169 except OSError:170 continue171 if not files and check.get("require_files", True):172 return {"met": None, "detail": "no file matched the globs", "locations": []}173 met = bool(hits) if expect == "present" else not hits174 return {"met": met, "detail": f"{len(hits)} match(es) in {len(files)} file(s)", "locations": hits[:20]}175 if kind == "plist":176 p = REPO / check["path"]177 if not p.is_file():178 return {"met": None, "detail": f"{check['path']} missing", "locations": []}179 try:180 data = plistlib.loads(p.read_bytes())181 except Exception as e: # malformed property list182 return {"met": None, "detail": f"cannot parse {check['path']}: {e}", "locations": []}183 present = check["key"] in data184 value = data.get(check["key"])185 if expect == "present":186 met = present187 elif expect == "absent":188 met = not present189 elif expect == "absent-or-false":190 met = (not present) or value is False191 else: # {"equals": value}192 met = present and value == expect.get("equals")193 return {"met": met, "detail": f"{check['key']} = {value!r}" if present else f"{check['key']} absent",194 "locations": [check["path"]]}195 return {"met": None, "detail": f"unknown check type {kind}", "locations": []}196197198def assess(tool: str, items: list[dict]) -> tuple[list[dict], list[dict], dict]:199 """Applies evidence verification and checks to every item. Returns (items, findings, counts)."""200 out, findings = [], []201 counts = {v.replace("-", "_"): 0 for v in VERDICTS}202 counts.update(stale_evidence=0, checks_run=0, checks_unmet=0, checks_inconclusive=0, unreferenced_failures=0)203 for item in items:204 it = dict(item)205 verdict = it.get("verdict", "not-assessed")206 if verdict not in VERDICTS:207 verdict = "not-assessed"208 it["runner_note"] = "unknown verdict in the policy file"209 notes = []210 # 1. evidence211 stale, current = [], []212 for ev in it.get("evidence", []):213 ok, why, now_ref = verify_evidence(ev)214 if not ok:215 stale.append(why)216 current.append(now_ref if isinstance(ev, str) else {**ev, "ref": now_ref})217 if current:218 it["evidence"] = current219 if stale:220 counts["stale_evidence"] += len(stale)221 notes.append("stale evidence: " + "; ".join(stale))222 if verdict in ("pass", "partial"):223 verdict = "not-assessed"224 # 2. checks225 results = []226 for check in it.get("checks", []):227 r = run_check(check)228 counts["checks_run"] += 1229 r.update(id=check.get("id", ""), description=check.get("description", ""))230 results.append(r)231 if r["met"] is None:232 counts["checks_inconclusive"] += 1233 notes.append(f"check {r['id']} inconclusive: {r['detail']}")234 if verdict == "pass":235 verdict = "not-assessed"236 elif not r["met"]:237 counts["checks_unmet"] += 1238 if check.get("finding"):239 # a known gap, already reflected in the declared verdict and recorded as a finding240 r["known_finding"] = check["finding"]241 notes.append(f"check {r['id']} not met (known: {check['finding']})")242 continue243 verdict = check.get("on_unmet", it.get("on_unmet", "fail"))244 notes.append(f"check {r['id']} not met: {r['detail']}")245 if verdict in ("fail", "partial") and check.get("severity"):246 findings.append(finding(247 tool=tool, rule=f"{it['id']}/{r['id']}", severity=check["severity"],248 title=check.get("description") or f"{it['id']}: automated check not met",249 location=(r["locations"] or [""])[0], area=check.get("area", "app"),250 masvs=it.get("masvs", it["id"] if it["id"].startswith("MASVS-") else ""),251 cwe=check.get("cwe", ""), description=f"{it.get('title', '')} — {r['detail']}. "252 + check.get("explanation", ""), recommendation=check.get("recommendation", ""),253 evidence=", ".join(r["locations"])))254 elif check.get("finding"):255 r["known_finding"] = check["finding"]256 notes.append(f"check {r['id']} is now met: review whether {check['finding']} can be closed and update the verdict")257 if results:258 it["check_results"] = results259 # 3. failing items of severity >= medium must point to a finding260 if verdict == "fail" and SEVERITY_RANK.get(it.get("severity", "info"), 0) >= 2:261 refs = [it.get("finding")] if isinstance(it.get("finding"), str) else (it.get("finding") or [])262 refs += [c.get("finding") for c in it.get("checks", []) if c.get("finding")]263 auto = any(f["rule"].startswith(it["id"] + "/") for f in findings)264 missing = [r for r in refs if r and not (REPO / "security/audit/findings" / f"{r}.json").is_file()]265 if (not refs and not auto) or missing:266 counts["unreferenced_failures"] += 1267 notes.append("failing item of severity >= medium without a recorded finding"268 + (f" (missing: {', '.join(missing)})" if missing else ""))269 if notes:270 it["runner_note"] = "; ".join(filter(None, [it.get("runner_note", "")] + notes))271 it["declared_verdict"] = item.get("verdict", "not-assessed")272 it["verdict"] = verdict273 counts[verdict.replace("-", "_")] += 1274 out.append(it)275 return out, findings, counts276277278def run_framework(tool: str, file_name: str) -> dict:279 start = time.time()280 policy = load_json(POLICIES / file_name)281 if not policy:282 return tool_result(tool=tool, category="framework", status=FAILED,283 reason=f"security/policies/{file_name} is missing or not valid JSON")284 items, findings, counts = assess(tool, policy.get("items", []))285 metrics = dict(counts)286 metrics["total"] = len(items)287 metrics["source"] = policy.get("source", {})288 metrics["items"] = [289 {k: it.get(k) for k in ("id", "title", "group", "verdict", "declared_verdict", "severity", "scope", "rationale",290 "gap", "finding", "evidence", "check_results", "runner_note", "masvs", "residual_risk")291 if it.get(k) not in (None, "", [])}292 for it in items293 ]294 status = FAILED if counts["unreferenced_failures"] else RUN295 return tool_result(296 tool=tool, category="framework", status=status,297 version=str(policy.get("source", {}).get("version", "")),298 reason="a failing item of severity >= medium has no recorded finding" if status == FAILED else "",299 command=f"python3 security/audit/runners/frameworks.py ({file_name})",300 duration_s=time.time() - start, coverage=policy.get("coverage", ""),301 metrics=metrics, findings=findings, artifacts=[f"security/policies/{file_name}"])302303304# --------------------------------------------------------------------------------------------305# Dontrust306# --------------------------------------------------------------------------------------------307308DONTRUST_HOME = TOOLS_HOME / "dontrust"309SCAN_ROOTS = ["Package.swift", "Sources", "App", "Scripts"]310SCAN_SKIP_DIRS = {".build", "build", "DerivedData", "Assets.xcassets", "node_modules", ".swiftpm"}311SCAN_SKIP_SUFFIXES = (".xcodeproj", ".xcworkspace", ".png", ".jpg", ".pdf", ".gz", ".ipa", ".xcarchive")312313314def _sha256(path: Path) -> str:315 return hashlib.sha256(path.read_bytes()).hexdigest()316317318def install_dontrust() -> tuple[bool, str]:319 """Downloads the pinned commit, verifies every file against the manifest, installs the locked320 dependencies without running install scripts and compiles the TypeScript sources."""321 policy = load_json(POLICIES / "dontrust.json") or {}322 pin = policy.get("tool", {})323 commit, manifest = pin.get("commit"), pin.get("files_sha256", {})324 if not commit or not manifest:325 return False, "security/policies/dontrust.json has no pinned commit or file manifest"326 node, pnpm = shutil.which("node"), shutil.which("pnpm")327 if not node or not pnpm:328 return False, "node (>= 20) and pnpm are required to build Dontrust"329 url = pin["archive_url"].replace("{commit}", commit)330 req = urllib.request.Request(url, headers={"User-Agent": "qyvora-audit"})331 try:332 blob = urllib.request.urlopen(req, timeout=120).read()333 except Exception as e:334 return False, f"download failed: {e}"335 staging = Path(tempfile.mkdtemp(prefix="dontrust-", dir=str(TOOLS_HOME if TOOLS_HOME.exists() else REPO / "security")))336 try:337 with tarfile.open(fileobj=io.BytesIO(blob), mode="r:gz") as tar:338 tar.extractall(staging, filter="data")339 roots = [p for p in staging.iterdir() if p.is_dir()]340 if len(roots) != 1:341 return False, "unexpected archive layout"342 src = roots[0]343 # keep only the files of the manifest, each with the recorded SHA-256344 for p in sorted(src.rglob("*")):345 if p.is_file() or p.is_symlink():346 r = str(p.relative_to(src))347 if p.is_symlink() or r not in manifest:348 p.unlink()349 for r, digest in manifest.items():350 f = src / r351 if not f.is_file():352 return False, f"file of the manifest missing from the archive: {r}"353 if _sha256(f) != digest:354 return False, f"SHA-256 mismatch for {r}: the pinned commit does not match the reviewed content"355 if DONTRUST_HOME.exists():356 shutil.rmtree(DONTRUST_HOME)357 DONTRUST_HOME.parent.mkdir(parents=True, exist_ok=True)358 shutil.move(str(src), str(DONTRUST_HOME))359 finally:360 shutil.rmtree(staging, ignore_errors=True)361 code, out, err, _ = run_cmd([pnpm, "install", "--frozen-lockfile", "--ignore-scripts"], cwd=DONTRUST_HOME, timeout=600)362 if code != 0:363 return False, "pnpm install failed: " + (err or out)[-500:]364 tsc = DONTRUST_HOME / "node_modules" / "typescript" / "bin" / "tsc"365 code, out, err, _ = run_cmd([node, str(tsc), "-p", "tsconfig.json"], cwd=DONTRUST_HOME, timeout=600)366 if code != 0 or not (DONTRUST_HOME / "dist" / "cli.js").is_file():367 return False, "TypeScript build failed: " + (err or out)[-500:]368 (DONTRUST_HOME / ".installed-commit").write_text(commit + "\n")369 return True, f"Dontrust {pin.get('version', '')} ({commit[:12]}) installed in {rel(DONTRUST_HOME)}"370371372def _stage_sources(dest: Path) -> int:373 """Copies the wallet sources (engine, services, application, scripts) into `dest`."""374 n = 0375 for root in SCAN_ROOTS:376 src = REPO / root377 if src.is_file():378 shutil.copy2(src, dest / root)379 n += 1380 continue381 for p in sorted(src.rglob("*")) if src.is_dir() else []:382 parts = p.relative_to(REPO).parts383 if any(part in SCAN_SKIP_DIRS or part.endswith(SCAN_SKIP_SUFFIXES) for part in parts):384 continue385 if p.is_file() and not p.is_symlink():386 target = dest / p.relative_to(REPO)387 target.parent.mkdir(parents=True, exist_ok=True)388 shutil.copy2(p, target)389 n += 1390 return n391392393def _triage(policy: dict, hit: dict) -> dict | None:394 for entry in policy.get("triage", []):395 if entry.get("rule") != hit.get("ruleId"):396 continue397 file = hit.get("file") or ""398 if entry.get("file") and not fnmatch.fnmatch(file, entry["file"]):399 continue400 if entry.get("snippet_contains") and entry["snippet_contains"] not in (hit.get("snippet") or ""):401 continue402 return entry403 return None404405406def run_dontrust(ctx: Context) -> dict:407 policy = load_json(POLICIES / "dontrust.json") or {}408 pin = policy.get("tool", {})409 coverage = policy.get("coverage", "")410 cli = DONTRUST_HOME / "dist" / "cli.js"411 node = shutil.which("node")412 marker = DONTRUST_HOME / ".installed-commit"413 if not pin:414 return not_run("dontrust", "wallet-analysis", "security/policies/dontrust.json is missing", coverage)415 if not node or not cli.is_file():416 return not_run("dontrust", "wallet-analysis",417 "Dontrust is not installed on this machine (run: python3 security/audit/runners/frameworks.py "418 "--install-dontrust; needs node >= 20 and pnpm)", coverage)419 installed = marker.read_text().strip() if marker.is_file() else ""420 if installed != pin.get("commit"):421 return not_run("dontrust", "wallet-analysis",422 f"the installed Dontrust ({installed[:12] or 'unknown'}) is not the pinned commit "423 f"{pin.get('commit', '')[:12]}; reinstall it", coverage)424 # the rule pack that runs must be the reviewed one425 for r, digest in pin.get("files_sha256", {}).items():426 if r.startswith("rules/") and ((DONTRUST_HOME / r).is_file() is False or _sha256(DONTRUST_HOME / r) != digest):427 return tool_result(tool="dontrust", category="wallet-analysis", status=FAILED, coverage=coverage,428 reason=f"installed rule file differs from the pinned manifest: {r}")429 start = time.time()430 work = Path(tempfile.mkdtemp(prefix="qy-dontrust-"))431 try:432 stage = work / "qyvora"433 stage.mkdir()434 staged = _stage_sources(stage)435 out_json = ctx.raw_path("dontrust.json")436 out_md = ctx.raw_path("dontrust.md")437 cmd = [node, str(cli), "scan", str(stage), "--json", str(out_json), "--out", str(out_md)]438 code, out, err, _ = run_cmd(cmd, cwd=work, timeout=600)439 if code != 0 or not out_json.is_file():440 return tool_result(tool="dontrust", category="wallet-analysis", status=FAILED, coverage=coverage,441 version=f"{pin.get('version', '')} ({pin.get('commit', '')[:12]})",442 reason="scan failed: " + (err or out)[-400:], duration_s=time.time() - start)443 raw = load_json(out_json) or {}444 finally:445 shutil.rmtree(work, ignore_errors=True)446447 findings, per_rule, triaged = [], {}, 0448 for hit in raw.get("findings", []):449 rule = hit.get("ruleId", "")450 per_rule[rule] = per_rule.get(rule, 0) + 1451 loc = f"{hit['file']}:{hit['line']}" if hit.get("file") else ""452 entry = _triage(policy, hit)453 f = finding(454 tool="dontrust", rule=rule, severity=hit.get("severity", "info"), title=hit.get("title", rule),455 location=loc, area="wallet", evidence=hit.get("snippet") or hit.get("note") or "",456 description=(hit.get("note") or "") + " — raw rule hit; a hit is a place to review, not a confirmed defect.",457 recommendation="Follow the rule's confirm steps (security/reports/raw/dontrust.md).",458 status=entry["status"] if entry else "open")459 if entry:460 triaged += 1461 f["triage"] = entry.get("justification", "")462 if entry.get("severity"):463 f["severity"] = entry["severity"]464 findings.append(f)465 skipped = raw.get("skippedRules", [])466 metrics = {467 "scanned_files": raw.get("scannedFiles"), "staged_files": staged, "rules_loaded": raw.get("scannedRules"),468 "rules_skipped": len(skipped), "rules_skipped_detail": skipped, "raw_hits": len(findings),469 "hits_per_rule": per_rule, "hits_triaged": triaged, "hits_untriaged": len(findings) - triaged,470 "node": run_cmd([node, "--version"])[1].strip(),471 "swift_scoped_rules": policy.get("swift_scoped_rules", []),472 }473 return tool_result(474 tool="dontrust", category="wallet-analysis", status=RUN,475 version=f"{pin.get('version', '')} ({pin.get('commit', '')[:12]})",476 command="node security/.tools/dontrust/dist/cli.js scan <copy of Package.swift Sources App Scripts> --json … --out …",477 duration_s=time.time() - start, coverage=coverage, metrics=metrics, findings=findings,478 artifacts=["security/reports/raw/dontrust.json", "security/reports/raw/dontrust.md", "security/policies/dontrust.json"])479480481# --------------------------------------------------------------------------------------------482# Entry points483# --------------------------------------------------------------------------------------------484485def run(ctx: Context) -> list[dict]:486 results = [run_framework(tool, file_name) for tool, file_name in FRAMEWORKS]487 if ctx.options.get("no_dontrust"):488 results.append(not_run("dontrust", "wallet-analysis", "disabled by option"))489 else:490 try:491 results.append(run_dontrust(ctx))492 except Exception as e: # never let one tool hide the others493 results.append(tool_result(tool="dontrust", category="wallet-analysis", status=FAILED, reason=f"runner error: {e}"))494 return results495496497def main(argv: list[str]) -> int:498 if "--install-dontrust" in argv:499 ok, message = install_dontrust()500 print(message)501 return 0 if ok else 1502 results = run(Context(mode="quick"))503 if "--json" in argv:504 print(json.dumps(results, indent=2, ensure_ascii=False))505 else:506 for r in results:507 m = r["metrics"]508 line = f"{r['tool']:<14} {r['status']:<8}"509 if "total" in m:510 line += (f" total {m['total']:>3} pass {m['pass']:>3} partial {m['partial']:>3} fail {m['fail']:>3} "511 f"n/a {m['not_applicable']:>3} not assessed {m['not_assessed']:>3} stale {m['stale_evidence']} "512 f"checks {m['checks_run']} (unmet {m['checks_unmet']})")513 elif "raw_hits" in m:514 line += f" files {m['scanned_files']} rules {m['rules_loaded']} hits {m['raw_hits']} untriaged {m['hits_untriaged']}"515 if r["reason"]:516 line += f" — {r['reason']}"517 print(line)518 for f in r["findings"]:519 print(f" [{f['severity']}/{f['status']}] {f['title']} {f['location']}")520 write_json(Context().raw_path("frameworks.json"), results)521 return 1 if any(r["status"] == FAILED for r in results) else 0522523524if __name__ == "__main__":525 sys.exit(main(sys.argv[1:]))526