Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# Project : QYVORA7# File : security/audit/lib/build.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"""Build locations and helpers shared by the runners that compile Swift code.4243One scratch directory per package keeps the builds incremental between audit runs:44`QY_AUDIT_SCRATCH` (default /tmp/qy-audit-build) with `engine/` for the root package and45`audit/` for security/tests. Remote helpers copy the tree to `<node>:qyvora-build/audit/`46(only that directory is ever written on a node) and run a command there.47"""4849from __future__ import annotations5051import os52import shlex53import subprocess54from pathlib import Path5556from lib.common import REPO, run_cmd5758SCRATCH = Path(os.environ.get("QY_AUDIT_SCRATCH", "/tmp/qy-audit-build"))59ENGINE_SCRATCH = SCRATCH / "engine"60AUDIT_SCRATCH = SCRATCH / "audit"61# Executables measured or disassembled (qytiming) are built without `-enable-testing`, like production code,62# in their own directory so that they do not invalidate the test build (which SwiftPM compiles with testability).63PRODUCT_SCRATCH = SCRATCH / "audit-products"64# qytiming built with QY_TIMING_INTERNALS=1 and testability: only for the timing targets that call internal functions65# of the Ed25519 module with chosen scalars (the verdicts on the public interface come from the production build).66INTERNALS_SCRATCH = SCRATCH / "audit-products-internals"67INTERNALS_ENV = {"QY_TIMING_INTERNALS": "1"}68INTERNALS_ARGS = ["-Xswiftc", "-enable-testing"]69AUDIT_PACKAGE = REPO / "security" / "tests"70REMOTE_DIR = "qyvora-build/audit"717273def swift_version() -> str:74 code, out, err, _ = run_cmd(["swift", "--version"], timeout=60)75 text = (out + err).strip().splitlines()76 for line in text:77 if "Swift version" in line:78 return line.strip()79 return text[0] if text else "unknown"808182def bin_path(package: Path, scratch: Path) -> Path | None:83 code, out, _, _ = run_cmd(["swift", "build", "-c", "release", "--package-path", str(package),84 "--scratch-path", str(scratch), "--show-bin-path"], timeout=300)85 path = out.strip().splitlines()[-1] if out.strip() else ""86 return Path(path) if code == 0 and path else None878889def build_product(product: str, timeout: int = 3600, scratch: Path | None = None,90 extra_args: list[str] | None = None, env: dict | None = None) -> tuple[Path | None, str]:91 """Builds an executable of the audit package in release mode; returns (path, error text)."""92 scratch = scratch or PRODUCT_SCRATCH93 environment = {"QY_AUDIT_ONLY": product}94 environment.update(env or {})95 code, out, err, _ = run_cmd(["swift", "build", "-c", "release", *(extra_args or []), "--package-path", str(AUDIT_PACKAGE),96 "--scratch-path", str(scratch), "--product", product], timeout=timeout,97 env=environment)98 if code != 0:99 lines = [l for l in (out + err).splitlines() if "error" in l]100 return None, "\n".join(lines[:15]) or (out + err)[-1500:]101 base = bin_path(AUDIT_PACKAGE, scratch)102 exe = base / product if base else None103 return (exe, "") if exe and exe.exists() else (None, f"{product} not found after build")104105106# --- cluster nodes ---------------------------------------------------------------------------107108def ssh(node: str, command: str, timeout: int = 3600) -> tuple[int, str, str, float]:109 return run_cmd(["ssh", "-o", "BatchMode=yes", "-o", "ConnectTimeout=15", node, command], timeout=timeout)110111112def node_load(node: str) -> float | None:113 """1-minute load average of a node, None when unreachable."""114 code, out, _, _ = ssh(node, "sysctl -n vm.loadavg 2>/dev/null || cat /proc/loadavg", timeout=40)115 if code != 0:116 return None117 for token in out.replace("{", " ").replace("}", " ").split():118 try:119 return float(token)120 except ValueError:121 continue122 return None123124125def sync_to_node(node: str, timeout: int = 1800) -> tuple[bool, str]:126 """Copies the working tree (without build output, Git data and local tools) to the node's audit directory."""127 ssh(node, f"mkdir -p {REMOTE_DIR}", timeout=60)128 cmd = ["rsync", "-a", "--delete", "--exclude", ".build", "--exclude", ".git", "--exclude", ".claude",129 "--exclude", "security/.tools", "--exclude", "security/reports/raw", "--exclude", "build", "--exclude", "DerivedData",130 "--exclude", "security/fuzzing/work", "--exclude", "*.xcarchive", "--exclude", "*.ipa",131 f"{REPO}/", f"{node}:{REMOTE_DIR}/"]132 code, out, err, _ = run_cmd(cmd, timeout=timeout)133 return code == 0, (out + err)[-800:]134135136def remote(node: str, command: str, timeout: int = 7200, env: dict | None = None) -> tuple[int, str, str, float]:137 """Runs a shell command in the node's copy of the tree (login shell: Homebrew and Swift on PATH)."""138 exports = " ".join(f"{k}={shlex.quote(str(v))}" for k, v in (env or {}).items())139 inner = f"cd {REMOTE_DIR} && {exports} {command}"140 return ssh(node, f"zsh -lc {shlex.quote(inner)}", timeout=timeout)141142143def fetch_from_node(node: str, remote_path: str, local: Path) -> bool:144 local.parent.mkdir(parents=True, exist_ok=True)145 return subprocess.run(["scp", "-q", "-o", "BatchMode=yes", f"{node}:{REMOTE_DIR}/{remote_path}", str(local)],146 capture_output=True).returncode == 0147