Files
Heimdall/.forgejo/workflows/ci.yml
T
Arnaud Dartois 4792b69e46 feat(agent): télémétrie inventaire matériel — CPU/mémoire/disque/GPU/OS/réseau (Fixes #82 #83 #84 #85) (#137)
## Contexte

Implémentation des tickets #82, #83, #84, #85 — télémétrie inventaire matériel agent. L'objectif est de fournir au central un maximum d'informations sur les machines des agents (CPU, mémoire, disques, GPU, OS, réseau, conteneur) sans SSH.

## Changements

### Nouveaux collecteurs (src/Heimdall.Agent/Services/)
- **CpuInfoProvider** : parse `/proc/cpuinfo` (vendor, modèle, cœurs physiques/logiques, fréquence, flags AVX/AVX2/FMA/AVX512, cache), topologie, détection cgroup CPU (`/sys/fs/cgroup/cpu.max` v2)
- **DiskInventoryProvider** : énumère les montages (`/proc/mounts`), capacité/libre/type SSD/HDD via `/sys/block/*/queue/rotation`
- **GpuInventoryProvider** : nvidia-smi, sysfs DRM, vainfo, rocm-smi avec fallback silencieux, multi-GPU
- **HostInfoProvider** : os-release, uname, `/proc/uptime` (uptime machine ≠ process), températures sysfs
- **ContainerInfoProvider** : détection Docker (/.dockerenv, cgroup), ID conteneur, limites CPU/mémoire

### Refonte SystemMetricsProvider
- Séparation host vs process (RAM machine ≠ RAM conteneur ≠ WorkingSet64)
- Uptime machine (`/proc/uptime`) distinct de l'uptime process
- Mémoire swap

### Entité Agent + Migration
- Champs structurés CPU/mémoire/disque/GPU/OS/réseau (tous nullable, rétrocompatible)
- Migration EF `AddAgentTelemetryInventory`

### Transport heartbeat
- Inventaire au register + refresh périodique (5 min, pas à chaque tick)
- Champs JSON pour listes (disques, GPU, interfaces réseau, températures)

### UI Admin (AgentDetail.razor)
- Sections CPU, Mémoire/Disques, GPU, Machine/Conteneur avec barres de progression et badges

### Tests
- 40+ tests unitaires : providers, handlers, entité Agent
- Total : 999 tests verts (Domain 149, Application 397, Agent 210, Web 243)

## Tickets liés
- Fixes #82 — CPU inventory
- Fixes #83 — Mémoire & disque
- Fixes #84 — GPU inventory
- Fixes #85 — OS, conteneur, réseau

## Résultats des tests
- `dotnet build` : 0 erreur, 0 warning
- Domain.Tests : 149 passed
- Application.Tests : 397 passed
- Agent.Tests : 210 passed
- Web.Tests : 243 passed
- Total : 999 tests ✅

## Checklist
- [x] `dotnet build` vert (TreatWarningsAsErrors)
- [x] Tests unitaires verts
- [x] Migration EF créée
- [x] Champs nullable (rétrocompatible)
- [x] Pas de référence Infrastructure dans les contrôleurs
- [x] Collecteurs avec fallback silencieux (pas de crash sans GPU/Docker/sysfs)

Reviewed-on: https://forgejo.tordais.cc/nonobis/Heimdall/pulls/137
2026-08-20 14:13:06 +02:00

778 lines
35 KiB
YAML

# ═══════════════════════════════════════════════════════════════════════════
# CI Heimdall — optimisée v2 (2026-08-18)
#
# PRINCIPES :
# • Build une seule fois → upload artifacts → tous les jobs de test
# téléchargent les artefacts au lieu de rebuild
# • Filtrage intelligent : chaque job ne tourne que si pertinent
# • Docker uniquement sur push main (pas de PR — gaspillage runner)
# • SonarQube non bloquant (analyse visible, gate en warning)
# • Nightly complet à 4h UTC
# ═══════════════════════════════════════════════════════════════════════════
name: CI
on:
push:
branches: [main]
pull_request:
branches: [main]
schedule:
- cron: '0 4 * * *'
workflow_dispatch:
env:
DOTNET_CLI_TELEMETRY_OPTOUT: 1
DOTNET_NOLOGO: 1
DOTNET_SKIP_FIRST_TIME_EXPERIENCE: 1
concurrency:
group: ci-${{ forgejo.ref }}
cancel-in-progress: true
jobs:
# ─────────────────────────────────────────────────────────────────────────
# CHANGES DETECTION
# ─────────────────────────────────────────────────────────────────────────
changes:
name: Détection changements
runs-on: debian-12
timeout-minutes: 5
outputs:
web_changed: ${{ steps.filter.outputs.web }}
db_changed: ${{ steps.filter.outputs.db }}
deps_changed: ${{ steps.filter.outputs.deps }}
steps:
- uses: https://forgejo.tordais.cc/actions/checkout@v4
with:
fetch-depth: 0
- name: Detect changed files
id: filter
shell: bash
run: |
if [ "${{ github.event_name }}" = "schedule" ]; then
echo "Nightly run — all checks enabled"
echo "web=true" >> "$GITHUB_OUTPUT"
echo "db=true" >> "$GITHUB_OUTPUT"
echo "deps=true" >> "$GITHUB_OUTPUT"
exit 0
fi
if [ "${{ github.event_name }}" = "pull_request" ]; then
BASE="${{ github.event.pull_request.base.sha }}"
HEAD="${{ github.event.pull_request.head.sha }}"
else
BASE="${{ github.event.before }}"
HEAD="${{ github.sha }}"
fi
if [ -z "$BASE" ] || [ "$BASE" = "0000000000000000000000000000000000000000" ]; then
echo "First push — all checks enabled"
echo "web=true" >> "$GITHUB_OUTPUT"
echo "db=true" >> "$GITHUB_OUTPUT"
echo "deps=true" >> "$GITHUB_OUTPUT"
exit 0
fi
CHANGED=$(git diff --name-only "$BASE"..."$HEAD" 2>/dev/null || echo "")
if [ -z "$CHANGED" ]; then
echo "No changes — all checks enabled"
echo "web=true" >> "$GITHUB_OUTPUT"
echo "db=true" >> "$GITHUB_OUTPUT"
echo "deps=true" >> "$GITHUB_OUTPUT"
exit 0
fi
echo "$CHANGED" | head -20
if echo "$CHANGED" | grep -qE '\.(razor|css)$|^src/Heimdall\.Web/|^tests/Heimdall\.Web\.Tests/'; then
echo "web=true" >> "$GITHUB_OUTPUT"
else
echo "web=false" >> "$GITHUB_OUTPUT"
fi
if echo "$CHANGED" | grep -qE '^src/Heimdall\.Infrastructure/|^src/Heimdall\.Application/|^src/Heimdall\.Domain/|^tests/Heimdall\.Infrastructure\.Tests/|^tests/Heimdall\.IntegrationTests/'; then
echo "db=true" >> "$GITHUB_OUTPUT"
else
echo "db=false" >> "$GITHUB_OUTPUT"
fi
if echo "$CHANGED" | grep -qE '\.csproj$|\.slnx$|Directory\.Build\.props$'; then
echo "deps=true" >> "$GITHUB_OUTPUT"
else
echo "deps=false" >> "$GITHUB_OUTPUT"
fi
# ─────────────────────────────────────────────────────────────────────────
# BUILD UNIQUE — upload artifacts pour tous les jobs suivants
# ─────────────────────────────────────────────────────────────────────────
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
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
# Réduire l'artifact : ne garder que le runtime linux-x64 (seul utilisé en CI).
# Sans RID, bin/ contient ~520 MB de runtimes multi-plateforme inutiles → artifact
# de 809 MB qui sature les runners (flaky 'context deadline exceeded').
- name: Réduire build (garder runtime linux-x64)
shell: bash
run: |
set -euo pipefail
find src tests -type d -path '*/runtimes' -not -path '*/obj/*' 2>/dev/null | while read -r d; do
for f in "$d"/*; do
[ "$(basename "$f")" = "linux-x64" ] || rm -rf "$f"
done
done
echo "Taille artifact finale:"
du -sh src tests 2>/dev/null | sort -rh | head -5
- name: Upload build artifacts
uses: https://forgejo.tordais.cc/actions/upload-artifact@v3
with:
name: build-output
path: |
src/**/bin/Release/
src/**/obj/Release/
tests/**/bin/Release/
tests/**/obj/Release/
retention-days: 1
# ─────────────────────────────────────────────────────────────────────────
# TESTS UNITAIRES — download artifacts (pas de rebuild)
# ─────────────────────────────────────────────────────────────────────────
test-unit:
name: Tests unitaires
needs: [build]
runs-on: debian-12
timeout-minutes: 15
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: Download build artifacts
uses: https://forgejo.tordais.cc/actions/download-artifact@v3
with:
name: build-output
- 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"
# Warm-up dotnet UNE fois (first-time-use / NuGet-Migrations) avant la
# parallélisation : évite la course sur /tmp/.dotnet/shm (mutex EEXIST)
# quand plusieurs dotnet test démarrent simultanément (flaky intermittent).
dotnet msbuild -version >/dev/null 2>&1
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 "::$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) — download artifacts
# ─────────────────────────────────────────────────────────────────────────
test-web:
name: Tests Web (bUnit)
needs: [build, changes]
if: needs.changes.outputs.web_changed == 'true'
runs-on: debian-12
timeout-minutes: 15
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: Download build artifacts
uses: https://forgejo.tordais.cc/actions/download-artifact@v3
with:
name: build-output
- 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<<EOF"
printf '%s\n' "$SUMMARY"
echo "EOF"
} >> "$GITHUB_OUTPUT"
# ─────────────────────────────────────────────────────────────────────────
# TESTS DB — download artifacts + PostgreSQL local
# ─────────────────────────────────────────────────────────────────────────
test-db:
name: Tests DB (Infrastructure)
needs: [build, changes]
if: needs.changes.outputs.db_changed == 'true'
runs-on: debian-12
timeout-minutes: 15
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: Download build artifacts
uses: https://forgejo.tordais.cc/actions/download-artifact@v3
with:
name: build-output
- name: Start PostgreSQL
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"
- name: Run Infrastructure tests
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: 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 (non bloquant, gate en warning)
# ─────────────────────────────────────────────────────────────────────────
sonar:
name: SonarQube
needs: [build]
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: Download build artifacts
uses: https://forgejo.tordais.cc/actions/download-artifact@v3
with:
name: build-output
- name: Secrets Infisical
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 "::warning::VAULT_PROJECT_ID manquant — SonarQube skipped"
echo "sonar_skip=true" >> "$GITHUB_OUTPUT"
exit 0
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 "::warning::Infisical login failed"
echo "sonar_skip=true" >> "$GITHUB_OUTPUT"
exit 0
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 "::warning::Infisical export vide"
echo "sonar_skip=true" >> "$GITHUB_OUTPUT"
exit 0
fi
python3 scripts/ci/inject_env.py "$DOTENV"
echo "sonar_skip=false" >> "$GITHUB_OUTPUT"
- name: SonarScanner analysis
if: steps.infisical.outputs.sonar_skip != 'true'
shell: bash
run: |
set -euo pipefail
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
HOST="${SONARQUBE_URL:-${SONAR_HOST_URL:-}}"
TOKEN="${SONARQUBE_TOKEN:-${SONAR_TOKEN:-}}"
KEY="${SONARQUBE_HEIMDALL_PROJECT_KEY:-heimdall}"
if [ -z "$HOST" ] || [ -z "$TOKEN" ]; then
echo "::warning::SonarQube non configuré"
exit 0
fi
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=main /d:sonar.analysis.sqbot=${{ github.sha }}"
fi
dotnet restore Heimdall.slnx --nologo
dotnet sonarscanner begin \
/k:"$KEY" /n:"$KEY" \
/d:sonar.host.url="$HOST" /d:sonar.token="$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 en échec"
if ls ./CoverageResults/**/coverage.cobertura.xml &>/dev/null; then
reportgenerator -reports:./CoverageResults/**/coverage.cobertura.xml -targetdir:. -reporttypes:SonarQube \
|| echo "::warning::ReportGenerator en échec"
fi
dotnet sonarscanner end /d:sonar.token="$TOKEN"
- name: Check quality gate (non bloquant)
if: steps.infisical.outputs.sonar_skip != 'true'
shell: bash
run: |
export PATH="$PATH:$HOME/.dotnet/tools"
HOST="${SONARQUBE_URL:-${SONAR_HOST_URL:-}}"
TOKEN="${SONARQUBE_TOKEN:-${SONAR_TOKEN:-}}"
KEY="${SONARQUBE_HEIMDALL_PROJECT_KEY:-heimdall}"
[ -z "$HOST" ] || [ -z "$TOKEN" ] && exit 0
GATE_CTX="projectKey=$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 "$TOKEN:" "$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"
if [ "$STATUS" != "OK" ]; then
echo "::warning::SonarQube gate = $STATUS (non bloquant)"
fi
# ─────────────────────────────────────────────────────────────────────────
# DOCKER — uniquement sur push main (pas de PR)
# ─────────────────────────────────────────────────────────────────────────
docker:
name: Docker + Trivy
if: github.event_name == 'push' || github.event_name == 'schedule'
runs-on: debian-12
timeout-minutes: 50
steps:
- uses: https://forgejo.tordais.cc/actions/checkout@v4
with:
fetch-depth: 0
- name: Secrets Infisical
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 "::warning::VAULT_PROJECT_ID manquant — Docker skipped"
exit 0
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)
[ -z "$TOKEN" ] || [ "$TOKEN" = "null" ] && exit 0
export INFISICAL_TOKEN="$TOKEN"
export INFISICAL_DOMAIN="$DOMAIN"
DOTENV=$(infisical export --projectId="$PROJECT_ID" --env=dev --format=dotenv 2>/tmp/infisical.err || true)
[ -n "$DOTENV" ] && 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
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 }}"
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"
if [ -n "$DOCKER_USER" ] && [ -n "$DOCKER_PASS" ]; then
while IFS=' ' read -r img df; do
[ -z "$img" ] && continue
echo "$DOCKER_PASS" | docker login -u "$DOCKER_USER" --password-stdin || continue
docker push "${img}:latest" || true
docker push "${img}:${SHA}" || true
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 || true
fi
- name: Trivy scan
shell: bash
run: |
IMAGE="eltruncho/heimdall:${{ github.sha }}"
trivy image --severity HIGH,CRITICAL --format json --output /tmp/trivy.json "$IMAGE" \
|| { echo "::warning::Trivy scan failed"; 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)
if [ "$COUNT" -gt 0 ]; then
echo "::warning::$COUNT vulnérabilité(s) HIGH/CRITICAL"
python3 scripts/ci/trivy_report.py /tmp/trivy.json "HIGH,CRITICAL" 2>/dev/null || true
fi
# ─────────────────────────────────────────────────────────────────────────
# DOCKER PR BUILD — images de test par PR (pr-N + sha + dev-latest)
# ─────────────────────────────────────────────────────────────────────────
docker-pr:
name: Docker PR
if: github.event_name == 'pull_request'
runs-on: debian-12
timeout-minutes: 30
steps:
- uses: https://forgejo.tordais.cc/actions/checkout@v4
- name: Secrets Infisical
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 "::warning::VAULT_PROJECT_ID manquant — Docker PR skipped"
exit 0
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>/dev/null || true)
TOKEN=$(printf '%s' "$LOGIN_OUT" | tail -1)
[ -z "$TOKEN" ] || [ "$TOKEN" = "null" ] && exit 0
export INFISICAL_TOKEN="$TOKEN"
export INFISICAL_DOMAIN="$DOMAIN"
DOTENV=$(infisical export --projectId="$PROJECT_ID" --env=dev --format=dotenv 2>/tmp/infisical.err || true)
[ -n "$DOTENV" ] && python3 scripts/ci/inject_env.py "$DOTENV"
- name: Build Docker image (PR)
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
PR_NUMBER="${{ github.event.pull_request.number }}"
SHA="${{ github.sha }}"
while IFS=' ' read -r img df; do
[ -z "$img" ] && continue
echo "Building $img from $df"
docker build -f "$df" \
-t "${img}:pr-${PR_NUMBER}" \
-t "${img}:${SHA}" \
-t "${img}:dev-latest" .
done <<< "$DOCKER_IMAGES"
DOCKER_USER="${DOCKER_HEIMDALL_LOGIN:-}"
DOCKER_PASS="${DOCKER_HEIMDALL_PASSWORD:-}"
if [ -n "$DOCKER_USER" ] && [ -n "$DOCKER_PASS" ]; then
echo "$DOCKER_PASS" | docker login -u "$DOCKER_USER" --password-stdin
while IFS=' ' read -r img df; do
[ -z "$img" ] && continue
docker push "${img}:pr-${PR_NUMBER}" || true
docker push "${img}:${SHA}" || true
docker push "${img}:dev-latest" || true
done <<< "$DOCKER_IMAGES"
else
echo "::warning::DOCKER_HEIMDALL_LOGIN/PASSWORD absents — push ignoré"
fi
# ─────────────────────────────────────────────────────────────────────────
# OWASP DEPENDENCY-CHECK — uniquement si .csproj changent
# ─────────────────────────────────────────────────────────────────────────
dependency-check:
name: OWASP Dependency-Check
needs: [changes]
if: needs.changes.outputs.deps_changed == 'true'
runs-on: debian-12
timeout-minutes: 60
steps:
- uses: https://forgejo.tordais.cc/actions/checkout@v4
- name: Install Java + DC
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
- name: Scan
shell: bash
run: |
mkdir -p /tmp/dc-out
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 || SCAN_EXIT=$?
if [ "$SCAN_EXIT" -ne 0 ]; then
echo "::warning::Dependency-Check: vulnérabilités détectées"
fi
# ─────────────────────────────────────────────────────────────────────────
# RÉSUMÉ TESTS — toujours pour les PR
# ─────────────────────────────────────────────────────────────────────────
post-summary:
name: Résumé tests (PR)
if: always() && github.event_name == 'pull_request'
needs: [changes, 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 }}
WEB_SKIPPED: ${{ needs.changes.outputs.web_changed }}
DB_SKIPPED: ${{ needs.changes.outputs.db_changed }}
run: |
{
echo "## Tests unitaires"
echo ""
if [ -n "$S_UNIT" ]; then
echo "$S_UNIT"
else
echo "_Pas de résultats (job skippé)_"
fi
echo ""
echo "---"
echo ""
echo "## Tests Web (bUnit)"
echo ""
if [ "$WEB_SKIPPED" = "false" ]; then
echo "_Skippé (aucun changement IHM)_"
elif [ -n "$S_WEB" ]; then
echo "$S_WEB"
else
echo "_Pas de résultats_"
fi
echo ""
echo "---"
echo ""
echo "## Tests DB (Infrastructure)"
echo ""
if [ "$DB_SKIPPED" = "false" ]; then
echo "_Skippé (aucun changement DB/Domain)_"
elif [ -n "$S_DB" ]; then
echo "$S_DB"
else
echo "_Pas de résultats_"
fi
} > /tmp/full-summary.md
python3 scripts/ci/post_comment.py "$(cat /tmp/full-summary.md)" "Résumé des tests"
# ─────────────────────────────────────────────────────────────────────────
# CI — wrapper pour branch protection (status check unique)
# ─────────────────────────────────────────────────────────────────────────
ci:
name: ci
runs-on: debian-12
if: always()
needs: [build, test-unit, test-web, test-db, sonar, docker, dependency-check, post-summary]
steps:
- name: Vérifier les résultats
shell: bash
run: |
echo "Résultats des jobs :"
echo " build: ${{ needs.build.result }}"
echo " test-unit: ${{ needs.test-unit.result }}"
echo " test-web: ${{ needs.test-web.result }}"
echo " test-db: ${{ needs.test-db.result }}"
echo " sonar: ${{ needs.sonar.result }}"
echo " docker: ${{ needs.docker.result }}"
echo " dependency-check: ${{ needs.dependency-check.result }}"
echo " post-summary: ${{ needs.post-summary.result }}"
# Échouer si un job critique a échoué (pas test-db qui est continue-on-error)
if [[ "${{ needs.build.result }}" == "failure" ]] || \
[[ "${{ needs.test-unit.result }}" == "failure" ]] || \
[[ "${{ needs.test-web.result }}" == "failure" ]] || \
[[ "${{ needs.sonar.result }}" == "failure" ]] || \
[[ "${{ needs.docker.result }}" == "failure" ]] || \
[[ "${{ needs.dependency-check.result }}" == "failure" ]]; then
echo "❌ Un job critique a échoué"
exit 1
fi
echo "✅ Tous les jobs critiques sont OK"