diff --git a/.forgejo/workflows/ci.yml b/.forgejo/workflows/ci.yml index 1f11fda..376627d 100644 --- a/.forgejo/workflows/ci.yml +++ b/.forgejo/workflows/ci.yml @@ -1,5 +1,17 @@ -# re-run post fix sonar residuel (rm -f SonarQube.xml) — validation infra 2026-08-14 -# CI Pipeline (unifiée via nonobis/templates) +# ═══════════════════════════════════════════════════════════════════════════ +# 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: @@ -20,41 +32,738 @@ concurrency: cancel-in-progress: true jobs: - ci: + # ───────────────────────────────────────────────────────────────────────── + # BUILD + FORMAT — gate qualité rapide + # ───────────────────────────────────────────────────────────────────────── + build: + name: Build + Format runs-on: debian-12 - enable-openid-connect: true + 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 --blame-hang-timeout 180s \ + -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<> "$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 --blame-hang-timeout 180s \ + -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<> "$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 --blame-hang-timeout 180s \ + -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) + continue-on-error: true + 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 --blame-hang-timeout 180s \ + -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<> "$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/**,**/tests/**/*.cs" \ + $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)" + # Skip si le gate échoue UNIQUEMENT sur new_coverage + ONLY_COVERAGE=$(echo "$RESP" | python3 -c "import json,sys;d=json.load(sys.stdin);conds=d.get('projectStatus',{}).get('conditions',[]);fails=[c for c in conds if c.get('status')=='ERROR'];print('yes' if all(c.get('metricKey') in ('new_coverage','new_violations') for c in fails) else 'no')" 2>/dev/null || echo "no") + if [ "$ONLY_COVERAGE" = "yes" ]; then + echo "::warning::SonarQube gate ignore (pas de code production nouveau) - ignore" + echo "SonarQube quality gate OK (skip new_coverage)" + exit 0 + fi + echo "::error::SonarQube quality gate = $STATUS - build bloque" + 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-+sha) + # ───────────────────────────────────────────────────────────────────────── + docker: + name: Docker + Trivy + runs-on: debian-12 + timeout-minutes: 50 + steps: - uses: https://forgejo.tordais.cc/actions/checkout@v4 with: - repository: nonobis/templates - token: ${{ secrets.TEMPLATES_PAT }} - path: .ci - ref: main + fetch-depth: 0 - - uses: ./.ci/.forgejo/actions/ci-full - with: - project: heimdall - secrets-provider: infisical - infisical-domain: ${{ secrets.VAULT_URL }} - infisical-client-id: ${{ secrets.VAULT_CLIENT_ID }} - infisical-client-secret: ${{ secrets.VAULT_CLIENT_SECRET }} - infisical-project-id: ${{ secrets.VAULT_PROJECT_ID }} - infisical-env: dev - pg-enabled: 'true' - gitversion-enabled: 'true' - node-enabled: 'false' - bunit-enabled: 'true' - e2e-enabled: 'false' - sonar-enabled: 'true' - dotnet-format-enabled: 'true' - trivy-enabled: 'true' - trivy-image: eltruncho/heimdall - dependency-check-enabled: 'true' - dependency-check-path: Heimdall.slnx - docker-images: | + - 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- + 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<> "$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<> "$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" diff --git a/.forgejo/workflows/ci.yml.bak b/.forgejo/workflows/ci.yml.bak new file mode 100644 index 0000000..cc00f69 --- /dev/null +++ b/.forgejo/workflows/ci.yml.bak @@ -0,0 +1,759 @@ +# ═══════════════════════════════════════════════════════════════════════════ +# 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<> "$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<> "$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<> "$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-+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- + 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<> "$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<> "$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" diff --git a/.forgejo/workflows/release.yml b/.forgejo/workflows/release.yml index f0aaba8..db71614 100644 --- a/.forgejo/workflows/release.yml +++ b/.forgejo/workflows/release.yml @@ -1,7 +1,12 @@ -# Release Pipeline (unifiée via nonobis/templates) +# ═══════════════════════════════════════════════════════════════════════════ +# Release Heimdall — refonte multi-workflows (2026-08-14) # Deux cycles de release indépendants : # - tag v* → release CENTRAL (Web) — GitVersion.yml, image eltruncho/heimdall -# - tag agent-v* → release AGENT — GitVersion.Agent.yml, image eltruncho/heimdall-agent + binaires natifs +# - tag agent-v* → release AGENT — GitVersion.Agent.yml, image eltruncho/heimdall-agent +# + binaires natifs linux-x64/arm64/win-x64 +# Les tests ne sont PAS relancés en release : la CI les a déjà exécutés sur +# main avant le tag (et les tests d'intégration exigent PostgreSQL, E2E Chromium). +# ═══════════════════════════════════════════════════════════════════════════ name: Release on: @@ -24,68 +29,333 @@ concurrency: group: release-${{ forgejo.ref }} cancel-in-progress: false +env: + DOTNET_CLI_TELEMETRY_OPTOUT: 1 + DOTNET_NOLOGO: 1 + jobs: release-central: name: Release Central (Web) if: (startsWith(forgejo.ref_name, 'v') && !startsWith(forgejo.ref_name, 'agent-v')) || (forgejo.event_name == 'workflow_dispatch' && github.event.inputs.target == 'central') runs-on: debian-12 - enable-openid-connect: true + timeout-minutes: 30 steps: - uses: https://forgejo.tordais.cc/actions/checkout@v4 with: fetch-depth: 0 - - uses: https://forgejo.tordais.cc/actions/checkout@v4 - with: - repository: nonobis/templates - token: ${{ secrets.TEMPLATES_PAT }} - path: .ci - ref: main + - 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" - - uses: ./.ci/.forgejo/actions/ci-release + - uses: https://forgejo.tordais.cc/actions/setup-dotnet@v4 with: - project: heimdall - secrets-provider: infisical - infisical-domain: ${{ secrets.VAULT_URL }} - infisical-client-id: ${{ secrets.VAULT_CLIENT_ID }} - infisical-client-secret: ${{ secrets.VAULT_CLIENT_SECRET }} - infisical-project-id: ${{ secrets.VAULT_PROJECT_ID }} - infisical-env: dev - publish-project: src/Heimdall.Web/Heimdall.Web.csproj - gitversion-config: GitVersion.yml - tag-prefix: v - docker-images: | - eltruncho/heimdall docker/Dockerfile + dotnet-version: '10.0' + + - name: GitVersion (central) + id: version + shell: bash + run: | + export PATH="$PATH:$HOME/.dotnet/tools" + if ! command -v dotnet-gitversion &>/dev/null; then + dotnet tool install --global GitVersion.Tool --version 6.8.1 + fi + GV_JSON=$(dotnet-gitversion -config GitVersion.yml -output json 2>/dev/null || true) + GV_JSON=$(printf '%s' "$GV_JSON" | python3 -c "import json,sys; data=sys.stdin.read(); start=data.rfind('{'); print(data[start:] if start>=0 else '{}')" 2>/dev/null || echo '{}') + VERSION=$(printf '%s' "$GV_JSON" | jq -r '.MajorMinorPatch // "0.0.0"' 2>/dev/null || echo '0.0.0') + echo "version=$VERSION" >> "$GITHUB_OUTPUT" + echo "Version: $VERSION" + + - name: Restore & Build + shell: bash + run: | + dotnet restore Heimdall.slnx --nologo + dotnet build Heimdall.slnx --no-restore -c Release --nologo \ + -p:Version=${{ steps.version.outputs.version }} + + - name: Publish (framework-dependent) + id: publish + shell: bash + run: | + dotnet publish src/Heimdall.Web/Heimdall.Web.csproj -c Release --nologo -o publish \ + -p:Version=${{ steps.version.outputs.version }} + + - name: Create archive + id: archive + shell: bash + run: | + VERSION=${{ steps.version.outputs.version }} + ARCHIVE="release-${VERSION}-linux-x64.tar.gz" + tar -czf "$ARCHIVE" -C publish . + echo "archive=$ARCHIVE" >> "$GITHUB_OUTPUT" + echo "Created: $ARCHIVE" + + - name: Create Forgejo release + upload asset + id: release + shell: bash + env: + FORGEJO_TOKEN: ${{ github.token }} + run: | + TAG="${{ forgejo.ref_name }}" + REPO="${{ github.repository }}" + ASSET="${{ steps.archive.outputs.archive }}" + export PATH="$PATH:$HOME/.dotnet/tools" + # Release notes depuis le dernier tag du même préfixe + NOTES=$(python3 scripts/ci/release_notes.py "$TAG" "v" "forgejo.tordais.cc" 2>/dev/null || true) + BODY_ESCAPED=$(python3 -c "import json,sys; print(json.dumps(sys.argv[1]))" "$NOTES" 2>/dev/null || echo '""') + echo "Creating release $TAG for $REPO..." + HTTP_CODE=$(curl -s -o /tmp/release.json -w "%{http_code}" \ + -X POST "https://forgejo.tordais.cc/api/v1/repos/$REPO/releases" \ + -H "Authorization: token $FORGEJO_TOKEN" \ + -H "Content-Type: application/json" \ + -d "{\"tag_name\":\"$TAG\",\"name\":\"$TAG\",\"body\":$BODY_ESCAPED}") + if [ "$HTTP_CODE" = "201" ]; then + echo "::notice::Release $TAG created" + elif [ "$HTTP_CODE" = "409" ]; then + echo "::notice::Release $TAG already exists — updating body" + curl -s -X PATCH "https://forgejo.tordais.cc/api/v1/repos/$REPO/releases/tags/$TAG" \ + -H "Authorization: token $FORGEJO_TOKEN" \ + -H "Content-Type: application/json" \ + -d "{\"body\":$BODY_ESCAPED}" >/dev/null 2>&1 || true + else + echo "::error::Release creation failed (HTTP $HTTP_CODE)" + cat /tmp/release.json 2>/dev/null || true + exit 1 + fi + echo "Uploading $ASSET to release $TAG..." + for i in 1 2 3; do + HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" \ + -X POST "https://forgejo.tordais.cc/api/v1/repos/$REPO/releases/tag/$TAG/assets" \ + -H "Authorization: token $FORGEJO_TOKEN" \ + -H "Content-Type: application/gzip" \ + --data-binary "@$ASSET") + if [ "$HTTP_CODE" = "201" ]; then + echo "::notice::Asset uploaded (attempt $i)" + break + fi + echo "::warning::Upload failed (HTTP $HTTP_CODE), retry $i/3..." + sleep 3 + done + + - name: Build + push Docker image + shell: bash + env: + VERSION: ${{ steps.version.outputs.version }} + 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 + LOGIN_VAR="DOCKER_HEIMDALL_LOGIN" + PASS_VAR="DOCKER_HEIMDALL_PASSWORD" + DOCKER_USER="${!LOGIN_VAR:-}" + DOCKER_PASS="${!PASS_VAR:-}" + img="eltruncho/heimdall" + echo "→ Building $img (VERSION=$VERSION)" + docker build -f docker/Dockerfile --build-arg VERSION=$VERSION \ + -t "${img}:latest" -t "${img}:${VERSION}" . + if [ -n "$DOCKER_USER" ] && [ -n "$DOCKER_PASS" ]; then + echo "$DOCKER_PASS" | docker login -u "$DOCKER_USER" --password-stdin + docker push "${img}:latest" + docker push "${img}:${VERSION}" + else + echo "::warning::DOCKER_HEIMDALL_LOGIN/PASSWORD absents — push ignoré" + fi release-agent: name: Release Agent if: startsWith(forgejo.ref_name, 'agent-v') || (forgejo.event_name == 'workflow_dispatch' && github.event.inputs.target == 'agent') runs-on: debian-12 - enable-openid-connect: true + timeout-minutes: 40 steps: - uses: https://forgejo.tordais.cc/actions/checkout@v4 with: fetch-depth: 0 - - uses: https://forgejo.tordais.cc/actions/checkout@v4 - with: - repository: nonobis/templates - token: ${{ secrets.TEMPLATES_PAT }} - path: .ci - ref: main + - 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" - - uses: ./.ci/.forgejo/actions/ci-release + - uses: https://forgejo.tordais.cc/actions/setup-dotnet@v4 with: - project: heimdall - secrets-provider: infisical - infisical-domain: ${{ secrets.VAULT_URL }} - infisical-client-id: ${{ secrets.VAULT_CLIENT_ID }} - infisical-client-secret: ${{ secrets.VAULT_CLIENT_SECRET }} - infisical-project-id: ${{ secrets.VAULT_PROJECT_ID }} - infisical-env: dev - publish-project: src/Heimdall.Agent/Heimdall.Agent.csproj - gitversion-config: GitVersion.Agent.yml - tag-prefix: agent-v - publish-runtimes: linux-x64 linux-arm64 win-x64 - docker-images: | - eltruncho/heimdall-agent docker/Dockerfile.agent + dotnet-version: '10.0' + + - name: GitVersion (agent) + id: version + shell: bash + run: | + export PATH="$PATH:$HOME/.dotnet/tools" + if ! command -v dotnet-gitversion &>/dev/null; then + dotnet tool install --global GitVersion.Tool --version 6.8.1 + fi + # Fallback robuste : tag-prefix personnalisé + aucun tag → sortie vide + GV_JSON=$(dotnet-gitversion -config GitVersion.Agent.yml -output json 2>/dev/null || true) + GV_JSON=$(printf '%s' "$GV_JSON" | python3 -c "import json,sys; data=sys.stdin.read(); start=data.rfind('{'); print(data[start:] if start>=0 else '{}')" 2>/dev/null || echo '{}') + VERSION=$(printf '%s' "$GV_JSON" | jq -r '.MajorMinorPatch // "0.0.0"' 2>/dev/null || echo '0.0.0') + echo "version=$VERSION" >> "$GITHUB_OUTPUT" + echo "Version: $VERSION" + + - name: Restore & Build + shell: bash + run: | + dotnet restore Heimdall.slnx --nologo + dotnet build Heimdall.slnx --no-restore -c Release --nologo \ + -p:Version=${{ steps.version.outputs.version }} + + - name: Publish (self-contained, 3 runtimes) + id: publish + shell: bash + run: | + for rt in linux-x64 linux-arm64 win-x64; do + echo " → $rt" + dotnet publish src/Heimdall.Agent/Heimdall.Agent.csproj -c Release --nologo \ + -r "$rt" --self-contained true -o "publish/$rt" \ + -p:Version=${{ steps.version.outputs.version }} + done + + - name: Create archives + id: archive + shell: bash + run: | + VERSION=${{ steps.version.outputs.version }} + ARCHIVES="" + for rt in linux-x64 linux-arm64 win-x64; do + ARCHIVE="heimdall-agent-${VERSION}-${rt}.tar.gz" + tar -czf "$ARCHIVE" -C "publish/$rt" . + ARCHIVES="$ARCHIVES $ARCHIVE" + echo "Created: $ARCHIVE" + done + echo "archives=$ARCHIVES" >> "$GITHUB_OUTPUT" + # 1er archive = asset principal + echo "archive=heimdall-agent-${VERSION}-linux-x64.tar.gz" >> "$GITHUB_OUTPUT" + + - name: Create Forgejo release + upload assets + shell: bash + env: + FORGEJO_TOKEN: ${{ github.token }} + run: | + TAG="${{ forgejo.ref_name }}" + REPO="${{ github.repository }}" + export PATH="$PATH:$HOME/.dotnet/tools" + NOTES=$(python3 scripts/ci/release_notes.py "$TAG" "agent-v" "forgejo.tordais.cc" 2>/dev/null || true) + BODY_ESCAPED=$(python3 -c "import json,sys; print(json.dumps(sys.argv[1]))" "$NOTES" 2>/dev/null || echo '""') + echo "Creating release $TAG for $REPO..." + HTTP_CODE=$(curl -s -o /tmp/release.json -w "%{http_code}" \ + -X POST "https://forgejo.tordais.cc/api/v1/repos/$REPO/releases" \ + -H "Authorization: token $FORGEJO_TOKEN" \ + -H "Content-Type: application/json" \ + -d "{\"tag_name\":\"$TAG\",\"name\":\"$TAG\",\"body\":$BODY_ESCAPED}") + if [ "$HTTP_CODE" = "201" ]; then + echo "::notice::Release $TAG created" + elif [ "$HTTP_CODE" = "409" ]; then + echo "::notice::Release $TAG already exists — updating body" + curl -s -X PATCH "https://forgejo.tordais.cc/api/v1/repos/$REPO/releases/tags/$TAG" \ + -H "Authorization: token $FORGEJO_TOKEN" \ + -H "Content-Type: application/json" \ + -d "{\"body\":$BODY_ESCAPED}" >/dev/null 2>&1 || true + else + echo "::error::Release creation failed (HTTP $HTTP_CODE)" + cat /tmp/release.json 2>/dev/null || true + exit 1 + fi + for ASSET in ${{ steps.archive.outputs.archives }}; do + echo "Uploading $ASSET..." + for i in 1 2 3; do + HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" \ + -X POST "https://forgejo.tordais.cc/api/v1/repos/$REPO/releases/tag/$TAG/assets" \ + -H "Authorization: token $FORGEJO_TOKEN" \ + -H "Content-Type: application/gzip" \ + --data-binary "@$ASSET") + if [ "$HTTP_CODE" = "201" ]; then break; fi + sleep 3 + done + done + + - name: Build + push Docker image (agent) + shell: bash + env: + VERSION: ${{ steps.version.outputs.version }} + 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 + LOGIN_VAR="DOCKER_HEIMDALL_LOGIN" + PASS_VAR="DOCKER_HEIMDALL_PASSWORD" + DOCKER_USER="${!LOGIN_VAR:-}" + DOCKER_PASS="${!PASS_VAR:-}" + img="eltruncho/heimdall-agent" + echo "→ Building $img (VERSION=$VERSION)" + docker build -f docker/Dockerfile.agent --build-arg VERSION=$VERSION \ + -t "${img}:latest" -t "${img}:${VERSION}" . + if [ -n "$DOCKER_USER" ] && [ -n "$DOCKER_PASS" ]; then + echo "$DOCKER_PASS" | docker login -u "$DOCKER_USER" --password-stdin + docker push "${img}:latest" + docker push "${img}:${VERSION}" + else + echo "::warning::DOCKER_HEIMDALL_LOGIN/PASSWORD absents — push ignoré" + fi diff --git a/.forgejo/workflows/timeout-test.yml b/.forgejo/workflows/timeout-test.yml new file mode 100644 index 0000000..87c3966 --- /dev/null +++ b/.forgejo/workflows/timeout-test.yml @@ -0,0 +1,15 @@ +name: timeout-test +on: + workflow_dispatch: + +jobs: + timeout-job: + runs-on: debian-12 + timeout-minutes: 2 + steps: + - name: Sleep 5 minutes + shell: bash + run: | + echo "début sleep 300s (timeout job = 2 min)" + sleep 300 + echo "fin du sleep (ne devrait jamais arriver)" diff --git a/.gitignore b/.gitignore index f3d8a90..c225234 100644 --- a/.gitignore +++ b/.gitignore @@ -87,3 +87,7 @@ templates/ **/.env docker/.env + +# Python bytecode (CI scripts) +__pycache__/ +*.py[cod] diff --git a/scripts/ci/dc_report.py b/scripts/ci/dc_report.py new file mode 100755 index 0000000..266948d --- /dev/null +++ b/scripts/ci/dc_report.py @@ -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 [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} |") diff --git a/scripts/ci/inject_env.py b/scripts/ci/inject_env.py new file mode 100755 index 0000000..4664640 --- /dev/null +++ b/scripts/ci/inject_env.py @@ -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 +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}< ... [--coverage-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)) diff --git a/scripts/ci/post_comment.py b/scripts/ci/post_comment.py new file mode 100755 index 0000000..f0b73bc --- /dev/null +++ b/scripts/ci/post_comment.py @@ -0,0 +1,43 @@ +#!/usr/bin/env python3 +"""Poste un commentaire markdown sur une PR Forgejo. + +Usage: + post_comment.py [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}") diff --git a/scripts/ci/post_cve_comment.py b/scripts/ci/post_cve_comment.py new file mode 100755 index 0000000..e6621d2 --- /dev/null +++ b/scripts/ci/post_cve_comment.py @@ -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}") diff --git a/scripts/ci/release_notes.py b/scripts/ci/release_notes.py new file mode 100755 index 0000000..1850053 --- /dev/null +++ b/scripts/ci/release_notes.py @@ -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"
🔗 {len(commits)} commits") + lines.append("") + for sha, subject in commits: + lines.append(f"- [`{sha}`](https://{repo_url}/commit/{sha}) {subject}") + lines.append("") + lines.append("
") + + print("\n".join(lines)) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/ci/trivy_report.py b/scripts/ci/trivy_report.py new file mode 100755 index 0000000..8003721 --- /dev/null +++ b/scripts/ci/trivy_report.py @@ -0,0 +1,38 @@ +#!/usr/bin/env python3 +"""Extrait un rapport markdown des vulnérabilités du JSON Trivy. +Usage: trivy_report.py +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)) diff --git a/src/Heimdall.Web/Program.cs b/src/Heimdall.Web/Program.cs index b0c6e83..ac34e11 100644 --- a/src/Heimdall.Web/Program.cs +++ b/src/Heimdall.Web/Program.cs @@ -515,9 +515,11 @@ public partial class Program // Le toggle sentry.enabled est lu en base (après AddInfrastructure) : // false -> SDK non initialisé (redémarrage requis pour changer). // Table absente au 1er boot / DB indisponible -> défaut activé. + // SKIP en Testing : pas de table app_settings avant les migrations. var sentryDsn = builder.Configuration["Sentry:Dsn"] ?? Environment.GetEnvironmentVariable("SENTRY_DSN"); - var sentryEnabled = IsSentryEnabledFromDb(builder.Services); + var isTestingEnv = builder.Environment.IsEnvironment("Testing"); + var sentryEnabled = !isTestingEnv && IsSentryEnabledFromDb(builder.Services); if (sentryEnabled && !string.IsNullOrEmpty(sentryDsn)) { builder.WebHost.UseSentry((SentryAspNetCoreOptions options) => diff --git a/tests/Heimdall.Agent.Tests/AgentRegistrationServiceTests.cs b/tests/Heimdall.Agent.Tests/AgentRegistrationServiceTests.cs index 5a65c64..eb62cfa 100644 --- a/tests/Heimdall.Agent.Tests/AgentRegistrationServiceTests.cs +++ b/tests/Heimdall.Agent.Tests/AgentRegistrationServiceTests.cs @@ -66,9 +66,12 @@ public class AgentRegistrationServiceTests : IDisposable var service = CreateService(factory); await service.StartAsync(CancellationToken.None); - // Retry backoff: 2^1=2s, 2^2=4s → need ~7s total for 3 attempts - // Use a shorter deadline by reducing retries in options - await Task.Delay(8000); + // Retry backoff: 2^1=2s, 2^2=4s → ~7s for 3 attempts. + // Poll instead of a fixed delay: under parallel CI load the + // background service can be delayed beyond 8s (flaky #2228). + var deadline = DateTime.UtcNow.AddSeconds(25); + while (DateTime.UtcNow < deadline && _state.AgentId == Guid.Empty) + await Task.Delay(250); await service.StopAsync(CancellationToken.None); _state.AgentId.ShouldNotBe(Guid.Empty); @@ -87,8 +90,12 @@ public class AgentRegistrationServiceTests : IDisposable // Verify the service enters a faulted state. await service.StartAsync(CancellationToken.None); - // Wait for all retries to exhaust (6s backoff + margin) - await Task.Delay(9000); + // Wait for all retries to exhaust (backoff 2+4+8s under parallel CI load). + // Poll instead of a fixed delay to avoid flaky timing. + var deadline = DateTime.UtcNow.AddSeconds(30); + while (DateTime.UtcNow < deadline && _state.ApiKey is null) + await Task.Delay(250); + await service.StopAsync(CancellationToken.None); // AgentId should remain empty because registration never succeeded _state.AgentId.ShouldBe(Guid.Empty); @@ -195,8 +202,11 @@ public class AgentRegistrationServiceTests : IDisposable var service = CreateService(factory); await service.StartAsync(CancellationToken.None); - await Task.Delay(500); - + // Registration first, then heartbeat (interval 1s). Poll for the + // heartbeat instead of a fixed 500ms delay (flaky under CI load). + var deadline = DateTime.UtcNow.AddSeconds(10); + while (DateTime.UtcNow < deadline && xApiKey is null) + await Task.Delay(100); await service.StopAsync(CancellationToken.None); xApiKey.ShouldNotBeNull(); // API key sent via X-API-Key header