ci: refonte multi-workflows — suppression du monolithe ci-full templates (Fixes #129) (#130)

## Contexte

La CI actuelle délègue tout à l'action composite monolithe `ci-full` de `nonobis/templates` : build → tests → Sonar → Docker → Trivy → Dependency-Check dans **un seul job, en série**. Le runner act/forgejo cache les actions composites **par URL** (`~/.cache/act` keyé par sha256, jamais invalidé) — cause racine des échecs CI récurrents d'août 2026 (ancien contenu exécuté malgré les pushs, purges hôte, runs rouges sur les 3 LXC).

Objectif : **supprimer cette CI et la refaire de zéro** en workflows natifs, plusieurs jobs **parallèles** (moins long, erreurs visibles par job), avec toutes les fonctionnalités actuelles.

## Changements

- [x] `.forgejo/workflows/ci.yml` — **8 jobs parallèles inline** (zéro action composite maison) :
  - `build` : restore + build + `dotnet format` (gate qualité rapide)
  - `test-unit` : Domain + Application + Agent + Api (parallèle interne)
  - `test-web` : bUnit Web.Tests
  - `test-db` : PostgreSQL CI + Infrastructure (Testcontainers) + Integration, sérialisés
  - `sonar` : analyse + **gate bloquant** (avec param `pullRequest` pour les PR)
  - `docker` : build images (main + PR), push main (latest+sha), images de test `pr-<N>`, **Trivy bloquant** (scan de l'image locale)
  - `dependency-check` : OWASP **bloquant** (failOnCVSS 7.0, cache NVD `/opt/dc-cache`)
  - `post-summary` : **commentaire PR unique** agrégé (tests unitaires + bUnit + DB)
- [x] `.forgejo/workflows/release.yml` — 2 cycles release inline : `v*` (central Web) et `agent-v*` (agent, binaires natifs linux-x64/arm64/win-x64), GitVersion double, archives, release Forgejo + notes auto, push Docker Hub
- [x] `scripts/ci/` — utilitaires versionnés dans le repo : résumé tests, commentaires PR, rapports CVE (Trivy/DC), injection secrets Infisical, notes de release
- [x] `renovate.yml` inchangé (dernière dépendance `templates` conservée : `RENOVATE_TOKEN` via Vault — documentée dans le ticket)

Seules actions par URL conservées : `checkout@v4` et `setup-dotnet@v4` (miroirs stables). Plus de checkout `.ci` / PAT `TEMPLATES_PAT` pour la CI.

## Tickets liés (obligatoire)

- Fixes #129
- Refs #125 (référencement ci-full tagué — obsolète)
- Refs #104 (secrets Vault → Infisical — la CI utilise le flux Infisical)
- Refs #101 (SonarQube gate conservé bloquant)

## Résultats des tests (obligatoire)

- [ ] Rapport QA de the-qa : à venir (commentaire)
- [ ] Tous les tests passent (voir run CI + commentaire post-summary)
- [ ] Coverage : voir commentaire CI

## Retours SonarQube (obligatoire)

- [ ] Quality gate SonarQube **OK** (voir run CI)
- [ ] Bugs / vulnérabilités : **0 non résolu**

## CVE (obligatoire)

- [ ] Aucune CVE HIGH/CRITICAL nouvelle sur cette PR (voir commentaire CI)
- [ ] CVE non corrigeables documentées en commentaire (si applicable)

## Checklist

- [x] Commits atomiques au format conventionnel (`ci: refonte multi-workflows — ...`)
- [x] Branche issue de `main`, à jour
- [x] Pas de secret en clair (tokens, mots de passe)
- [x] YAML des workflows validés (pyyaml) + scripts Python compilés
- [ ] CI verte : build, tests, Trivy, Dependency-Check, SonarQube (à confirmer sur le run)
- [x] Release notes / versioning impacté (GitVersion conservé en release)

Reviewed-on: https://forgejo.tordais.cc/nonobis/Heimdall/pulls/130
This commit is contained in:
Arnaud Dartois authored and Arnaud Dartois committed 2026-08-18 08:22:47 +02:00
1 parent 45ce41ce7e
commit 1fbeff9906
14 files changed
+2234 -80

No files matched your search

+43
View File
@@ -0,0 +1,43 @@
#!/usr/bin/env python3
"""Rapport markdown des vulnérabilités HIGH/CRITICAL du JSON OWASP Dependency-Check.
Usage: dc_report.py <dependency-check-report.json> [count]
(2e argument 'count' → affiche uniquement le nombre de vulnérabilités)"""
import json
import sys
try:
data = json.load(open(sys.argv[1]))
except Exception:
print("")
sys.exit(0)
mode_count = len(sys.argv) > 2 and sys.argv[2] == "count"
vulns = []
seen = set()
for dep in data.get("dependencies", []):
for v in dep.get("vulnerabilities", []):
sev = (v.get("cvssv3", {}) or {}).get("baseScore", 0)
sev_label = v.get("severity", "UNKNOWN")
if sev < 7.0 and sev_label not in ("HIGH", "CRITICAL"):
continue
vid = v.get("name", "CVE-?")
if vid in seen:
continue
seen.add(vid)
vulns.append((vid, sev_label, sev, dep.get("fileName", "?"), (v.get("description", "") or "")[:80]))
if mode_count:
print(len(vulns))
sys.exit(0)
if not vulns:
print("")
sys.exit(0)
print(f"### 🛡️ OWASP Dependency-Check — Vulnerabilités HIGH/CRITICAL ({len(vulns)})")
print("")
print("| CVE | Sévérité | Dépendance | Description |")
print("|---|---|---|---|")
for vid, sev_label, sev, fname, desc in vulns:
print(f"| {vid} | {sev_label} (CVSS {sev}) | {fname} | {desc} |")
+27
View File
@@ -0,0 +1,27 @@
#!/usr/bin/env python3
"""Injecte des secrets au format dotenv dans $GITHUB_ENV (steps suivants du job).
Usage: inject_env.py <dotenv-content>
Sûr pour les valeurs multi-lignes et caractères spéciaux (délimiteur EOF)."""
import os
import sys
dotenv = sys.argv[1] if len(sys.argv) > 1 else ""
out = os.environ.get("GITHUB_ENV")
if not out:
print("GITHUB_ENV non défini — rien à injecter")
sys.exit(0)
count = 0
with open(out, "a") as f:
for line in dotenv.splitlines():
line = line.strip()
if not line or line.startswith("#") or "=" not in line:
continue
key, _, val = line.partition("=")
key = key.strip()
val = val.strip().strip("'").strip('"')
if not key:
continue
f.write(f"{key}<<HEIMDALL_EOF\n{val}\nHEIMDALL_EOF\n")
count += 1
print(f"Secrets Infisical injectés dans l'environnement du job ({count} clés)")
+77
View File
@@ -0,0 +1,77 @@
#!/usr/bin/env python3
"""Parse les logs `dotnet test` et produit un résumé markdown (tests + coverage).
Usage:
parse_test_log.py <log1> <log2> ... [--coverage-dir <dir>]
Lit les fichiers de log (générés par les jobs CI) et les rapports coverage
cobertura (optionnel) ; sort le markdown sur stdout. Vide si rien trouvé.
"""
import glob
import os
import re
import sys
args = sys.argv[1:]
cov_dir = None
if "--coverage-dir" in args:
i = args.index("--coverage-dir")
cov_dir = args[i + 1]
del args[i:i + 2]
logs = [a for a in args if os.path.isfile(a)]
results = [] # (projet, passed, failed, skipped, total, status)
error_lines = []
for f in sorted(logs):
try:
with open(f, errors="replace") as fh:
content = fh.read()
except OSError:
continue
# "Passed! - Failed: 0, Passed: 225, Skipped: 0, Total: 225, ... - X.dll (net10.0)"
for m in re.finditer(
r"(Passed!|Failed!)\s+-\s+Failed:\s*(\d+),\s+Passed:\s*(\d+),\s+Skipped:\s*(\d+),\s+Total:\s*(\d+)[^:]*-\s*([\w.]+)\.dll",
content,
):
results.append((m.group(6), m.group(2), m.group(3), m.group(4), m.group(5), m.group(1)))
for m in re.finditer(r"error CS\d+:\s*(.+)", content):
error_lines.append(m.group(1).strip()[:120])
if not results and not error_lines:
print("")
sys.exit(0)
out = []
if results:
out.append("| Projet | Statut | Passed | Failed | Skipped | Total |")
out.append("|---|---|---|---|---|---|")
for proj, failed, passed, skipped, total, status in results:
icon = "🟢" if status == "Passed!" else "🔴"
out.append(f"| `{proj}` | {icon} | {passed} | {failed} | {skipped} | {total} |")
failed_total = sum(int(r[1]) for r in results)
if failed_total:
out.append(f"\n**⚠️ {failed_total} test(s) en échec** — voir le détail dans le job CI.")
else:
out.append("\n**✅ Tous les tests passent.**")
if error_lines:
out.append("\n**Erreurs de compilation détectées :**")
for e in error_lines[:10]:
out.append(f"- `{e}`")
# Coverage moyen (cobertura)
if cov_dir:
rates = []
for cf in glob.glob(os.path.join(cov_dir, "**", "*.cobertura.xml"), recursive=True):
try:
with open(cf, errors="replace") as fh:
data = fh.read()
lm = re.search(r'line-rate="([\d.]+)"', data)
if lm:
rates.append(float(lm.group(1)))
except OSError:
continue
if rates:
avg = sum(rates) / len(rates) * 100
out.append(f"\n**Coverage moyen : {avg:.1f}%** ({len(rates)} projet(s))")
print("\n".join(out))
+43
View File
@@ -0,0 +1,43 @@
#!/usr/bin/env python3
"""Poste un commentaire markdown sur une PR Forgejo.
Usage:
post_comment.py <texte> [titre]
Env requis : FORGEJO_TOKEN, REPO (owner/repo), PR_NUMBER.
Si REPO/PR_NUMBER/FORGEJO_TOKEN absents → warning, sortie 0 (commentaire ignoré).
"""
import json
import os
import sys
import urllib.request
text = sys.argv[1] if len(sys.argv) > 1 else ""
title = sys.argv[2] if len(sys.argv) > 2 else "CI"
repo = os.environ.get("REPO", "")
pr = os.environ.get("PR_NUMBER", "")
token = os.environ.get("FORGEJO_TOKEN", "")
if not text.strip():
print("Rien à commenter — sortie sans commentaire")
raise SystemExit(0)
body = f"## 🤖 {title}\n\n{text}\n\n_Généré automatiquement par la CI._"
if not repo or not pr or not token:
print("::warning::REPO/PR_NUMBER/FORGEJO_TOKEN manquants — commentaire ignoré")
raise SystemExit(0)
url = f"https://forgejo.tordais.cc/api/v1/repos/{repo}/issues/{pr}/comments"
req = urllib.request.Request(
url,
data=json.dumps({"body": body}).encode(),
headers={"Authorization": f"token {token}", "Content-Type": "application/json"},
method="POST",
)
try:
urllib.request.urlopen(req)
print(f"Commentaire posté sur la PR #{pr}")
except Exception as e:
print(f"::warning::Impossible de poster le commentaire: {e}")
+40
View File
@@ -0,0 +1,40 @@
#!/usr/bin/env python3
"""Poste un commentaire CVE (Trivy + Dependency-Check) sur une PR Forgejo.
Usage: post_cve_comment.py
Env: FORGEJO_TOKEN, TRIVY_REPORT, DC_REPORT, REPO, PR_NUMBER"""
import json
import os
import urllib.request
body = ""
trivy = os.environ.get("TRIVY_REPORT", "")
dc = os.environ.get("DC_REPORT", "")
if trivy:
body += "\n" + trivy + "\n"
if dc:
body += "\n" + dc + "\n"
if not body.strip():
print("Aucune CVE à signaler — pas de commentaire")
raise SystemExit(0)
body = "## 🛡️ Rapport sécurité — CVE détectées\n\n" + body + "\n\n_Généré automatiquement par la CI (Trivy / OWASP Dependency-Check)._"
repo = os.environ.get("REPO", "")
pr = os.environ.get("PR_NUMBER", "")
token = os.environ.get("FORGEJO_TOKEN", "")
if not repo or not pr or not token:
print("::warning::REPO/PR_NUMBER/FORGEJO_TOKEN manquants — commentaire ignoré")
raise SystemExit(0)
url = f"https://forgejo.tordais.cc/api/v1/repos/{repo}/issues/{pr}/comments"
req = urllib.request.Request(
url,
data=json.dumps({"body": body}).encode(),
headers={"Authorization": f"token {token}", "Content-Type": "application/json"},
method="POST",
)
try:
urllib.request.urlopen(req)
print(f"Commentaire CVE posté sur la PR #{pr}")
except Exception as e:
print(f"::warning::Impossible de poster le commentaire CVE: {e}")
+117
View File
@@ -0,0 +1,117 @@
#!/usr/bin/env python3
"""release_notes.py — Génère les release notes Forgejo depuis le dernier tag du même préfixe.
Usage:
release_notes.py [TAG] [PREFIX] [REPO_URL]
TAG : tag de la release courante (défaut : détecté via git describe)
PREFIX : préfixe de tag (défaut : 'v') — les notes ne comparent qu'avec
les tags du même préfixe (ex. 'agent-v' pour l'agent)
REPO_URL : base d'URL du repo pour les liens commits (défaut : forgejo.tordais.cc)
Sortie : markdown prêt pour le body d'une release Forgejo (stdout).
"""
import subprocess
import sys
import datetime
CATEGORIES = {
"feat": ("✨ Features", "feature"),
"fix": ("🐛 Fixes", "bug"),
"perf": ("⚡ Performance", "perf"),
"chore": ("🧹 Maintenance", "chore"),
"refactor": ("🧹 Maintenance", "refactor"),
"docs": ("🧹 Maintenance", "docs"),
"style": ("🧹 Maintenance", "style"),
"build": ("🧹 Maintenance", "build"),
"ci": ("🧹 Maintenance", "ci"),
"test": ("🧹 Maintenance", "test"),
"revert": ("↩️ Reverts", "revert"),
}
def git(*args):
r = subprocess.run(["git", *args], capture_output=True, text=True)
return r.stdout.strip()
def git_or_none(*args):
r = subprocess.run(["git", *args], capture_output=True, text=True)
return r.stdout.strip() if r.returncode == 0 else ""
def tag_date(t):
return git_or_none("log", "-1", "--format=%ct", t)
def parse_commit(line):
"""'abc1234|message' -> (sha, subject)"""
if "|" in line:
sha, subject = line.split("|", 1)
else:
sha, subject = line, line
return sha, subject
def categorize(subject):
subject_l = subject.lower()
for prefix, (title, _) in CATEGORIES.items():
if subject_l.startswith(prefix + ":") or subject_l.startswith(prefix + "("):
return title
return "📦 Autres"
def main():
tag = sys.argv[1] if len(sys.argv) > 1 else git("describe", "--tags", "--abbrev=0") or ""
prefix = sys.argv[2] if len(sys.argv) > 2 else "v"
repo_url = sys.argv[3] if len(sys.argv) > 3 else "forgejo.tordais.cc"
# Dernier tag du même préfixe, antérieur à celui-ci (par date du commit tagué)
all_tags = [t for t in git("tag", "--list").splitlines() if t.startswith(prefix) and t != tag]
all_tags.sort(key=lambda t: (tag_date(t) or "0"), reverse=True)
prev = all_tags[0] if all_tags else None
if prev:
raw = git("log", f"{prev}..{tag}", "--pretty=format:%h|%s")
elif tag:
raw = git("log", tag, "--pretty=format:%h|%s")
else:
raw = git("log", "--pretty=format:%h|%s")
commits = [parse_commit(l) for l in raw.splitlines() if l]
if not commits:
print(f"## {tag} — {datetime.date.today().isoformat()}\n\n_No commits._")
return 0
grouped = {}
for sha, subject in commits:
grouped.setdefault(categorize(subject), []).append((sha, subject))
today = datetime.date.today().isoformat()
lines = [f"## {tag} — {today}", ""]
for title in ["✨ Features", "🐛 Fixes", "⚡ Performance", "↩️ Reverts", "🧹 Maintenance", "📦 Autres"]:
items = grouped.get(title)
if not items:
continue
lines.append(f"### {title}")
lines.append("")
for sha, subject in items:
lines.append(f"- {subject} ([`{sha}`](https://{repo_url}/commit/{sha}))")
lines.append("")
# Liste complète repliable
lines.append(f"<details><summary>🔗 {len(commits)} commits</summary>")
lines.append("")
for sha, subject in commits:
lines.append(f"- [`{sha}`](https://{repo_url}/commit/{sha}) {subject}")
lines.append("")
lines.append("</details>")
print("\n".join(lines))
return 0
if __name__ == "__main__":
sys.exit(main())
+38
View File
@@ -0,0 +1,38 @@
#!/usr/bin/env python3
"""Extrait un rapport markdown des vulnérabilités du JSON Trivy.
Usage: trivy_report.py <trivy.json> <severity-label>
Sortie: markdown (vide si aucune vulnérabilité)."""
import json
import sys
try:
data = json.load(open(sys.argv[1]))
except Exception:
print("")
sys.exit(0)
severity_label = sys.argv[2] if len(sys.argv) > 2 else "HIGH,CRITICAL"
seen = set()
rows = []
for r in data.get("Results", []):
target = r.get("Target", "")
for v in r.get("Vulnerabilities", []):
vid = v.get("VulnerabilityID", "")
if vid in seen:
continue
seen.add(vid)
pkg = v.get("PkgName", "?")
inst = v.get("InstalledVersion", "?")
fixed = v.get("FixedVersion", "") or "—"
sev = v.get("Severity", "UNKNOWN")
rows.append(f"| {vid} | {sev} | {pkg} {inst} → {fixed} | {target} |")
if not rows:
print("")
sys.exit(0)
print(f"### 🛡️ Trivy — Vulnérabilités {severity_label} ({len(seen)})")
print("")
print("| CVE | Sévérité | Paquet | Cible |")
print("|---|---|---|---|")
print("\n".join(rows))