Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# Project : QYVORA7# File : security/audit/runners/ipa_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"""Builds an unsigned Release archive of the iOS application and packages it as an .ipa.4243The archive is the input of the MobSF runner and of the binary checks. Nothing is signed and44nothing is uploaded: `CODE_SIGNING_ALLOWED=NO`, scratch directory under /tmp, the .ipa is written45to `security/reports/raw/Qyvora-unsigned.ipa` (git-ignored).4647A build is reused when the Git commit and the working-tree state are the same as the previous48build of this scratch directory (set QY_AUDIT_REBUILD=1 to force a rebuild).4950Standalone: `python3 security/audit/runners/ipa_build.py`51"""5253from __future__ import annotations5455import hashlib56import json57import os58import shutil59import sys60import zipfile61from pathlib import Path6263sys.path.insert(0, str(Path(__file__).resolve().parents[1]))64from lib.common import FAILED, NOT_RUN, RUN, REPO, Context, load_json, rel, run_cmd, tool_result, write_json # noqa: E4026566TOOL = "ipa-build"67SCRATCH = Path(os.environ.get("QY_AUDIT_IPA_SCRATCH", "/tmp/qy-audit-ipa"))68ARCHIVE = SCRATCH / "Qyvora.xcarchive"69APP = ARCHIVE / "Products" / "Applications" / "Qyvora.app"70DSYM = ARCHIVE / "dSYMs" / "Qyvora.app.dSYM"71LOG = SCRATCH / "archive.log"72MARKER = SCRATCH / "build.json"73IPA_NAME = "Qyvora-unsigned.ipa"74COVERAGE = ("Unsigned Release archive (xcodebuild archive, iphoneos SDK, arm64, CODE_SIGNING_ALLOWED=NO). "75 "It is the same compiler configuration as the distributed build, but it is not the signed App Store "76 "binary: no code signature, no embedded provisioning profile, entitlements not applied.")777879def tree_state() -> dict:80 """Commit and a digest of the uncommitted changes that can affect the application."""81 _, head, _, _ = run_cmd(["git", "rev-parse", "HEAD"])82 _, status, _, _ = run_cmd(["git", "status", "--porcelain", "--", "App", "Sources", "Package.swift"])83 _, diff, _, _ = run_cmd(["git", "diff", "HEAD", "--", "App", "Sources", "Package.swift"])84 digest = hashlib.sha256((status + "\x1f" + diff).encode()).hexdigest()[:16]85 return {"commit": head.strip(), "dirty": bool(status.strip()), "state": digest}868788def sha256_file(path: Path) -> str:89 h = hashlib.sha256()90 with open(path, "rb") as f:91 for block in iter(lambda: f.read(1 << 20), b""):92 h.update(block)93 return h.hexdigest()949596def package_ipa(app: Path, ipa: Path) -> None:97 """Payload/Qyvora.app zipped with deterministic ordering (symlinks kept, modes kept)."""98 ipa.parent.mkdir(parents=True, exist_ok=True)99 if ipa.exists():100 ipa.unlink()101 with zipfile.ZipFile(ipa, "w", zipfile.ZIP_DEFLATED) as z:102 for path in sorted(app.rglob("*")):103 arc = Path("Payload") / app.name / path.relative_to(app)104 if path.is_symlink():105 info = zipfile.ZipInfo(str(arc))106 info.external_attr = (0o120777 << 16)107 z.writestr(info, os.readlink(path))108 elif path.is_file():109 z.write(path, str(arc))110111112def build(ctx: Context | None = None) -> dict:113 """Returns {ok, reason, app, ipa, dsym, log, state, duration_s, reused, xcode, errors}."""114 ctx = ctx or Context()115 ipa = ctx.raw_path(IPA_NAME)116 state = tree_state()117 out = {"ok": False, "reason": "", "app": str(APP), "ipa": str(ipa), "dsym": str(DSYM), "log": str(LOG),118 "state": state, "duration_s": 0.0, "reused": False, "xcode": "", "errors": [], "status": FAILED}119120 if not shutil.which("xcodebuild") or not shutil.which("xcodegen"):121 out["status"] = NOT_RUN122 out["reason"] = "xcodebuild or xcodegen is not installed on this machine (the iOS archive needs macOS with Xcode)"123 return out124 _, xv, _, _ = run_cmd(["xcodebuild", "-version"])125 out["xcode"] = " ".join(xv.split())126127 previous = load_json(MARKER, {}) or {}128 if (not os.environ.get("QY_AUDIT_REBUILD") and previous.get("state") == state129 and (APP / "Qyvora").exists() and previous.get("ok")):130 out.update(ok=True, reused=True, status=RUN, duration_s=previous.get("duration_s", 0.0))131 if not ipa.exists():132 package_ipa(APP, ipa)133 out["ipa_sha256"] = sha256_file(ipa)134 return out135136 SCRATCH.mkdir(parents=True, exist_ok=True)137 code, o, e, t1 = run_cmd(["xcodegen", "generate"], cwd=REPO / "App", timeout=300)138 if code != 0:139 out["reason"] = "xcodegen generate failed: " + (o + e).strip()[-800:]140 return out141 if ARCHIVE.exists():142 shutil.rmtree(ARCHIVE)143 cmd = ["xcodebuild", "-project", "Qyvora.xcodeproj", "-scheme", "Qyvora", "-configuration", "Release",144 "-sdk", "iphoneos", "-destination", "generic/platform=iOS",145 "-archivePath", str(ARCHIVE), "-derivedDataPath", str(SCRATCH / "DerivedData"),146 "CODE_SIGNING_ALLOWED=NO", "CODE_SIGNING_REQUIRED=NO", "CODE_SIGN_IDENTITY=",147 "-jobs", os.environ.get("QY_AUDIT_XCODE_JOBS", "8"), "archive"]148 out["command"] = "cd App && xcodegen generate && " + " ".join(cmd)149 code, o, e, t2 = run_cmd(cmd, cwd=REPO / "App", timeout=3600)150 LOG.write_text(o + "\n" + e)151 out["duration_s"] = round(t1 + t2, 1)152 if code != 0 or not (APP / "Qyvora").exists():153 errors = sorted({line.strip() for line in (o + e).splitlines() if "error:" in line})[:20]154 out["errors"] = errors155 out["reason"] = (f"xcodebuild archive exited {code}"156 + (": " + " | ".join(errors[:5]) if errors else " (see " + str(LOG) + ")"))157 write_json(MARKER, {"ok": False, "state": state, "duration_s": out["duration_s"]})158 return out159 package_ipa(APP, ipa)160 out.update(ok=True, status=RUN)161 out["ipa_sha256"] = sha256_file(ipa)162 write_json(MARKER, {"ok": True, "state": state, "duration_s": out["duration_s"]})163 return out164165166def run(ctx: Context) -> dict:167 b = build(ctx)168 if not b["ok"]:169 return tool_result(tool=TOOL, category="mobile", status=b["status"], reason=b["reason"],170 version=b["xcode"], command=b.get("command", ""), duration_s=b["duration_s"],171 coverage=COVERAGE, metrics={"compiler_errors": b["errors"]})172 ipa = Path(b["ipa"])173 return tool_result(174 tool=TOOL, category="mobile", status=RUN, version=b["xcode"], command=b.get("command", "(reused build)"),175 duration_s=b["duration_s"], coverage=COVERAGE,176 metrics={"commit": b["state"]["commit"], "dirty": b["state"]["dirty"], "reused_previous_build": b["reused"],177 "ipa_bytes": ipa.stat().st_size, "ipa_sha256": b["ipa_sha256"],178 "executable_bytes": (APP / "Qyvora").stat().st_size, "signed": False},179 artifacts=[rel(ipa)])180181182if __name__ == "__main__":183 print(json.dumps(run(Context(mode="quick")), indent=2))184