diff --git a/.gitea/workflows/verifica.yml b/.gitea/workflows/verifica.yml index 363bc25..312bdd0 100644 --- a/.gitea/workflows/verifica.yml +++ b/.gitea/workflows/verifica.yml @@ -1,18 +1,149 @@ -# Verifica a ogni push e a ogni pull request: compilazione con gli avvisi come errori -# (compreso Febe.Desktop, che si compila anche da Linux) e tutte le prove. -# Le prove che richiedono Chromium e Xvfb si saltano da sole se il runner non li ha. +# Verifica: a ogni push su qualunque ramo (i tag li prende rilascio.yml) e a mano (Actions ▸ verifica ▸ Esegui). +# I suoi quattro lavori sono i controlli richiesti per unire in main (docs/processo.md): +# controlli sintassi degli script, flussi senza tabulazioni, segni di conflitto, versione, progetti della +# soluzione, JSON; segreti in tutta la storia con gitleaks (versione e impronta fissate); +# prove compilazione di tutta la soluzione con gli avvisi come errori e tutte le prove di tests/Febe.Tests +# (mai «dotnet test» sulla soluzione intera: tests/Febe.Tests.Windows gira solo su Windows) con +# Chromium, Xvfb, ffmpeg, NSIS e Node veri in un contenitore Debian 13: nessuna prova deve saltarsi. +# Il mondo sintetico del sito di prova ha il seme 13 e, per la categoria SitoDiProva, anche il seme di +# questa esecuzione, scritto nel registro per rifare un errore; +# installatore Febe-Setup--ci..exe e lo zip portabile, artefatti per 14 giorni; +# immagine l'immagine Docker costruita con buildx, provata senza rete (parte, salute, Chromium, it_IT) e +# scansionata con Trivy (si ferma per una CRITICAL con correzione); solo dopo un push su main la +# pubblica come :main e :sha-<7 caratteri> (:latest resta al rilascio). Alla fine, sempre, toglie +# immagini, contenitori, cache e builder di questa esecuzione. # -# Runner: act_runner con l'etichetta ubuntu-latest. +# Niente «pull_request»: in Gitea una richiesta di unione mostra lo stato del suo ultimo commit, che il push del ramo +# ha già verificato; pull_request rifarebbe tutto sullo stesso commit (refs/pull/N/head) sull'unico runner. +# Runner: act_runner con l'etichetta ubuntu-latest, un lavoro alla volta. I lavori parlano con il demone Docker del +# server, lo stesso di Encelado, Mimante e degli altri progetti: niente montaggi della cartella del lavoro in altri +# contenitori (sul server i percorsi sono diversi); le immagini passano come archivi e contesti di costruzione. +# Che cosa di Gitea 28 si usa e perché: docs/decisioni.md (20 ottobre 2026) e docs/processo.md. name: verifica on: push: - branches: [main, febe-v1] - pull_request: + branches: ["**"] + workflow_dispatch: + inputs: + seme: + description: "Seme del mondo sintetico per la seconda passata delle prove (vuoto: 1000 più il numero dell'esecuzione)" + required: false + default: "" + +permissions: + contents: read + +# Su un ramo conta l'ultimo push: l'esecuzione precedente si annulla. Su main ogni commit ha il suo gruppo, così ogni +# unione arriva fino in fondo e pubblica la sua :sha-. +concurrency: + group: verifica-${{ gitea.ref }}${{ gitea.ref == 'refs/heads/main' && format('-{0}', gitea.sha) || '' }} + cancel-in-progress: ${{ gitea.ref != 'refs/heads/main' }} + +defaults: + run: + shell: bash + +env: + DOTNET_NOLOGO: "1" + DOTNET_CLI_TELEMETRY_OPTOUT: "1" + DOTNET_SKIP_FIRST_TIME_EXPERIENCE: "1" jobs: - prove: + controlli: runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + # Tutta la storia, di tutti i rami e i tag: gitleaks la legge commit per commit. + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Script, flussi, conflitti, versione, soluzione e JSON + run: bash .gitea/scripts/controlli.sh + + - name: Segreti in tutta la storia (gitleaks) + run: bash .gitea/scripts/segreti.sh out/sicurezza + + - name: Rapporto di gitleaks (segreti oscurati) + if: failure() + uses: actions/upload-artifact@v3 + with: + name: rapporto-gitleaks + path: out/sicurezza/gitleaks.json + retention-days: 14 + if-no-files-found: ignore + + prove: + needs: controlli + runs-on: ubuntu-latest + timeout-minutes: 60 + # Debian 13 con Node 24: Chromium vero della distribuzione, come nell'immagine di Febe (su Ubuntu è uno snap), e + # Node per le azioni e per la prova della pagina di accesso. + container: + image: node:24-trixie + env: + FEBE_CHROMIUM: /usr/bin/chromium + SEME_RICHIESTO: ${{ gitea.event.inputs.seme }} + NUMERO: ${{ gitea.run_number }} + steps: + - uses: actions/checkout@v4 + + - name: Chromium, Xvfb, ffmpeg, NSIS e lingua italiana + run: bash .gitea/scripts/ambiente-prove.sh + + - uses: actions/setup-dotnet@v4 + with: + dotnet-version: "10.0.x" + + - name: Compilazione di tutta la soluzione (avvisi = errori) + run: dotnet build Febe.slnx -c Release -nologo -warnaserror + + - name: Semi del mondo sintetico + id: semi + run: | + seme="${SEME_RICHIESTO:-}" + [ -n "$seme" ] || seme=$((1000 + ${NUMERO:-0})) + if ! [[ "$seme" =~ ^-?[0-9]{1,9}$ ]]; then + echo "Seme non valido: «$seme» (serve un intero di al massimo nove cifre)." >&2 + exit 1 + fi + echo "seme=$seme" >> "$GITHUB_OUTPUT" + echo "Mondo sintetico: seme 13 per tutte le prove, seme $seme per la seconda passata (categoria SitoDiProva)." + echo "Per rifarla: FEBE_SEME_PROVA=$seme dotnet test tests/Febe.Tests --filter \"TestCategory=SitoDiProva\"" + + - name: Prove, seme 13 + run: >- + dotnet test tests/Febe.Tests -c Release --no-build --nologo + --logger "trx;LogFileName=prove-seme-13.trx" --results-directory out/prove + + - name: Prove del sito di prova, seme dell'esecuzione + if: ${{ !cancelled() && steps.semi.outputs.seme != '' }} + env: + FEBE_SEME_PROVA: ${{ steps.semi.outputs.seme }} + run: >- + dotnet test tests/Febe.Tests -c Release --no-build --nologo --filter "TestCategory=SitoDiProva" + --logger "trx;LogFileName=prove-seme-$FEBE_SEME_PROVA.trx" --results-directory out/prove + + - name: Riepilogo delle prove + if: ${{ !cancelled() }} + run: bash .gitea/scripts/riepilogo-prove.sh out/prove 0 + + - name: Risultati delle prove + if: ${{ !cancelled() }} + uses: actions/upload-artifact@v3 + with: + name: risultati-prove + path: out/prove/*.trx + retention-days: 14 + if-no-files-found: warn + + installatore: + needs: prove + runs-on: ubuntu-latest + timeout-minutes: 30 + env: + NUMERO: ${{ gitea.run_number }} steps: - uses: actions/checkout@v4 @@ -20,37 +151,151 @@ jobs: with: dotnet-version: "10.0.x" - - name: Compilazione (avvisi = errori) - run: dotnet build Febe.slnx -c Release -nologo -warnaserror + - name: NSIS e zip + run: | + SUDO=""; [ "$(id -u)" = 0 ] || SUDO=sudo + $SUDO apt-get update -qq + $SUDO apt-get install -y -qq nsis zip > /dev/null - - name: Prove - run: >- - dotnet test tests/Febe.Tests -c Release --no-build --nologo - --logger "trx;LogFileName=prove.trx" --results-directory out/prove + - name: Febe.exe, programma di installazione e zip portabile (versione di prova) + run: | + V=$(sed -n 's:.*\(.*\).*:\1:p' Directory.Build.props | head -n 1) + echo "Versione di questa esecuzione: $V-ci.$NUMERO" + bash installer/costruisci.sh "$V-ci.$NUMERO" - - name: Risultati - if: always() + - name: Artefatti per Windows uses: actions/upload-artifact@v3 with: - name: risultati-prove - path: out/prove/*.trx - if-no-files-found: ignore + name: windows + path: | + out/Febe-Setup-*.exe + out/Febe-*-portabile.zip + retention-days: 14 + if-no-files-found: error immagine: - runs-on: ubuntu-latest needs: prove + runs-on: ubuntu-latest + timeout-minutes: 60 + env: + FLUSSO: verifica + ESECUZIONE: ${{ gitea.run_id }} + NUMERO: ${{ gitea.run_number }} + BUILDER: febe-ci-${{ gitea.run_id }} + PROVA: febe-ci:${{ gitea.run_id }} steps: - uses: actions/checkout@v4 - - name: Costruzione dell'immagine Docker (senza pubblicarla; le prove girano anche dentro la build) + # Ciò che un'esecuzione interrotta (annullata, scaduta) non ha potuto togliere, e un tentativo precedente di + # questa stessa esecuzione. + - name: Resti di esecuzioni interrotte run: | - docker version - docker build -f docker/Dockerfile \ - --build-arg VERSION=ci \ - --build-arg GIT_COMMIT="${GITHUB_SHA::12}" \ - -t febe:ci . + bash .gitea/scripts/pulizia-docker.sh residui 90 + bash .gitea/scripts/pulizia-docker.sh esecuzione "$ESECUZIONE" - - name: L'immagine parte e mostra la pagina di errore senza password + # Registro: la variabile REGISTRY delle Actions, se c'è, altrimenti l'host dell'indirizzo del server (ROOT_URL). + - name: Versione, registro e nomi + id: nome + env: + REGISTRO_SCELTO: ${{ vars.REGISTRY }} + SERVER: ${{ gitea.server_url }} + PROPRIETARIO: ${{ gitea.repository_owner }} run: | - docker run --rm --entrypoint /usr/bin/chromium febe:ci --version - docker run --rm --entrypoint sh febe:ci -c 'locale -a | grep -i it_IT && ls /etc/chromium/policies/managed/' + V=$(sed -n 's:.*\(.*\).*:\1:p' Directory.Build.props | head -n 1) + REGISTRY="$REGISTRO_SCELTO" + [ -n "$REGISTRY" ] || REGISTRY=$(echo "$SERVER" | sed -E 's#^https?://##; s#/.*$##') + OWNER=$(echo "$PROPRIETARIO" | tr '[:upper:]' '[:lower:]') + { + echo "VERSIONE=$V-ci.$NUMERO" + echo "GIT_COMMIT=${GITHUB_SHA::12}" + echo "REGISTRY=$REGISTRY" + echo "IMAGE=$REGISTRY/$OWNER/febe" + echo "ARCHIVIO=${RUNNER_TEMP:-/tmp}/febe-$ESECUZIONE.tar" + } >> "$GITHUB_ENV" + echo "registro=$REGISTRY" >> "$GITHUB_OUTPUT" + echo "Immagine $V-ci.$NUMERO del commit ${GITHUB_SHA::12}, provata come $PROVA; registro $REGISTRY/$OWNER/febe" + + # Un builder buildx di questa esecuzione (con la sua cache), che sa che il registro di casa risponde in HTTP. + - name: Builder buildx dell'esecuzione + uses: docker/setup-buildx-action@v3 + with: + name: febe-ci-${{ gitea.run_id }} + driver: docker-container + buildkitd-config-inline: | + [registry."${{ steps.nome.outputs.registro }}"] + http = true + insecure = true + + - name: Costruzione dell'immagine (dentro girano compilazione e prove) + run: | + bash .gitea/scripts/costruisci-immagine.sh archivio "$ARCHIVIO" "$PROVA" + docker load -i "$ARCHIVIO" + + - name: Prova del contenitore, senza rete + run: bash .gitea/scripts/prova-immagine.sh "$PROVA" "$ESECUZIONE" + + - name: Vulnerabilità dell'immagine (Trivy) + run: bash .gitea/scripts/scansione-immagine.sh "$ARCHIVIO" out/sicurezza + + - name: Rapporto di Trivy + if: ${{ !cancelled() }} + uses: actions/upload-artifact@v3 + with: + name: sicurezza-immagine + path: out/sicurezza/trivy.json + retention-days: 14 + if-no-files-found: ignore + + - name: Pubblicare? + id: segreto + env: + TOKEN: ${{ secrets.REGISTRY_TOKEN }} + EVENTO: ${{ gitea.event_name }} + RIFERIMENTO: ${{ gitea.ref }} + run: | + if [ "$EVENTO" != push ] || [ "$RIFERIMENTO" != refs/heads/main ]; then + echo "Si pubblica solo dopo un push su main: qui l'immagine è costruita, provata e scansionata." + echo "presente=no" >> "$GITHUB_OUTPUT" + elif [ -z "$TOKEN" ]; then + echo "::warning::Manca il segreto REGISTRY_TOKEN: l'immagine di main è costruita, provata e scansionata ma non pubblicata. Aggiungilo (token con package: read and write) e rilancia la verifica di questo commit." + echo "presente=no" >> "$GITHUB_OUTPUT" + else + echo "presente=si" >> "$GITHUB_OUTPUT" + fi + + - name: Pubblicazione come :main e :sha- + if: steps.segreto.outputs.presente == 'si' + env: + TOKEN: ${{ secrets.REGISTRY_TOKEN }} + UTENTE: ${{ gitea.actor }} + run: | + # Le credenziali vanno nella configurazione del client: buildx le passa al builder, il demone non c'entra (e + # proverebbe HTTPS). Non si stampano mai. + CONFIG="${DOCKER_CONFIG:-$HOME/.docker}" + mkdir -p "$CONFIG" + [ -s "$CONFIG/config.json" ] || echo '{}' > "$CONFIG/config.json" + AUTH=$(printf '%s:%s' "$UTENTE" "$TOKEN" | base64 -w0) + jq --arg r "$REGISTRY" --arg a "$AUTH" '.auths[$r].auth = $a' "$CONFIG/config.json" > "$CONFIG/config.json.nuovo" + mv "$CONFIG/config.json.nuovo" "$CONFIG/config.json" + NOMI=("$IMAGE:sha-${GITHUB_SHA::7}") + # :main solo se main è ancora a questo commit: un'esecuzione arrivata in ritardo non lo riporta indietro. + CIMA=$(git ls-remote origin refs/heads/main 2> /dev/null | cut -f1) + if [ "$CIMA" = "$GITHUB_SHA" ]; then + NOMI+=("$IMAGE:main") + elif [ -z "$CIMA" ]; then + echo "::warning::Non riesco a leggere la cima di main: si pubblica solo :sha-${GITHUB_SHA::7} e :main resta dov'è." + else + echo "main è già andato avanti (${CIMA::7}): si pubblica solo :sha-${GITHUB_SHA::7}." + fi + bash .gitea/scripts/costruisci-immagine.sh pubblica "${NOMI[@]}" + + - name: Pulizia (sempre) + if: always() + run: | + CONFIG="${DOCKER_CONFIG:-$HOME/.docker}/config.json" + if [ -s "$CONFIG" ] && [ -n "${REGISTRY:-}" ]; then + jq --arg r "$REGISTRY" 'if .auths then .auths |= del(.[$r]) else . end' "$CONFIG" > "$CONFIG.nuovo" \ + && mv "$CONFIG.nuovo" "$CONFIG" || echo "::warning::Non riesco a togliere le credenziali da $CONFIG." + fi + if [ -n "${ARCHIVIO:-}" ]; then rm -f "$ARCHIVIO"; fi + bash .gitea/scripts/pulizia-docker.sh esecuzione "$ESECUZIONE" diff --git a/docs/decisioni.md b/docs/decisioni.md index ccbb776..faa77b7 100644 --- a/docs/decisioni.md +++ b/docs/decisioni.md @@ -234,3 +234,10 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15). | 2026-10-20 | Trivy sull'archivio dell'immagine provata (non dal demone): una vulnerabilità CRITICAL con correzione disponibile ferma il lavoro, le HIGH (e le CRITICAL senza correzione) si riportano nel registro e in `trivy.json` (artefatto di 14 giorni); eccezioni solo in `.trivyignore`, con motivo scritto e scadenza `exp:` | La regola chiesta da Alberto; scansionare l'archivio vuol dire scansionare proprio l'immagine provata, senza dipendere dal socket del demone | | 2026-10-20 | La prova del contenitore (`prova-immagine.sh`) gira sempre con `--network none`: Chromium, criteri, lingua, poi l'avvio come da guida (profilo seccomp, password casuale passata solo nell'ambiente del client) fino a «healthy», `febe --controllo-salute` e l'arresto entro 30 secondi | Regola 1: un'immagine appena costruita non deve poter raggiungere Instagram nemmeno per sbaglio; il controllo di salute passa dalla rete interna del contenitore | | 2026-10-20 | Ciò che la CI crea sul demone porta i suoi segni: etichette `febe.ci.workflow`, `febe.ci.run`, `febe.ci.ref`, `febe.ci.commit` sull'immagine e sui contenitori di prova, nome locale `febe-ci:`, builder `febe-ci-`. `pulizia-docker.sh` toglie solo quello (più le immagini senza nome oltre 72 ore): alla fine di ogni lavoro, all'inizio del lavoro successivo per i resti più vecchi di 90 minuti, e ogni settimana. Mai `system prune`, `builder prune`, `volume prune` | Il demone è lo stesso di Encelado, Mimante e degli altri progetti: la loro cache e le loro immagini non si toccano; un'esecuzione annullata non può pulire da sé, e un lavoro dura al massimo 60 minuti, quindi un resto di 90 minuti è certamente orfano | +| 2026-10-20 | `verifica` a ogni push su qualunque ramo (`branches: ["**"]`, quindi mai sui tag) e a mano (`workflow_dispatch`, con un seme facoltativo); niente `pull_request` | In Gitea i controlli di una richiesta di unione sono gli stati del suo ultimo commit, che il push del ramo ha già verificato; `pull_request` girerebbe sullo stesso commit (`refs/pull/N/head`, non un'unione di prova) e sull'unico runner raddoppierebbe tutto. Niente richieste da fork: un solo autore, rami nello stesso repository | +| 2026-10-20 | Concorrenza di `verifica`: su un ramo l'esecuzione nuova annulla quella in corso; su main ogni commit ha il suo gruppo e nessuna si annulla; `:main` si sposta solo se main è ancora a quel commit | Il runner fa un lavoro alla volta; ogni unione in main deve arrivare a pubblicare la sua `:sha-`, e un'esecuzione in ritardo non deve riportare indietro `:main`. Gitea 28 valuta le espressioni di `concurrency.group` e `cancel-in-progress` (`services/actions/concurrency.go`) | +| 2026-10-20 | Lavoro «prove» nel contenitore `node:24-trixie` (Debian 13 con Node 24), con Chromium, Xvfb, ffmpeg, NSIS e la lingua italiana installati a ogni esecuzione; il riepilogo non ammette prove saltate; seconda passata della categoria `SitoDiProva` con il seme 1000 + numero dell'esecuzione, o quello chiesto a mano | Su Ubuntu Chromium è uno snap; le azioni JavaScript girano dentro il contenitore del lavoro e vogliono Node; un'immagine di CI costruita da noi non può fare da contenitore del lavoro, perché act_runner la scaricherebbe da un registro e quello di casa è in HTTP; nella CI una prova saltata vuol dire un ambiente rotto, non una prova superata | +| 2026-10-20 | Installatore di ogni esecuzione con versione `-ci.` e immagine con etichetta `org.opencontainers.image.version` uguale; dopo ogni unione in main l'immagine va sul registro come `:main` e `:sha-<7 caratteri>`, mai `:latest`, che resta del rilascio | Decisione di Alberto del 20 ottobre; la versione di prova non si confonde con una versione rilasciata e `installer/costruisci.sh` la accetta già | +| 2026-10-20 | Artefatti con `actions/upload-artifact@v3` e `retention-days: 14` (risultati delle prove, installatore e zip, rapporti di sicurezza) | La v4 rifiuta di girare dove il server non è github.com (prende Gitea per GHES) e la sua copia per Gitea sarebbe un'azione nuova, non approvata; il backend v3 di Gitea 28 rispetta `retentionDays` (`routers/api/actions/artifacts.go`) | +| 2026-10-20 | `permissions: contents: read` in `verifica` e `pulizia`; i riepiloghi delle prove e di Trivy vanno nel registro e anche in `GITHUB_STEP_SUMMARY` | Gitea 28 applica `permissions` al gettone del lavoro (docs.gitea.com, «Actions job token permissions»), che così non può scrivere nel repository; i riepiloghi dei lavori esistono da Gitea 1.27 ma compaiono solo se il runner li carica, quindi il registro resta la fonte | +| 2026-10-20 | Ciò che la CI usa di Gitea 28 e di act_runner: `concurrency` con espressioni, `timeout-minutes` dei lavori (lo applica il runner), `workflow_dispatch` con `inputs`, `schedule`, `defaults.run.shell`, `container` del lavoro, contesti `gitea.*`, `vars` e `secrets`; gli stati dei commit si chiamano «verifica / (push)» (`modules/actions/workflows.go`) e solo push, pull_request e release ne creano | Controllato sul codice di Gitea `release/v28` e su docs.gitea.com il 20 ottobre 2026; ciò che solo la prima esecuzione vera può provare è in `docs/processo.md` | diff --git a/tests/Febe.Tests/Packaging/PipelineTests.cs b/tests/Febe.Tests/Packaging/PipelineTests.cs new file mode 100644 index 0000000..06e228e --- /dev/null +++ b/tests/Febe.Tests/Packaging/PipelineTests.cs @@ -0,0 +1,258 @@ +using System.Text.RegularExpressions; +using Febe.Tests.Desktop.Support; +using Febe.Tests.Support; + +namespace Febe.Tests.Packaging; + +/// +/// The CI of the repository (.gitea/workflows/verifica.yml, pulizia.yml and the scripts of .gitea/scripts), read as +/// text: the rules that must survive later edits. Every push of every branch is verified and nothing else triggers +/// it twice; the tests run only through tests/Febe.Tests, with the browser, and again with the seed of the run; the +/// image is published only from main and never as :latest; credentials are never printed; the external tools are +/// pinned and checked; the cleanup touches only what the CI of Febe made; the tried container never has a network. +/// +[TestClass] +public sealed partial class PipelineTests +{ + private static readonly string[] Jobs = ["controlli", "prove", "installatore", "immagine"]; + + [TestMethod] + public void EveryPushOfEveryBranchIsVerifiedOnceAndTagsAreLeftToTheRelease() + { + var workflow = Workflow("verifica.yml"); + StringAssert.Contains(workflow, "on:\n push:\n branches: [\"**\"]\n workflow_dispatch:"); + var code = Code(workflow); + Assert.DoesNotContain("pull_request", code, "a PR shows the status of its head commit, already verified by the push"); + Assert.DoesNotContain("tags:", code, "tags belong to rilascio.yml"); + StringAssert.Contains(code, "cancel-in-progress: ${{ gitea.ref != 'refs/heads/main' }}", "every merge into main runs to the end"); + } + + [TestMethod] + public void TheJobsFollowOneAnotherAndEachHasATimeout() + { + var workflow = Workflow("verifica.yml"); + foreach (var job in Jobs) + { + StringAssert.Contains(Job(workflow, job), "timeout-minutes:", job); + } + + StringAssert.Contains(Job(workflow, "prove"), "needs: controlli"); + StringAssert.Contains(Job(workflow, "installatore"), "needs: prove"); + StringAssert.Contains(Job(workflow, "immagine"), "needs: prove"); + foreach (var other in new[] { "rilascio.yml", "pulizia.yml" }) + { + var text = Workflow(other); + foreach (Match job in JobHeader().Matches(text)) + { + StringAssert.Contains(Job(text, job.Groups["name"].Value), "timeout-minutes:", $"{other}: {job.Groups["name"].Value}"); + } + } + } + + [TestMethod] + public void TheWholeSolutionIsBuiltAndTheTestsRunOnlyThroughTheTestProjectWithTheBrowser() + { + var prove = Job(Workflow("verifica.yml"), "prove"); + StringAssert.Contains(prove, "container:\n image: node:24-trixie", "Debian: Chromium is a real package there, a snap on Ubuntu"); + StringAssert.Contains(prove, "bash .gitea/scripts/ambiente-prove.sh"); + StringAssert.Contains(prove, "dotnet build Febe.slnx -c Release -nologo -warnaserror"); + StringAssert.Contains(prove, "bash .gitea/scripts/riepilogo-prove.sh out/prove 0", "no test may skip itself in the CI"); + + // The second pass: the tests of the synthetic world again, with the seed of the run in the variable the helper reads. + StringAssert.Contains(prove, $"{SyntheticSite.Variable}: ${{{{ steps.semi.outputs.seme }}}}"); + StringAssert.Contains(prove, $"--filter \"TestCategory={SyntheticSite.Category}\""); + + var environment = Script("ambiente-prove.sh"); + foreach (var package in new[] { "chromium", "xvfb", "ffmpeg", "nsis", "locales" }) + { + StringAssert.Contains(environment, package); + } + + // tests/Febe.Tests.Windows runs only on Windows: never «dotnet test» on the solution or without a project. + foreach (var name in new[] { "verifica.yml", "rilascio.yml" }) + { + foreach (Match test in DotnetTest().Matches(Code(Workflow(name)))) + { + Assert.AreEqual("tests/Febe.Tests", test.Groups["target"].Value, $"{name}: {test.Value}"); + } + } + } + + [TestMethod] + public void TheImageIsPublishedOnlyAfterAPushToMainAsMainAndShaNeverAsLatest() + { + var image = Job(Workflow("verifica.yml"), "immagine"); + var decision = Step(image, "Pubblicare?"); + StringAssert.Contains(decision, "[ \"$EVENTO\" != push ] || [ \"$RIFERIMENTO\" != refs/heads/main ]"); + StringAssert.Contains(decision, "::warning::Manca il segreto REGISTRY_TOKEN"); + Assert.DoesNotContain("exit 1", decision, "without the secret the job stays green"); + var publish = Step(image, "Pubblicazione come :main e :sha-"); + StringAssert.Contains(publish, "if: steps.segreto.outputs.presente == 'si'"); + StringAssert.Contains(publish, "\"$IMAGE:sha-${GITHUB_SHA::7}\""); + StringAssert.Contains(publish, "\"$IMAGE:main\""); + StringAssert.Contains(publish, "bash .gitea/scripts/costruisci-immagine.sh pubblica"); + Assert.DoesNotContain(":latest", Code(Workflow("verifica.yml")), ":latest belongs to the release"); + + // Built with buildx, tried without a network and scanned before anything is published; always cleaned up. + StringAssert.Contains(image, "uses: docker/setup-buildx-action@v3"); + StringAssert.Contains(image, "http = true"); + StringAssert.Contains(image, "insecure = true"); + var decide = image.IndexOf("- name: Pubblicare?", StringComparison.Ordinal); + foreach (var gate in new[] { "bash .gitea/scripts/costruisci-immagine.sh archivio", "bash .gitea/scripts/prova-immagine.sh", "bash .gitea/scripts/scansione-immagine.sh" }) + { + var at = image.IndexOf(gate, StringComparison.Ordinal); + Assert.IsTrue(at >= 0 && at < decide, $"«{gate}» comes before the publication"); + } + var cleanup = Step(image, "Pulizia (sempre)"); + StringAssert.Contains(cleanup, "if: always()"); + StringAssert.Contains(cleanup, "bash .gitea/scripts/pulizia-docker.sh esecuzione \"$ESECUZIONE\""); + StringAssert.Contains(cleanup, ".auths |= del(.[$r])", "the credentials leave the client configuration"); + } + + [TestMethod] + public void SecretsAreNeverPrintedNorTheDaemonUsedForTheRegistry() + { + foreach (var (name, text) in AllCiFiles()) + { + var code = Code(text); + Assert.DoesNotContain("docker login", code, name); + Assert.DoesNotContain("docker push", code, name); + Assert.IsFalse(Trace().IsMatch(code), $"{name}: no shell tracing (it would print secrets)"); + + // A secret goes into echo or printf only to be piped or redirected, never to the log. + foreach (var line in code.Split('\n').Where(l => Printing().IsMatch(l))) + { + var secret = SecretReference().Match(line); + if (secret.Success) + { + var after = line[secret.Index..]; + Assert.IsTrue(after.Contains('|', StringComparison.Ordinal) || after.Contains('>', StringComparison.Ordinal), $"{name}: «{line.Trim()}» would print a secret"); + } + } + } + } + + [TestMethod] + public void TheExternalToolsArePinnedAndCheckedAndNoThirdPartyActionRunsThem() + { + var tool = Script("strumento.sh"); + StringAssert.Contains(tool, "versione=\"8.30.1\""); + StringAssert.Contains(tool, "versione=\"0.75.0\""); + Assert.HasCount(2, Sha256().Matches(tool), "one SHA-256 per tool"); + StringAssert.Contains(tool, "sha256sum -c"); + Assert.DoesNotContain("latest", Code(tool)); + foreach (var (name, text) in AllCiFiles()) + { + Assert.DoesNotContain("trivy-action", Code(text), name); + Assert.DoesNotContain("gitleaks-action", Code(text), name); + } + + var secrets = Script("segreti.sh"); + StringAssert.Contains(secrets, "--redact"); + StringAssert.Contains(Job(Workflow("verifica.yml"), "controlli"), "fetch-depth: 0"); + var scan = Script("scansione-immagine.sh"); + StringAssert.Contains(scan, "--severity CRITICAL --ignore-unfixed"); + StringAssert.Contains(scan, "--exit-code 1"); + } + + [TestMethod] + public void TheCleanupTouchesOnlyWhatTheCiOfFebeMade() + { + var cleanup = Code(Script("pulizia-docker.sh")); + foreach (var forbidden in new[] { "system prune", "builder prune", "volume prune", "container prune", "image prune -a", "prune --all", "image prune -f -a" }) + { + Assert.DoesNotContain(forbidden, cleanup, "the daemon is shared with Alberto's other projects"); + } + + Assert.HasCount(1, ImagePrune().Matches(cleanup), "only dangling images, older than three days"); + StringAssert.Contains(cleanup, "docker image prune -f --filter \"until=72h\""); + StringAssert.Contains(cleanup, "--filter \"label=febe.ci.run=$run\""); + StringAssert.Contains(cleanup, "^buildx_buildkit_(febe-ci-[0-9]+)0$"); + + var weekly = Workflow("pulizia.yml"); + StringAssert.Contains(weekly, "schedule:"); + StringAssert.Contains(weekly, "workflow_dispatch:"); + StringAssert.Contains(weekly, "bash .gitea/scripts/pulizia-docker.sh settimanale"); + } + + [TestMethod] + public void TheTriedContainerNeverHasANetwork() + { + var smoke = Code(Script("prova-immagine.sh")); + var runs = DockerRun().Matches(smoke); + Assert.IsGreaterThanOrEqualTo(4, runs.Count); + foreach (Match run in runs) + { + StringAssert.Contains(run.Value, "--network none", "rule 1: the image under test cannot reach any site"); + } + } + + /// The workflows and the scripts of the CI, by name. + private static List<(string Name, string Text)> AllCiFiles() => + [.. Directory.EnumerateFiles(CiPath("workflows")).Concat(Directory.EnumerateFiles(CiPath("scripts"))) + .Select(file => (Path.GetFileName(file), Read(file)))]; + + private static string Workflow(string name) => Read(CiPath("workflows", name)); + + private static string Script(string name) => Read(CiPath("scripts", name)); + + private static string Read(string path) => File.ReadAllText(path).Replace("\r\n", "\n", StringComparison.Ordinal); + + /// A path under .gitea; inconclusive in the build of the image, whose context leaves .gitea out. + private static string CiPath(params string[] parts) + { + var path = Repository.PathOf([".gitea", .. parts]); + var root = Repository.Root()!; + if (!File.Exists(path) && !Directory.Exists(path) && !Directory.Exists(Path.Combine(root, ".git")) && !File.Exists(Path.Combine(root, ".git"))) + { + Assert.Inconclusive("Questa copia del repository non ha .gitea/ (costruzione dell'immagine Docker)."); + } + + return path; + } + + /// The text without comment lines (YAML and shell): what runs, not what the comments say. + private static string Code(string text) => + string.Join('\n', text.Replace("\r\n", "\n", StringComparison.Ordinal).Split('\n').Where(line => !line.TrimStart().StartsWith('#'))); + + /// The block of a job: from « name:» to the next job. + private static string Job(string workflow, string name) + { + var match = Regex.Match(workflow, $@"^ {Regex.Escape(name)}:\n(?(?:(?: .*|\s*)\n)*)", RegexOptions.Multiline); + Assert.IsTrue(match.Success, $"manca il lavoro {name}"); + return match.Groups["body"].Value; + } + + /// The block of a step, from its «- name:» to the next step. + private static string Step(string job, string name) + { + var start = job.IndexOf("- name: " + name, StringComparison.Ordinal); + Assert.IsGreaterThanOrEqualTo(0, start, $"manca il passo «{name}»"); + var next = job.IndexOf("\n - ", start + 1, StringComparison.Ordinal); + return next < 0 ? job[start..] : job[start..next]; + } + + [GeneratedRegex(@"(?<=^jobs:\n(?:.*\n)*?)^ (?[a-z][\w-]*):$", RegexOptions.Multiline)] + private static partial Regex JobHeader(); + + [GeneratedRegex(@"dotnet test(?:\s+(?[^\s-][^\s]*))?")] + private static partial Regex DotnetTest(); + + [GeneratedRegex(@"(?m)^\s*set\s+-[a-wyz]*x|\bbash\s+-x\b")] + private static partial Regex Trace(); + + [GeneratedRegex(@"\b(?:echo|printf)\b")] + private static partial Regex Printing(); + + [GeneratedRegex(@"\$\{?(?:TOKEN|FEBE_PASSWORD|AUTH|REGISTRY_TOKEN|PASSWORD)\b")] + private static partial Regex SecretReference(); + + [GeneratedRegex(@"\b[0-9a-f]{64}\b")] + private static partial Regex Sha256(); + + [GeneratedRegex(@"docker (?:image|container|volume|builder|system) prune")] + private static partial Regex ImagePrune(); + + [GeneratedRegex(@"docker run\b(?:[^\n]*\\\n)*[^\n]*")] + private static partial Regex DockerRun(); +}