SPB Git

Repository Public

common.py 8.5 KB 217 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# Project          : QYVORA7# File             : security/audit/lib/common.py8# Module           : Security9# Repository       : https://git.spboucher.ai/qyvora10# Project Website  : Not specified11# Created          : 2026-12-0412# Last Modified    : 2026-12-0413#14# Author           : Simon-Pierre Boucher15# Position         : Professor of Finance16# Institution      : Université du Québec en Outaouais (UQO)17# Organization     : SP Boucher18# Website          : https://spboucher.ai19# Git              : https://git.spboucher.ai20#21# Preferred Contact: contact@spboucher.ai22# Development      : dev@spboucher.ai23# Support          : support@spboucher.ai24# Security/Admin   : admin@spboucher.ai25#26# Copyright (c) 202627# Simon-Pierre Boucher28# All rights reserved where applicable. This file is governed by the29# applicable project license, copyright notices and relevant law.30# Existing third-party rights and notices remain unaffected.31#32# License          : None specified (no license file in this repository)33#34# Do not embed credentials, private keys, access tokens,35# certificates or confidential personal information.36#37# =============================================================================38# END OF SP BOUCHER SOURCE HEADER39# =============================================================================4041"""Shared helpers of the QYVORA security-audit engine (Python standard library only).4243Every tool runner returns one *tool result* dictionary built with `tool_result()`; every problem44is one *finding* dictionary built with `finding()`. The orchestrator merges them into45`security/reports/SECURITY_AUDIT_RESULTS.json`. Nothing here invents a value: a tool that cannot46run is recorded as NOT RUN with the reason, never as passed.47"""4849from __future__ import annotations5051import hashlib52import json53import os54import shutil55import subprocess56import time57from pathlib import Path5859REPO = Path(__file__).resolve().parents[3]60SECURITY = REPO / "security"61# QY_AUDIT_REPORTS redirects the whole output (results, reports, raw tool output) to another directory: used by the62# pre-push hook and by the server-side integration so that a check never rewrites the committed reports.63REPORTS = Path(os.environ["QY_AUDIT_REPORTS"]).resolve() if os.environ.get("QY_AUDIT_REPORTS") else SECURITY / "reports"64RAW = REPORTS / "raw"65POLICIES = SECURITY / "policies"66TOOLS_HOME = SECURITY / ".tools"  # local virtual environments and downloaded binaries (git-ignored)6768SEVERITIES = ["critical", "high", "medium", "low", "info"]69STATUSES = ["open", "fixed", "accepted-risk", "false-positive"]70RUN, NOT_RUN, FAILED = "RUN", "NOT RUN", "FAILED"717273class Context:74    """What a runner receives: the mode, the options and where to write raw output."""7576    def __init__(self, mode: str = "quick", options: dict | None = None):77        self.mode = mode  # "quick" or "full"78        self.options = options or {}79        self.repo = REPO80        self.raw = RAW81        RAW.mkdir(parents=True, exist_ok=True)8283    @property84    def full(self) -> bool:85        return self.mode == "full"8687    def raw_path(self, name: str) -> Path:88        return RAW / name899091def which(name: str) -> str | None:92    """Locate a tool: the audit's own tool directory first, then PATH."""93    for candidate in (TOOLS_HOME / "bin" / name, TOOLS_HOME / "venv" / "bin" / name):94        if candidate.exists():95            return str(candidate)96    return shutil.which(name)979899def run_cmd(cmd: list[str], cwd: Path | str | None = None, timeout: int | None = None,100            env: dict | None = None, stdin: str | None = None) -> tuple[int, str, str, float]:101    """Run a command; returns (exit code, stdout, stderr, seconds). Exit code 124 = timeout, 127 = missing."""102    start = time.time()103    full_env = dict(os.environ)104    if env:105        full_env.update(env)106    try:107        p = subprocess.run(cmd, cwd=str(cwd or REPO), capture_output=True, text=True, timeout=timeout,108                           env=full_env, input=stdin, errors="replace")109        return p.returncode, p.stdout, p.stderr, time.time() - start110    except subprocess.TimeoutExpired as e:111        out = e.stdout.decode(errors="replace") if isinstance(e.stdout, bytes) else (e.stdout or "")112        err = e.stderr.decode(errors="replace") if isinstance(e.stderr, bytes) else (e.stderr or "")113        return 124, out, err + f"\n[timeout after {timeout}s]", time.time() - start114    except FileNotFoundError as e:115        return 127, "", str(e), time.time() - start116117118def fingerprint(*parts: str) -> str:119    return hashlib.sha256("\x1f".join(parts).encode()).hexdigest()[:12]120121122def finding(*, title: str, severity: str, location: str = "", tool: str = "manual-review",123            id: str | None = None, description: str = "", recommendation: str = "",124            cwe: str = "", masvs: str = "", cvss_vector: str = "", cvss_score: float | None = None,125            status: str = "open", fix_commit: str = "", regression_test: str = "",126            area: str = "", rule: str = "", evidence: str = "") -> dict:127    """One finding in the common schema (see security/audit/schema/results.schema.json)."""128    assert severity in SEVERITIES, severity129    assert status in STATUSES, status130    fp = fingerprint(tool, rule or title, location.split(":")[0], evidence or title)131    return {132        "id": id or f"QY-{tool.upper().replace(' ', '-')}-{fp}",133        "title": title,134        "severity": severity,135        "cvss_vector": cvss_vector,136        "cvss_score": cvss_score,137        "cwe": cwe,138        "masvs": masvs,139        "area": area,140        "location": location,141        "tool": tool,142        "rule": rule,143        "status": status,144        "fix_commit": fix_commit,145        "regression_test": regression_test,146        "description": description,147        "recommendation": recommendation,148        "evidence": evidence[:2000],149        "fingerprint": fp,150    }151152153def tool_result(*, tool: str, category: str, status: str, version: str = "", reason: str = "",154                command: str = "", duration_s: float = 0.0, coverage: str = "",155                metrics: dict | None = None, tests: list | None = None,156                findings: list | None = None, artifacts: list | None = None) -> dict:157    """One tool result. `status` is RUN, NOT RUN or FAILED. `tests` is a list of test-count records:158    {area, name, algorithm, parameter_set, cases, passed, failed, skipped, seed, note}."""159    assert status in (RUN, NOT_RUN, FAILED), status160    return {161        "tool": tool,162        "category": category,163        "status": status,164        "version": version,165        "reason": reason,166        "command": command,167        "duration_s": round(duration_s, 2),168        "coverage": coverage,169        "metrics": metrics or {},170        "tests": tests or [],171        "findings": findings or [],172        "artifacts": artifacts or [],173    }174175176def not_run(tool: str, category: str, reason: str, coverage: str = "") -> dict:177    return tool_result(tool=tool, category=category, status=NOT_RUN, reason=reason, coverage=coverage)178179180def load_json(path: Path, default=None):181    try:182        return json.loads(Path(path).read_text())183    except (OSError, ValueError):184        return default185186187def write_json(path: Path, obj) -> None:188    path = Path(path)189    path.parent.mkdir(parents=True, exist_ok=True)190    path.write_text(json.dumps(obj, indent=2, ensure_ascii=False, sort_keys=False) + "\n")191192193def tool_pins() -> dict:194    """Pinned tool versions (security/policies/tools.json)."""195    return load_json(POLICIES / "tools.json", {}) or {}196197198def apply_triage(findings: list[dict]) -> list[dict]:199    """Apply security/policies/triage.json: reviewed tool findings keyed by fingerprint or id.200    An entry may set status (accepted-risk / false-positive / fixed), severity and must give a justification."""201    triage = (load_json(POLICIES / "triage.json", {}) or {}).get("entries", {})202    for f in findings:203        entry = triage.get(f["fingerprint"]) or triage.get(f["id"])204        if entry:205            for key in ("status", "severity", "fix_commit", "regression_test", "cvss_vector", "cvss_score"):206                if key in entry:207                    f[key] = entry[key]208            f["triage"] = entry.get("justification", "")209    return findings210211212def rel(path: Path | str) -> str:213    try:214        return str(Path(path).resolve().relative_to(REPO))215    except ValueError:216        return str(path)217
Files main
Menu

Theme