Files
Heimdall/.forgejo/workflows/ci.yml.bak
T
Arnaud Dartois 1fbeff9906 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
2026-08-18 08:22:47 +02:00

760 lines
36 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# ═══════════════════════════════════════════════════════════════════════════
# CI Heimdall — refonte multi-workflows (2026-08-14)
#
# PRINCIPES (remplace l'ancien monolithe ci-full de nonobis/templates) :
# • Workflows NATIFS, steps 100% inline — ZÉRO action composite maison
# (élimine le cache d'actions runner par URL : ~/.cache/act keyé par hash
# d'URL, jamais invalidé — cause racine des échecs CI d'août 2026).
# • Seules actions par URL : checkout@v4 et setup-dotnet@v4 (miroirs stables).
# • Un JOB par domaine → parallélisme réel (3 runners × capacity 2-4) et
# erreurs visibles par job dans l'UI Forgejo, pas un seul gros job rouge.
# • Pas d'actions/cache bloquant : continue-on-error (cache runner activé
# via the-devops, sinon restore NuGet direct).
# • Secrets Infisical injectés uniquement dans les jobs qui en ont besoin.
# ═══════════════════════════════════════════════════════════════════════════
name: CI
on:
push:
branches: [main]
paths-ignore:
- '**.md'
- 'docs/**'
pull_request:
branches: [main]
env:
DOTNET_CLI_TELEMETRY_OPTOUT: 1
DOTNET_NOLOGO: 1
concurrency:
group: ci-${{ forgejo.ref }}
cancel-in-progress: true
jobs:
# ─────────────────────────────────────────────────────────────────────────
# BUILD + FORMAT — gate qualité rapide
# ─────────────────────────────────────────────────────────────────────────
build:
name: Build + Format
runs-on: debian-12
timeout-minutes: 15
steps:
- uses: https://forgejo.tordais.cc/actions/checkout@v4
with:
fetch-depth: 0
- uses: https://forgejo.tordais.cc/actions/setup-dotnet@v4
with:
dotnet-version: '10.0'
- name: Cache NuGet (best-effort)
continue-on-error: true
uses: https://forgejo.tordais.cc/actions/cache@v4
with:
path: ~/.nuget/packages
key: nuget-${{ runner.os }}-${{ hashFiles('**/*.csproj', '**/*.slnx', '**/Directory.Build.props') }}
restore-keys: |
nuget-${{ runner.os }}-
- name: Restore & Build
shell: bash
run: |
dotnet restore Heimdall.slnx --nologo
dotnet build Heimdall.slnx --no-restore -c Release --nologo /maxcpucount
- name: dotnet format (whitespace)
shell: bash
run: dotnet format Heimdall.slnx whitespace --verify-no-changes --no-restore
# ─────────────────────────────────────────────────────────────────────────
# TESTS UNITAIRES RAPIDES (Domain, Application, Agent, Api — parallèle interne)
# ─────────────────────────────────────────────────────────────────────────
test-unit:
name: Tests unitaires
runs-on: debian-12
timeout-minutes: 25
outputs:
summary: ${{ steps.gen-summary.outputs.summary }}
steps:
- uses: https://forgejo.tordais.cc/actions/checkout@v4
- uses: https://forgejo.tordais.cc/actions/setup-dotnet@v4
with:
dotnet-version: '10.0'
- name: Cache NuGet (best-effort)
continue-on-error: true
uses: https://forgejo.tordais.cc/actions/cache@v4
with:
path: ~/.nuget/packages
key: nuget-${{ runner.os }}-${{ hashFiles('**/*.csproj', '**/*.slnx', '**/Directory.Build.props') }}
restore-keys: |
nuget-${{ runner.os }}-
- name: Restore & Build
shell: bash
run: |
dotnet restore Heimdall.slnx --nologo
dotnet build Heimdall.slnx --no-restore -c Release --nologo /maxcpucount
- name: Run unit tests (parallel)
shell: bash
run: |
set -euo pipefail
mkdir -p /tmp/coverage
PROJECTS="tests/Heimdall.Domain.Tests/Heimdall.Domain.Tests.csproj tests/Heimdall.Application.Tests/Heimdall.Application.Tests.csproj tests/Heimdall.Agent.Tests/Heimdall.Agent.Tests.csproj tests/Heimdall.Api.Tests/Heimdall.Api.Tests.csproj"
FAIL=0
declare -A JOB_LOG
for proj in $PROJECTS; do
NAME=$(basename "$(dirname "$proj")")
LOG="/tmp/${NAME}.log"
dotnet test "$proj" --no-build -c Release --nologo \
-p:CollectCoverage=true -p:CoverletOutputFormat=cobertura \
-p:CoverletOutput=/tmp/coverage/$NAME/ > "$LOG" 2>&1 &
JOB_LOG[$!]="$NAME"
done
for pid in "${!JOB_LOG[@]}"; do
if ! wait "$pid"; then
NAME="${JOB_LOG[$pid]}"
echo "::warning::$NAME exited non-zero"
tail -25 "/tmp/${NAME}.log" 2>/dev/null | sed 's/^/ /'
FAIL=1
fi
done
grep -h -E "(Passed!|Failed!|Failed:|error CS)" /tmp/*.log 2>/dev/null || true
exit $FAIL
- name: Générer le résumé
id: gen-summary
if: always()
shell: bash
run: |
SUMMARY=$(python3 scripts/ci/parse_test_log.py /tmp/*.log --coverage-dir /tmp/coverage 2>/dev/null || true)
{
echo "summary<<EOF"
printf '%s\n' "$SUMMARY"
echo "EOF"
} >> "$GITHUB_OUTPUT"
# ─────────────────────────────────────────────────────────────────────────
# TESTS WEB (bUnit — Blazor components, pas de navigateur)
# ─────────────────────────────────────────────────────────────────────────
test-web:
name: Tests Web (bUnit)
runs-on: debian-12
timeout-minutes: 30
outputs:
summary: ${{ steps.gen-summary.outputs.summary }}
steps:
- uses: https://forgejo.tordais.cc/actions/checkout@v4
- uses: https://forgejo.tordais.cc/actions/setup-dotnet@v4
with:
dotnet-version: '10.0'
- name: Cache NuGet (best-effort)
continue-on-error: true
uses: https://forgejo.tordais.cc/actions/cache@v4
with:
path: ~/.nuget/packages
key: nuget-${{ runner.os }}-${{ hashFiles('**/*.csproj', '**/*.slnx', '**/Directory.Build.props') }}
restore-keys: |
nuget-${{ runner.os }}-
- name: Restore & Build
shell: bash
run: |
dotnet restore Heimdall.slnx --nologo
dotnet build Heimdall.slnx --no-restore -c Release --nologo /maxcpucount
- name: Run bUnit tests
shell: bash
run: |
set -euo pipefail
mkdir -p /tmp/coverage
LOG=/tmp/Heimdall.Web.Tests.log
dotnet test tests/Heimdall.Web.Tests/Heimdall.Web.Tests.csproj --no-build -c Release --nologo \
-p:CollectCoverage=true -p:CoverletOutputFormat=cobertura \
-p:CoverletOutput=/tmp/coverage/bunit/ > "$LOG" 2>&1 || {
tail -40 "$LOG" | sed 's/^/ /'
exit 1
}
grep -h -E "(Passed!|Failed!|Failed:|error CS)" "$LOG" 2>/dev/null || true
- name: Générer le résumé
id: gen-summary
if: always()
shell: bash
run: |
SUMMARY=$(python3 scripts/ci/parse_test_log.py /tmp/*.log --coverage-dir /tmp/coverage 2>/dev/null || true)
{
echo "summary<<EOF"
printf '%s\n' "$SUMMARY"
echo "EOF"
} >> "$GITHUB_OUTPUT"
# ─────────────────────────────────────────────────────────────────────────
# TESTS DB (Infrastructure Testcontainers + Integration PostgreSQL réel)
# Sérialisés dans le job : la contention Testcontainers/PostgreSQL partagé
# rend les tests flaky (SaveChangesWithRetry timeout). PGDATA sur /tmp
# (jamais /dev/shm : tmpfs 64 Mo → 53100 No space left on device).
# ─────────────────────────────────────────────────────────────────────────
test-db:
name: Tests DB (Infrastructure + Integration)
runs-on: debian-12
timeout-minutes: 90
outputs:
summary: ${{ steps.gen-summary.outputs.summary }}
steps:
- uses: https://forgejo.tordais.cc/actions/checkout@v4
- uses: https://forgejo.tordais.cc/actions/setup-dotnet@v4
with:
dotnet-version: '10.0'
- name: Cache NuGet (best-effort)
continue-on-error: true
uses: https://forgejo.tordais.cc/actions/cache@v4
with:
path: ~/.nuget/packages
key: nuget-${{ runner.os }}-${{ hashFiles('**/*.csproj', '**/*.slnx', '**/Directory.Build.props') }}
restore-keys: |
nuget-${{ runner.os }}-
- name: Restore & Build
shell: bash
run: |
dotnet restore Heimdall.slnx --nologo
dotnet build Heimdall.slnx --no-restore -c Release --nologo /maxcpucount
- name: Start PostgreSQL (CI)
shell: bash
run: |
set -euo pipefail
apt-get -qq update
apt-get install -y -qq --no-install-recommends postgresql-15 postgresql-client-15
PGDATA=/tmp/pgdata
rm -rf "$PGDATA"
su - postgres -c "/usr/lib/postgresql/15/bin/initdb -D $PGDATA --auth=trust --no-locale --encoding=UTF8"
su - postgres -c "echo -e 'host all all 127.0.0.1/32 md5\nhost all all ::1/128 md5' >> $PGDATA/pg_hba.conf"
su - postgres -c "/usr/lib/postgresql/15/bin/pg_ctl -D $PGDATA -l /tmp/pgdata.log start"
for i in $(seq 1 15); do
su - postgres -c "/usr/lib/postgresql/15/bin/pg_isready -h localhost" > /dev/null 2>&1 && break
sleep 1
done
su - postgres -c "psql -c \"CREATE USER app WITH PASSWORD 'password';\"" 2>/dev/null || true
su - postgres -c "psql -c \"CREATE DATABASE app_test OWNER app;\"" 2>/dev/null || true
PGPASSWORD=password psql -U app -d app_test -h localhost -c "SELECT 1" > /dev/null
echo "PostgreSQL prêt (PGDATA=$PGDATA)"
- name: Run Infrastructure tests (Testcontainers)
shell: bash
env:
DATABASE_URL: Host=localhost;Port=5432;Database=app_test;Username=app;Password=password
run: |
set -euo pipefail
mkdir -p /tmp/coverage
LOG=/tmp/Heimdall.Infrastructure.Tests.log
dotnet test tests/Heimdall.Infrastructure.Tests/Heimdall.Infrastructure.Tests.csproj --no-build -c Release --nologo \
-p:CollectCoverage=true -p:CoverletOutputFormat=cobertura \
-p:CoverletOutput=/tmp/coverage/Infrastructure/ > "$LOG" 2>&1 || {
tail -40 "$LOG" | sed 's/^/ /'
exit 1
}
grep -h -E "(Passed!|Failed!|Failed:|error CS)" "$LOG" 2>/dev/null || true
- name: Pre-pull Testcontainers image (postgres:17-alpine)
shell: bash
run: |
# Les IntegrationTests démarrent leur propre PostgreSQL via
# Testcontainers. Pré-pull pour éviter le pull au moment du test
# (contention avec le job Docker+Trivy sur le même daemon).
# Le conteneur node:22-bookworm n'a pas docker CLI — installer comme
# le job Docker (socket hôte monté via docker_host: automount).
export DOCKER_HOST=unix:///var/run/docker.sock
if ! command -v docker &>/dev/null; then
curl -fsSL -o /tmp/docker.tgz https://download.docker.com/linux/static/stable/x86_64/docker-27.3.1.tgz
tar xzf /tmp/docker.tgz -C /tmp
export PATH="/tmp/docker:$PATH"
fi
docker version --format 'docker server {{.Server.Version}}' || echo "::warning::daemon docker inaccessible (Testcontainers utilisera son propre client)"
docker pull postgres:17-alpine || echo "::warning::pre-pull postgres:17-alpine échoué (sera pullé par Testcontainers)"
- name: Run Integration tests (PostgreSQL réel)
shell: bash
env:
DATABASE_URL: Host=localhost;Port=5432;Database=app_test;Username=app;Password=password
ASPNETCORE_ENVIRONMENT: Testing
run: |
set -euo pipefail
LOG=/tmp/Heimdall.IntegrationTests.log
dotnet test tests/Heimdall.IntegrationTests/Heimdall.IntegrationTests.csproj --no-build -c Release --nologo \
-p:CollectCoverage=true -p:CoverletOutputFormat=cobertura \
-p:CoverletOutput=/tmp/coverage/Integration/ > "$LOG" 2>&1 || {
tail -40 "$LOG" | sed 's/^/ /'
exit 1
}
grep -h -E "(Passed!|Failed!|Failed:|error CS)" "$LOG" 2>/dev/null || true
- name: Générer le résumé
id: gen-summary
if: always()
shell: bash
run: |
SUMMARY=$(python3 scripts/ci/parse_test_log.py /tmp/*.log --coverage-dir /tmp/coverage 2>/dev/null || true)
{
echo "summary<<EOF"
printf '%s\n' "$SUMMARY"
echo "EOF"
} >> "$GITHUB_OUTPUT"
# ─────────────────────────────────────────────────────────────────────────
# SONARQUBE — analyse + gate bloquant (politique projet)
# ─────────────────────────────────────────────────────────────────────────
sonar:
name: SonarQube
runs-on: debian-12
timeout-minutes: 40
steps:
- uses: https://forgejo.tordais.cc/actions/checkout@v4
- uses: https://forgejo.tordais.cc/actions/setup-dotnet@v4
with:
dotnet-version: '10.0'
- name: Secrets Infisical (projet CI)
id: infisical
shell: bash
env:
DOMAIN: ${{ secrets.VAULT_URL }}
CLIENT_ID: ${{ secrets.VAULT_CLIENT_ID }}
CLIENT_SECRET: ${{ secrets.VAULT_CLIENT_SECRET }}
PROJECT_ID: ${{ secrets.VAULT_PROJECT_ID }}
run: |
if [ -z "$PROJECT_ID" ]; then
echo "::error::VAULT_PROJECT_ID manquant (secrets org Forgejo)"
exit 1
fi
if ! command -v infisical &>/dev/null; then
curl -fsSL "https://artifacts-cli.infisical.com/infisical.gpg" | gpg --dearmor > /usr/share/keyrings/infisical-archive-keyring.gpg
chmod 644 /usr/share/keyrings/infisical-archive-keyring.gpg
echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/infisical-archive-keyring.gpg] https://artifacts-cli.infisical.com/deb stable main" > /etc/apt/sources.list.d/infisical.list
apt-get update -qq && apt-get install -y -qq infisical
fi
LOGIN_OUT=$(infisical login --method=universal-auth --client-id="$CLIENT_ID" --client-secret="$CLIENT_SECRET" --domain="$DOMAIN" --plain --silent 2>&1 || true)
TOKEN=$(printf '%s' "$LOGIN_OUT" | tail -1)
if [ -z "$TOKEN" ] || [ "$TOKEN" = "null" ]; then
echo "::error::Infisical login failed — vérifier VAULT_URL/VAULT_CLIENT_ID/VAULT_CLIENT_SECRET"
printf '%s\n' "$LOGIN_OUT" | tail -5 | sed 's/^/ /'
exit 1
fi
export INFISICAL_TOKEN="$TOKEN"
export INFISICAL_DOMAIN="$DOMAIN"
DOTENV=$(infisical export --projectId="$PROJECT_ID" --env=dev --format=dotenv 2>/tmp/infisical.err || true)
if [ -z "$DOTENV" ]; then
echo "::error::Infisical export vide — vérifier projectId/env/permissions"
tail -5 /tmp/infisical.err 2>/dev/null | sed 's/^/ /' || true
exit 1
fi
python3 scripts/ci/inject_env.py "$DOTENV"
- name: Cache NuGet (best-effort)
continue-on-error: true
uses: https://forgejo.tordais.cc/actions/cache@v4
with:
path: ~/.nuget/packages
key: nuget-${{ runner.os }}-${{ hashFiles('**/*.csproj', '**/*.slnx', '**/Directory.Build.props') }}
restore-keys: |
nuget-${{ runner.os }}-
- name: Install SonarScanner + ReportGenerator
shell: bash
run: |
export PATH="$PATH:$HOME/.dotnet/tools"
dotnet tool install --global dotnet-sonarscanner 2>/dev/null || true
dotnet tool install --global dotnet-reportgenerator-globaltool 2>/dev/null || true
- name: Résoudre la config SonarQube
id: resolve
shell: bash
run: |
HOST="${SONARQUBE_URL:-${SONAR_HOST_URL:-}}"
TOKEN="${SONARQUBE_TOKEN:-${SONAR_TOKEN:-}}"
KEY="${SONARQUBE_HEIMDALL_PROJECT_KEY:-heimdall}"
if [ -z "$HOST" ] || [ -z "$TOKEN" ]; then
echo "::error::SonarQube non configuré — SONARQUBE_URL/SONARQUBE_TOKEN absents (Infisical)"
exit 1
fi
echo "SonarQube: $KEY @ $HOST"
echo "SONAR_RESOLVED_HOST=$HOST" >> "$GITHUB_ENV"
echo "SONAR_RESOLVED_TOKEN=$TOKEN" >> "$GITHUB_ENV"
echo "SONAR_RESOLVED_KEY=$KEY" >> "$GITHUB_ENV"
- name: SonarScanner analysis
shell: bash
env:
SONAR_HOST: ${{ env.SONAR_RESOLVED_HOST }}
SONAR_TOKEN: ${{ env.SONAR_RESOLVED_TOKEN }}
SONAR_KEY: ${{ env.SONAR_RESOLVED_KEY }}
run: |
set -euo pipefail
export PATH="$PATH:$HOME/.dotnet/tools"
PR_PARAMS=""
if [ "${{ github.event_name }}" = "pull_request" ]; then
PR_PARAMS="/d:sonar.pullrequest.key=${{ github.event.pull_request.number }} /d:sonar.pullrequest.branch=${{ github.event.pull_request.number }} /d:sonar.pullrequest.base=${{ github.base_ref }} /d:sonar.analysis.sqbot=${{ github.event.pull_request.head.sha }}"
fi
dotnet restore Heimdall.slnx --nologo
dotnet sonarscanner begin \
/k:"$SONAR_KEY" /n:"$SONAR_KEY" \
/d:sonar.host.url="$SONAR_HOST" /d:sonar.token="$SONAR_TOKEN" \
/d:sonar.coverageReportPaths=./SonarQube.xml \
/d:sonar.exclusions="scripts/ci/**,.forgejo/**,docs/**,**/Migrations/**" \
$PR_PARAMS
dotnet build Heimdall.slnx -c Release --no-restore --nologo
dotnet test Heimdall.slnx -c Release --no-build --nologo \
--collect:"XPlat Code Coverage" --results-directory ./CoverageResults \
--filter "FullyQualifiedName!~Integration&FullyQualifiedName!~E2E&FullyQualifiedName!~Infrastructure" \
|| echo "::warning::dotnet test Sonar (collecte coverage) en échec — analyse sans coverage"
if ls ./CoverageResults/**/coverage.cobertura.xml &>/dev/null; then
reportgenerator -reports:./CoverageResults/**/coverage.cobertura.xml -targetdir:. -reporttypes:SonarQube \
|| echo "::warning::ReportGenerator SonarQube en échec — analyse sans coverage"
else
echo "::warning::Aucun rapport cobertura — analyse SonarQube SANS coverage"
fi
dotnet sonarscanner end /d:sonar.token="$SONAR_TOKEN"
- name: Check quality gate (bloquant)
shell: bash
env:
SONAR_HOST: ${{ env.SONAR_RESOLVED_HOST }}
SONAR_TOKEN: ${{ env.SONAR_RESOLVED_TOKEN }}
PROJECT_KEY: ${{ env.SONAR_RESOLVED_KEY }}
run: |
echo "=== SonarQube quality gate: $PROJECT_KEY ==="
GATE_CTX="projectKey=$PROJECT_KEY"
if [ "${{ github.event_name }}" = "pull_request" ]; then
GATE_CTX="$GATE_CTX&pullRequest=${{ github.event.pull_request.number }}"
fi
STATUS="PENDING"
RESP="{}"
for i in $(seq 1 18); do
sleep 5
RESP=$(curl -s -u "$SONAR_TOKEN:" "$SONAR_HOST/api/qualitygates/project_status?$GATE_CTX" 2>/dev/null || echo '{}')
STATUS=$(echo "$RESP" | python3 -c "import json,sys; print(json.load(sys.stdin).get('projectStatus',{}).get('status','PENDING'))" 2>/dev/null || echo 'PENDING')
[ "$STATUS" != "PENDING" ] && break
done
echo "Quality gate status: $STATUS"
if [ "$STATUS" != "OK" ]; then
echo "--- Détail du gate ($STATUS) :"
echo "$RESP" | python3 -m json.tool 2>/dev/null | head -60 || echo "$RESP" | head -5
echo "::error::🚨 SonarQube quality gate = $STATUS — build bloqué (retour Sonar traité obligatoirement)"
exit 1
fi
echo "✅ SonarQube quality gate OK"
# ─────────────────────────────────────────────────────────────────────────
# DOCKER BUILD + PUSH + TRIVY (même job : Trivy scanne l'image locale)
# Build main+PR ; push main (latest+sha) ; images de test PR (pr-<N>+sha)
# ─────────────────────────────────────────────────────────────────────────
docker:
name: Docker + Trivy
runs-on: debian-12
timeout-minutes: 50
steps:
- uses: https://forgejo.tordais.cc/actions/checkout@v4
with:
fetch-depth: 0
- name: Secrets Infisical (projet CI)
id: infisical
shell: bash
env:
DOMAIN: ${{ secrets.VAULT_URL }}
CLIENT_ID: ${{ secrets.VAULT_CLIENT_ID }}
CLIENT_SECRET: ${{ secrets.VAULT_CLIENT_SECRET }}
PROJECT_ID: ${{ secrets.VAULT_PROJECT_ID }}
run: |
if [ -z "$PROJECT_ID" ]; then
echo "::error::VAULT_PROJECT_ID manquant (secrets org Forgejo)"
exit 1
fi
if ! command -v infisical &>/dev/null; then
curl -fsSL "https://artifacts-cli.infisical.com/infisical.gpg" | gpg --dearmor > /usr/share/keyrings/infisical-archive-keyring.gpg
chmod 644 /usr/share/keyrings/infisical-archive-keyring.gpg
echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/infisical-archive-keyring.gpg] https://artifacts-cli.infisical.com/deb stable main" > /etc/apt/sources.list.d/infisical.list
apt-get update -qq && apt-get install -y -qq infisical
fi
LOGIN_OUT=$(infisical login --method=universal-auth --client-id="$CLIENT_ID" --client-secret="$CLIENT_SECRET" --domain="$DOMAIN" --plain --silent 2>&1 || true)
TOKEN=$(printf '%s' "$LOGIN_OUT" | tail -1)
if [ -z "$TOKEN" ] || [ "$TOKEN" = "null" ]; then
echo "::error::Infisical login failed — vérifier VAULT_URL/VAULT_CLIENT_ID/VAULT_CLIENT_SECRET"
printf '%s\n' "$LOGIN_OUT" | tail -5 | sed 's/^/ /'
exit 1
fi
export INFISICAL_TOKEN="$TOKEN"
export INFISICAL_DOMAIN="$DOMAIN"
DOTENV=$(infisical export --projectId="$PROJECT_ID" --env=dev --format=dotenv 2>/tmp/infisical.err || true)
if [ -z "$DOTENV" ]; then
echo "::error::Infisical export vide — vérifier projectId/env/permissions"
tail -5 /tmp/infisical.err 2>/dev/null | sed 's/^/ /' || true
exit 1
fi
python3 scripts/ci/inject_env.py "$DOTENV"
- name: Build + Push images
shell: bash
env:
DOCKER_IMAGES: |
eltruncho/heimdall docker/Dockerfile
eltruncho/heimdall-agent docker/Dockerfile.agent
run: |
set -euo pipefail
if ! command -v docker &>/dev/null; then
apt-get update -qq && apt-get install -y -qq --no-install-recommends docker.io
fi
# Résolution scopée par projet (Infisical) : DOCKER_HEIMDALL_TARGET/LOGIN/PASSWORD
PROJ_UPPER="HEIMDALL"
TARGET_VAR="DOCKER_${PROJ_UPPER}_TARGET"
LOGIN_VAR="DOCKER_${PROJ_UPPER}_LOGIN"
PASS_VAR="DOCKER_${PROJ_UPPER}_PASSWORD"
REGISTRY="${!TARGET_VAR:-forgejo}"
DOCKER_USER="${!LOGIN_VAR:-}"
DOCKER_PASS="${!PASS_VAR:-}"
SHA="${{ github.sha }}"
echo "Registry target: $REGISTRY"
push_dockerhub() {
local img="$1"
echo "→ Pushing $img to Docker Hub"
echo "$DOCKER_PASS" | docker login -u "$DOCKER_USER" --password-stdin || return 1
docker push "${img}:latest" || return 1
docker push "${img}:${SHA}" || true
}
push_forgejo() {
local img="$1"
if [ -z "${REGISTRY_TOKEN:-}" ] || [ -z "${REGISTRY_URL:-}" ]; then
echo "::warning::Forgejo registry not configured — skipping"
return 1
fi
echo "→ Pushing $img to Forgejo Registry"
echo "${REGISTRY_TOKEN:-}" | docker login "${REGISTRY_URL:-}" -u "${REGISTRY_USER:-nonobis}" --password-stdin || return 1
REG="${REGISTRY_URL}/${REGISTRY_USER:-nonobis}"
docker tag "${img}:latest" "$REG/$(basename "$img"):latest" 2>/dev/null || true
docker tag "${img}:${SHA}" "$REG/$(basename "$img"):${SHA}" 2>/dev/null || true
docker push "$REG/$(basename "$img"):latest" || true
docker push "$REG/$(basename "$img"):${SHA}" || true
}
# Build (main + PR)
while IFS=' ' read -r img df; do
[ -z "$img" ] && continue
echo "→ Building $img from $df"
docker build -f "$df" -t "${img}:latest" -t "${img}:${SHA}" .
done <<< "$DOCKER_IMAGES"
# Push sur main uniquement
if [ "${{ forgejo.ref }}" = "refs/heads/main" ]; then
while IFS=' ' read -r img df; do
[ -z "$img" ] && continue
if [ -n "$DOCKER_USER" ] && [ -n "$DOCKER_PASS" ]; then
if [ "$REGISTRY" = "dockerhub" ]; then
push_dockerhub "$img" || echo "::warning::Docker Hub push failed for $img"
else
push_forgejo "$img" || echo "::warning::Forgejo push failed for $img"
fi
else
echo "::warning::Credentiales registry manquantes (DOCKER_HEIMDALL_LOGIN/PASSWORD) — push ignoré"
fi
done <<< "$DOCKER_IMAGES"
fi
# Images de test sur PR : tag pr-<N> + sha (jamais latest/version)
if [ "${{ github.event_name }}" = "pull_request" ]; then
PR_NUM="${{ github.event.pull_request.number }}"
echo "→ Pushing test images for PR #$PR_NUM"
while IFS=' ' read -r img df; do
[ -z "$img" ] && continue
BASE="$(basename "$img")"
if [ -n "$DOCKER_USER" ] && [ -n "$DOCKER_PASS" ] && [ "$REGISTRY" = "dockerhub" ]; then
echo "$DOCKER_PASS" | docker login -u "$DOCKER_USER" --password-stdin || continue
docker tag "${img}:${SHA}" "${img}:pr-${PR_NUM}" 2>/dev/null || true
docker push "${img}:pr-${PR_NUM}" || echo "::warning::push pr-${PR_NUM} failed for $img"
docker push "${img}:${SHA}" || true
elif [ -n "${REGISTRY_TOKEN:-}" ] && [ -n "${REGISTRY_URL:-}" ]; then
echo "${REGISTRY_TOKEN:-}" | docker login "${REGISTRY_URL:-}" -u "${REGISTRY_USER:-nonobis}" --password-stdin || continue
REG="${REGISTRY_URL}/${REGISTRY_USER:-nonobis}"
docker tag "${img}:${SHA}" "$REG/$BASE:pr-${PR_NUM}" 2>/dev/null || true
docker push "$REG/$BASE:pr-${PR_NUM}" || echo "::warning::push pr-${PR_NUM} failed for $img"
docker push "$REG/$BASE:${SHA}" || true
else
echo "::warning::Registry non configuré pour les images de test PR — $img ignorée"
fi
done <<< "$DOCKER_IMAGES"
fi
- name: Install Trivy
shell: bash
run: |
if ! command -v trivy &>/dev/null; then
curl -sfL https://raw.githubusercontent.com/aquasecurity/trivy/main/contrib/install.sh \
| sh -s -- -b /usr/local/bin 2>/dev/null || \
(apt-get install -y -qq wget && \
wget -qO- https://github.com/aquasecurity/trivy/releases/download/v0.51.0/trivy_0.51.0_Linux-64bit.deb -O /tmp/trivy.deb && \
dpkg -i /tmp/trivy.deb && rm /tmp/trivy.deb)
fi
trivy --version | head -1
- name: Trivy scan (bloquant)
id: trivy
shell: bash
run: |
set -u
IMAGE="eltruncho/heimdall:${{ github.sha }}"
echo "=== Trivy Scan: $IMAGE (severity: HIGH,CRITICAL) ==="
trivy image --severity HIGH,CRITICAL --format json --output /tmp/trivy.json "$IMAGE" \
|| { echo "::warning::Trivy scan failed (image may not exist locally)"; echo "report=" >> "$GITHUB_OUTPUT"; echo "vuln-count=0" >> "$GITHUB_OUTPUT"; exit 0; }
COUNT=$(python3 -c "import json; d=json.load(open('/tmp/trivy.json')); print(sum(len(r.get('Vulnerabilities',[])) for r in d.get('Results',[])))" 2>/dev/null || echo 0)
echo "vuln-count=$COUNT" >> "$GITHUB_OUTPUT"
REPORT=$(python3 scripts/ci/trivy_report.py /tmp/trivy.json "HIGH,CRITICAL" 2>/dev/null || echo '')
{
echo "report<<EOF"
printf '%s' "$REPORT"
echo ""
echo "EOF"
} >> "$GITHUB_OUTPUT"
if [ -n "$REPORT" ]; then
echo "::warning::$COUNT vulnérabilité(s) HIGH/CRITICAL détectée(s)"
echo "$REPORT"
else
echo "✅ Aucune vulnérabilité HIGH/CRITICAL"
fi
if [ "$COUNT" -gt 0 ]; then
echo "::error::🚨 $COUNT vulnérabilité(s) HIGH/CRITICAL — build bloqué (Trivy bloquant)"
exit 1
fi
- name: Post Trivy report on PR
if: always() && github.event_name == 'pull_request' && steps.trivy.outputs.report != ''
shell: bash
env:
FORGEJO_TOKEN: ${{ github.token }}
REPO: ${{ github.repository }}
PR_NUMBER: ${{ github.event.pull_request.number }}
TRIVY_REPORT: ${{ steps.trivy.outputs.report }}
run: python3 scripts/ci/post_cve_comment.py
# ─────────────────────────────────────────────────────────────────────────
# DEPENDENCY-CHECK (OWASP) — bloquant, cache NVD /opt/dc-cache (volume hôte)
# ─────────────────────────────────────────────────────────────────────────
dependency-check:
name: OWASP Dependency-Check
runs-on: debian-12
timeout-minutes: 60
steps:
- uses: https://forgejo.tordais.cc/actions/checkout@v4
- name: Install Java + Dependency-Check CLI
shell: bash
run: |
if ! command -v java &>/dev/null; then
apt-get update -qq && apt-get install -y -qq --no-install-recommends openjdk-17-jre-headless
fi
if [ ! -x /opt/dependency-check/bin/dependency-check.sh ]; then
apt-get install -y -qq unzip
curl -fsSL "https://github.com/jeremylong/DependencyCheck/releases/download/v12.1.0/dependency-check-12.1.0-release.zip" -o /tmp/dc.zip
unzip -q /tmp/dc.zip -d /opt/
mv /opt/dependency-check /opt/dependency-check-bin 2>/dev/null || true
mv /opt/dependency-check-bin /opt/dependency-check 2>/dev/null || true
chmod +x /opt/dependency-check/bin/dependency-check.sh
rm -f /tmp/dc.zip
fi
/opt/dependency-check/bin/dependency-check.sh --version | head -1
- name: Scan dependencies (bloquant, failOnCVSS 7.0)
id: scan
shell: bash
run: |
set -u
mkdir -p /tmp/dc-out
echo "=== OWASP Dependency-Check: heimdall (scan: Heimdall.slnx, failOnCVSS: 7.0) ==="
NVD_ARGS=""
if [ -n "${NVD_API_KEY:-}" ]; then
NVD_ARGS="--nvdApiKey $NVD_API_KEY"
echo "NVD API key configurée (téléchargements NVD plus rapides)"
fi
# --data /opt/dc-cache : volume hôte persistant monté via container.options
# du runner (setup-dc-cache.sh) — la base NVD est téléchargée UNE fois par LXC.
SCAN_EXIT=0
/opt/dependency-check/bin/dependency-check.sh \
--scan "Heimdall.slnx" \
--project "heimdall" \
--format JSON \
--out /tmp/dc-out \
--data /opt/dc-cache \
--failOnCVSS 7.0 \
--disableAssembly \
$NVD_ARGS \
|| SCAN_EXIT=$?
REPORT=$(python3 scripts/ci/dc_report.py /tmp/dc-out/dependency-check-report.json 2>/dev/null || echo '')
COUNT=$(python3 scripts/ci/dc_report.py /tmp/dc-out/dependency-check-report.json count 2>/dev/null || echo 0)
echo "vuln-count=$COUNT" >> "$GITHUB_OUTPUT"
{
echo "report<<EOF"
printf '%s' "$REPORT"
echo ""
echo "EOF"
} >> "$GITHUB_OUTPUT"
if [ -n "$REPORT" ]; then
echo "::warning::$COUNT vulnérabilité(s) HIGH/CRITICAL détectée(s) (Dependency-Check)"
echo "$REPORT"
else
echo "✅ Dependency-Check : aucune vulnérabilité HIGH/CRITICAL"
fi
if [ "$SCAN_EXIT" -ne 0 ]; then
echo "::error::🚨 Dependency-Check a détecté des vulnérabilités bloquantes (failOnCVSS 7.0)"
exit "$SCAN_EXIT"
fi
- name: Post Dependency-Check report on PR
if: always() && github.event_name == 'pull_request' && steps.scan.outputs.report != ''
shell: bash
env:
FORGEJO_TOKEN: ${{ github.token }}
REPO: ${{ github.repository }}
PR_NUMBER: ${{ github.event.pull_request.number }}
DC_REPORT: ${{ steps.scan.outputs.report }}
run: python3 scripts/ci/post_cve_comment.py
# ─────────────────────────────────────────────────────────────────────────
# RÉSUMÉ TESTS SUR LA PR (agrégé depuis les 3 jobs de test, toujours posté)
# ─────────────────────────────────────────────────────────────────────────
post-summary:
name: Résumé tests (PR)
if: always() && github.event_name == 'pull_request'
needs: [test-unit, test-web, test-db]
runs-on: debian-12
timeout-minutes: 10
steps:
- uses: https://forgejo.tordais.cc/actions/checkout@v4
- name: Agréger et poster le résumé
shell: bash
env:
FORGEJO_TOKEN: ${{ github.token }}
REPO: ${{ github.repository }}
PR_NUMBER: ${{ github.event.pull_request.number }}
S_UNIT: ${{ needs.test-unit.outputs.summary }}
S_WEB: ${{ needs.test-web.outputs.summary }}
S_DB: ${{ needs.test-db.outputs.summary }}
run: |
{
printf '%s\n\n---\n\n' "**Tests unitaires**"
printf '%s\n\n' "$S_UNIT"
printf '%s\n\n---\n\n' "**Tests Web (bUnit)**"
printf '%s\n\n' "$S_WEB"
printf '%s\n\n---\n\n' "**Tests DB (Infrastructure + Integration)**"
printf '%s\n' "$S_DB"
} > /tmp/full-summary.md
python3 scripts/ci/post_comment.py "$(cat /tmp/full-summary.md)" "Résumé des tests"