CI senza azioni e senza Node, solo comandi scritti in casa (C6, 3/4)

Per la decisione di Alberto del 18 novembre 2026 (niente componenti esterni) i flussi
di verifica, rilascio e pulizia non usano più azioni JavaScript, che vogliono Node:

- sorgenti con git init/fetch e il gettone del lavoro, passato a git solo
  nell'ambiente del passo, mai scritto nella configurazione;
- SDK .NET con .gitea/scripts/dotnet.sh, dai metadati di Microsoft e verificato
  con lo SHA-512 prima di installarlo nella cache degli strumenti del runner;
- builder buildx creato da costruisci-immagine.sh builder;
- artefatti nel pacchetto generico febe-ci del registro di Gitea (artefatti.sh,
  con REGISTRY_TOKEN), tolti dalla pulizia del lunedì dopo 14 giorni; la release
  ricostruisce installatore e zip invece di riceverli da un altro lavoro;
- JSON letto con un lettore in awk POSIX (json.awk) per i controlli e per la
  scelta delle versioni del registro, al posto di versioni-registro.js;
- contenitore delle prove debian:trixie al posto di node:24-trixie;
- la prova della pagina di accesso gira in Chromium invece che in Node.

controlli.sh rifiuta ora un flusso con uses:, tabulazioni o rientri dispari, e le
prove nuove controllano l'assenza di Node, il passo dei sorgenti uguale in ogni
lavoro, l'SDK prima di ogni dotnet, la scelta dell'SDK, il caricamento degli
artefatti con un curl finto e la scadenza dei vecchi. Nessuna esecuzione vera di
Gitea Actions: ciò che resta da vedere è in docs/processo.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-18 14:41:49 +01:00
1 parent 7a54f1a460
commit a4ad8a8bc4
27 files changed
+1763 -396

No files matched your search

+2
View File
@@ -1,4 +1,6 @@
# Gli script di shell restano con le righe Unix anche su un Windows con core.autocrlf: bash non regge il CR.
*.sh text eol=lf
# Anche i programmi awk della CI (json.awk e quelli che lo usano), che girano con bash.
*.awk text eol=lf
# Binari: mai conversioni.
*.ico binary
+12 -8
View File
@@ -1,9 +1,10 @@
#!/usr/bin/env bash
# Prepara il contenitore Debian del lavoro «prove» (node:24-trixie: Debian 13 con Node, che serve alle azioni) perché
# nessuna prova si salti: Chromium vero della distribuzione (su Ubuntu è uno snap, che nei contenitori non va) con le
# sue lingue, Xvfb, ffmpeg e ffprobe, la lingua it_IT.UTF-8, fusi orari, ICU e gli stessi
# caratteri dell'immagine di Febe. Node c'è già (prova della pagina di accesso); setpriv, getent e l'utente nobody
# (65534) vengono con Debian (prove dell'avvio del contenitore).
# Prepara il contenitore Debian del lavoro «prove» (debian:trixie, Debian 13 senza nient'altro: nessuna azione
# JavaScript, quindi niente Node) perché nessuna prova si salti: Chromium vero della distribuzione (su Ubuntu è uno
# snap, che nei contenitori non va) con le sue lingue, Xvfb, ffmpeg e ffprobe, la lingua it_IT.UTF-8, fusi orari e gli
# stessi caratteri dell'immagine di Febe; ICU, OpenSSL, zlib e libstdc++ per l'SDK .NET (dotnet.sh). git, curl e i
# certificati li installa il passo prima dei sorgenti. setpriv, getent e l'utente nobody (65534) vengono con Debian
# (prove dell'avvio del contenitore).
#
# .gitea/scripts/ambiente-prove.sh
set -euo pipefail
@@ -17,7 +18,7 @@ $sudo apt-get install -y -qq --no-install-recommends \
chromium chromium-l10n \
xvfb \
ffmpeg \
locales tzdata libicu76 ca-certificates \
locales tzdata libicu76 libssl3t64 zlib1g libstdc++6 ca-certificates curl git \
fonts-noto-color-emoji fonts-liberation fonts-dejavu-core \
util-linux procps > /dev/null
$sudo sed -i 's/^# *\(it_IT.UTF-8 UTF-8\)/\1/' /etc/locale.gen
@@ -28,7 +29,10 @@ chromium --version
command -v Xvfb
ffmpeg -version | head -n 1 || true
ffprobe -version | head -n 1 || true
echo "node $(node --version)"
locale -a | grep -i '^it_IT\.utf8$'
for strumento in setpriv getent stat chown sh; do command -v "$strumento" > /dev/null || { echo "Manca $strumento." >&2; exit 1; }; done
for strumento in setpriv getent stat chown sh awk sort; do command -v "$strumento" > /dev/null || { echo "Manca $strumento." >&2; exit 1; }; done
if command -v node > /dev/null; then
echo "C'è node in questo contenitore: la CI non deve usarlo (nessuna azione JavaScript, nessuno script Node)." >&2
exit 1
fi
getent passwd 65534 > /dev/null && getent group 65534 > /dev/null || { echo "Mancano l'utente o il gruppo 65534 (nobody)." >&2; exit 1; }
+67
View File
@@ -0,0 +1,67 @@
#!/usr/bin/env bash
# Artefatti della CI, al posto di actions/upload-artifact (un'azione JavaScript, che vuole Node): i file vanno nel
# registro dei pacchetti di Gitea, pacchetto generico febe-ci, una versione per esecuzione:
#
# <versione>-ci.<numero> dal flusso verifica (come Febe-Setup-<versione>-ci.<numero>.exe)
# <versione>-rilascio.<numero> dal flusso rilascio
#
# con <versione> da Directory.Build.props e <numero> il numero dell'esecuzione (NUMERO). Si scaricano dalla pagina del
# pacchetto su Gitea (proprietario ▸ Pacchetti ▸ febe-ci). La pulizia del lunedì (pulizia-docker.sh completa) toglie le
# versioni create più di 14 giorni prima, come faceva la scadenza degli artefatti.
#
# .gitea/scripts/artefatti.sh verifica|rilascio <file>...
#
# Variabili: REGISTRY_TOKEN (token con «package: read and write», solo nell'intestazione di curl, mai stampato), GITEA_URL
# (l'indirizzo del server, gitea.server_url), PROPRIETARIO, NUMERO. Senza REGISTRY_TOKEN un avviso e nessun file
# caricato: il lavoro resta verde, come per l'immagine. Un file che manca o un rifiuto del registro fanno fallire il
# passo. Un file con lo stesso nome già caricato (un nuovo tentativo della stessa esecuzione) si sostituisce.
set -euo pipefail
flusso="${1:-}"
case "$flusso" in
verifica) suffisso=ci ;;
rilascio) suffisso=rilascio ;;
*) echo "Uso: artefatti.sh verifica|rilascio <file>..." >&2; exit 2 ;;
esac
shift
(($# > 0)) || { echo "Indica almeno un file da caricare." >&2; exit 2; }
cd "$(git rev-parse --show-toplevel)"
numero="${NUMERO:-}"
[[ "$numero" =~ ^[0-9]+$ ]] || { echo "Manca NUMERO, il numero dell'esecuzione, o non è un numero: «$numero»." >&2; exit 2; }
v=$(sed -n 's:.*<Version>\(.*\)</Version>.*:\1:p' Directory.Build.props | head -n 1)
versione="$v-$suffisso.$numero"
[[ "$versione" =~ ^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?-(ci|rilascio)\.[0-9]+$ ]] || { echo "Versione degli artefatti non valida: «$versione»." >&2; exit 2; }
for file in "$@"; do
[[ -f "$file" ]] || { echo "Manca l'artefatto $file." >&2; exit 1; }
[[ "$(basename "$file")" =~ ^[0-9A-Za-z._-]+$ ]] || { echo "Nome di file non adatto a un pacchetto: «$(basename "$file")»." >&2; exit 2; }
done
if [[ -z "${REGISTRY_TOKEN:-}" ]]; then
echo "::warning::Manca il segreto REGISTRY_TOKEN: gli artefatti ($*) non vanno sul registro dei pacchetti. Aggiungilo (token con package: read and write) per averli per 14 giorni."
exit 0
fi
proprietario="${PROPRIETARIO:?Manca PROPRIETARIO.}"
base="${GITEA_URL:?Manca GITEA_URL.}"
base="${base%/}/api/packages/$proprietario/generic/febe-ci/$versione"
# Una chiamata al registro: il codice HTTP, 000 se Gitea non risponde. Il token sta solo nell'intestazione di curl.
chiedi() {
local codice
codice=$(curl -sS --max-time 900 -H "Authorization: token $REGISTRY_TOKEN" -o /dev/null -w '%{http_code}' "$@") || true
echo "${codice:-000}"
}
for file in "$@"; do
nome="$(basename "$file")"
codice=$(chiedi -X PUT --upload-file "$file" "$base/$nome")
if [[ "$codice" == 409 ]]; then
codice=$(chiedi -X DELETE "$base/$nome")
[[ "$codice" == 204 ]] || { echo "Il registro non toglie la copia precedente di $nome: risponde $codice." >&2; exit 1; }
codice=$(chiedi -X PUT --upload-file "$file" "$base/$nome")
fi
[[ "$codice" == 201 ]] || { echo "Il registro non accetta $nome: risponde $codice." >&2; exit 1; }
echo "$nome caricato ($(du -h "$file" | cut -f1))"
done
echo "Artefatti: ${GITEA_URL%/}/$proprietario/-/packages/generic/febe-ci/$versione"
+47 -29
View File
@@ -4,18 +4,21 @@
#
# bash .gitea/scripts/controlli.sh
#
# 1. ogni script di shell del repository è sintassi valida (bash -n; sh -n per quelli in sh) e ha le righe Unix; gli
# script Node della CI (.gitea/scripts/*.js) sono JavaScript valido (node --check);
# 2. i flussi della CI non hanno tabulazioni (YAML non le accetta come rientro);
# 1. ogni script di shell del repository è sintassi valida (bash -n; sh -n per quelli in sh) e ha le righe Unix, come
# i programmi awk della CI;
# 2. i flussi della CI si leggono come YAML a blocchi: niente tabulazioni né righe Windows, rientri di due spazi fuori
# dai blocchi di testo, «on:» e «jobs:» presenti; e sono fatti solo di comandi: nessun «uses:», cioè nessuna
# azione (le azioni JavaScript vogliono Node, e la CI di Febe è scritta in casa: decisione del 18 novembre 2026);
# 3. nessun file contiene segni di conflitto rimasti da un'unione;
# 4. la versione di Directory.Build.props è nella forma x.y.z[-qualcosa], quella che installer/costruisci.sh accetta;
# 5. ogni progetto elencato in Febe.slnx esiste;
# 6. ogni file JSON del repository si legge (configurazioni, campioni ripuliti, criteri di Chromium).
# 6. ogni file JSON del repository si legge (configurazioni, campioni ripuliti, criteri di Chromium), con json.awk.
set -uo pipefail
radice="$(git rev-parse --show-toplevel)" || exit 2
cd "$radice" || exit 2
errori=0
export LC_ALL=C
errore() {
echo "ERRORE: $*" >&2
@@ -35,25 +38,48 @@ while IFS= read -r -d '' script; do
fi
done < <(git ls-files -z -- '*.sh')
echo " $quanti script controllati"
echo "== Script Node della CI"
if command -v node > /dev/null; then
quanti=0
while IFS= read -r -d '' script; do
quanti=$((quanti + 1))
node --check "$script" || errore "$script: JavaScript non valido."
done < <(git ls-files -z -- '.gitea/scripts/*.js')
echo " $quanti script controllati"
else
errore "manca node: gli script Node della CI non si possono controllare."
fi
while IFS= read -r -d '' programma; do
if grep -q $'\r' "$programma"; then
errore "$programma ha righe Windows (CR) (.gitattributes chiede eol=lf)."
fi
done < <(git ls-files -z -- '*.awk')
echo "== Flussi della CI"
quanti=0
while IFS= read -r -d '' flusso; do
quanti=$((quanti + 1))
if grep -n $'\t' "$flusso" > /dev/null; then
errore "$flusso contiene tabulazioni: in YAML il rientro si fa con gli spazi."
fi
# Un blocco di testo («run: |», «>-») tiene tutte le righe più rientrate della sua chiave; fuori, i rientri sono di
# due spazi in due e nessuna riga chiama un'azione.
if rilievi=$(awk '
FNR == 1 { blocco = -1; on = 0; jobs = 0 }
{
riga = $0
if (riga ~ /\r$/) { print FNR ": riga Windows (CR)"; next }
match(riga, /^ */)
rientro = RLENGTH
vuota = riga ~ /^ *$/
if (blocco >= 0) {
if (vuota || rientro > blocco) next
blocco = -1
}
if (vuota || riga ~ /^ *#/) next
if (rientro % 2 == 1) print FNR ": rientro dispari"
if (riga ~ /^ *(- +)?uses *:/) print FNR ": «uses:» (nessuna azione: solo comandi)"
if (riga ~ /^on:/) on = 1
if (riga ~ /^jobs:/) jobs = 1
if (riga ~ /: *[|>][-+]?[0-9]? *(#.*)?$/) blocco = rientro
}
END {
if (!on) print "manca «on:»"
if (!jobs) print "manca «jobs:»"
}' "$flusso") && [[ -n "$rilievi" ]]; then
errore "$flusso:"$'\n'"$(sed 's/^/ riga /; s/^ riga manca/ manca/' <<< "$rilievi")"
fi
done < <(git ls-files -z -- '.gitea/workflows/*.yml' '.gitea/workflows/*.yaml')
echo " $quanti flussi controllati"
echo "== Segni di conflitto"
if conflitti=$(git grep -n -I -E '^(<{7}|>{7})( |$)' -- . ':!*.png' ':!*.jpg'); then
@@ -78,21 +104,13 @@ done < <(sed -n 's:.*<Project Path="\([^"]*\)".*:\1:p' Febe.slnx)
echo " $(grep -c '<Project Path=' Febe.slnx) progetti"
echo "== File JSON"
if command -v node > /dev/null; then
# Un solo processo per tutti i file; stampa i file che non si leggono, uno per riga.
guasti=$(git ls-files -z -- '*.json' | node -e '
const fs = require("fs");
const files = fs.readFileSync(0, "utf8").split("\0").filter(Boolean);
for (const f of files) {
try { JSON.parse(fs.readFileSync(f, "utf8").replace(/^/, "")); } catch (e) { console.log(f + ": " + e.message); }
}
console.error(" " + files.length + " file controllati");')
if [[ -n "$guasti" ]]; then
# Un solo processo per tutti i file; stampa i file che non si leggono, uno per riga, con il motivo e la riga.
mapfile -d '' json < <(git ls-files -z -- '*.json')
if ((${#json[@]} > 0)); then
if ! guasti=$(awk -f .gitea/scripts/json.awk -f .gitea/scripts/json-valido.awk "${json[@]}"); then
errore "JSON non valido:"
echo "$guasti" >&2
echo "${guasti:-(nessun dettaglio)}" >&2
fi
else
errore "manca node: i file JSON non si possono controllare."
fi
if ((errori > 0)); then
+23 -2
View File
@@ -3,6 +3,11 @@
# stessi argomenti e le stesse etichette: la costruzione che si pubblica esce intera dalla cache di quella che si è
# provata e scansionata, quindi gli strati sono gli stessi.
#
# costruisci-immagine.sh builder <registro> il builder buildx dell'esecuzione (BUILDER), con il
# driver docker-container e la configurazione di
# buildkit che dice che il registro di casa risponde in
# HTTP (al posto di docker/setup-buildx-action, un'azione
# JavaScript); lo toglie pulizia-docker.sh esecuzione
# costruisci-immagine.sh archivio <file.tar> <nome locale> archivio dell'immagine, per docker load e per Trivy
# costruisci-immagine.sh pubblica <nome:etichetta>... spinta sul registro da buildx: le credenziali sono
# già nella configurazione del client, il demone non
@@ -20,10 +25,26 @@
# lo controlla PipelineTests.
set -euo pipefail
modo="${1:?Indica il modo: archivio o pubblica.}"
modo="${1:?Indica il modo: builder, archivio o pubblica.}"
shift
cd "$(git rev-parse --show-toplevel)"
if [[ "$modo" == builder ]]; then
registro="${1:?Indica il registro, per esempio 192.168.30.23:3000.}"
# Solo un nome di host (o un indirizzo) con la porta: il valore finisce in un file TOML.
[[ "$registro" =~ ^[A-Za-z0-9.-]+(:[0-9]+)?$ ]] || { echo "Registro non valido: «$registro»." >&2; exit 2; }
configurazione="${RUNNER_TEMP:-/tmp}/buildkitd-${BUILDER:?}.toml"
printf '[registry."%s"]\n http = true\n insecure = true\n' "$registro" > "$configurazione"
# --buildkitd-config da buildx 0.13; prima si chiamava --config.
opzione=--buildkitd-config
aiuto=$(docker buildx create --help 2> /dev/null) || true
[[ "$aiuto" == *--buildkitd-config* ]] || opzione=--config
docker buildx create --name "$BUILDER" --driver docker-container "$opzione" "$configurazione" --bootstrap
rm -f "$configurazione"
docker buildx inspect "$BUILDER"
exit 0
fi
comuni=(--builder "${BUILDER:?}" -f docker/Dockerfile --provenance=false --sbom=false
--build-arg "VERSION=${VERSIONE:?}" --build-arg "GIT_COMMIT=${GIT_COMMIT:?}"
--label "febe.ci.workflow=${FLUSSO:?}" --label "febe.ci.run=${ESECUZIONE:?}"
@@ -47,7 +68,7 @@ case "$modo" in
printf 'Pubblicata: %s\n' "$@"
;;
*)
echo "Modo sconosciuto: «$modo» (archivio o pubblica)." >&2
echo "Modo sconosciuto: «$modo» (builder, archivio o pubblica)." >&2
exit 2
;;
esac
+56
View File
@@ -0,0 +1,56 @@
# For dotnet.sh, with json.awk: in the release metadata of a .NET channel (releases.json of
# builds.dotnet.microsoft.com/dotnet/release-metadata/<channel>/), the newest SDK («latest-sdk») and the address and
# SHA-512 of its archive for the rid asked:
#
# LC_ALL=C awk -v rid=linux-x64 -f json.awk -f dotnet-sdk.awk releases.json
#
# Prints «<version><TAB><address><TAB><sha512>» and exits with 0, or says why on stderr and exits with 1. The archive
# is the file object with that address: https, on one of Microsoft's two hosts of .NET builds, named
# dotnet-sdk-<version>-<rid>.tar.gz, with a hash of 128 hexadecimal digits.
function json_begin(file) {}
function json_open(kind) {
if (kind == "o") {
address[json_depth] = ""
hash[json_depth] = ""
}
}
function json_scalar(kind, value) {
if (kind != "s" || json_depth == 0 || json_stack[json_depth] != "o") return
if (json_depth == 1 && json_at[1] == "latest-sdk") latest = value
if (json_at[json_depth] == "url") address[json_depth] = value
if (json_at[json_depth] == "hash") hash[json_depth] = value
}
function json_close(kind) {
if (kind == "o" && address[json_depth] != "") sha512[address[json_depth]] = hash[json_depth]
}
function json_end(file, error) {
problem = error
}
END {
if (problem != "") {
print "metadati dei rilasci .NET non validi: " problem > "/dev/stderr"
exit 1
}
if (latest !~ /^[0-9]+[.][0-9]+[.][0-9]+(-[0-9A-Za-z.]+)?$/) {
print "nei metadati dei rilasci .NET manca «latest-sdk» o non è una versione: «" substr(latest, 1, 40) "»" > "/dev/stderr"
exit 1
}
name = "dotnet-sdk-" latest "-" rid ".tar.gz"
for (candidate in sha512) {
if (substr(candidate, length(candidate) - length(name)) != "/" name) continue
if (candidate !~ /^https:[/][/](builds[.]dotnet[.]microsoft[.]com|dotnetcli[.]blob[.]core[.]windows[.]net)[/]/) continue
if (sha512[candidate] !~ /^[0-9a-fA-F]+$/ || length(sha512[candidate]) != 128) continue
found = candidate
}
if (found == "") {
print "nei metadati dei rilasci .NET non c'è l'archivio " name " con la sua impronta" > "/dev/stderr"
exit 1
}
print latest "\t" found "\t" tolower(sha512[found])
}
+70
View File
@@ -0,0 +1,70 @@
#!/usr/bin/env bash
# Installa l'SDK .NET per un lavoro della CI, al posto di actions/setup-dotnet (un'azione JavaScript, che vuole Node).
# Come quella prende l'ultimo SDK del canale (predefinito 10.0, come «10.0.x»), ma lo verifica: la versione e
# l'impronta SHA-512 dell'archivio vengono dai metadati dei rilasci di Microsoft (letti con json.awk e dotnet-sdk.awk,
# awk POSIX), l'archivio da builds.dotnet.microsoft.com, e si installa solo se l'impronta coincide. Mai uno script di
# installazione scaricato al volo.
#
# .gitea/scripts/dotnet.sh [canale]
#
# Dove: nella cache degli strumenti del runner (RUNNER_TOOL_CACHE, il volume act-toolcache che act_runner monta in ogni
# lavoro, anche nei contenitori), in febe-dotnet/<versione>; senza, nella cartella temporanea del lavoro. Una versione
# già installata e verificata non si riscarica; le versioni più vecchie di febe-dotnet si tolgono. Aggiunge dotnet al
# PATH dei passi seguenti (GITHUB_PATH) e scrive DOTNET_ROOT (GITHUB_ENV); fuori dalla CI stampa solo la cartella.
# Serve curl, tar, sha512sum e awk; le librerie di sistema dell'SDK (ICU, OpenSSL) ci sono già nell'immagine del runner
# e le installa ambiente-prove.sh nel contenitore Debian delle prove.
set -euo pipefail
canale="${1:-10.0}"
[[ "$canale" =~ ^[0-9]+\.[0-9]+$ ]] || { echo "Canale .NET non valido: «$canale» (per esempio 10.0)." >&2; exit 2; }
qui="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
case "$(uname -s)-$(uname -m)" in
Linux-x86_64) rid=linux-x64 ;;
Linux-aarch64) rid=linux-arm64 ;;
*) echo "Piattaforma non prevista per l'SDK .NET della CI: $(uname -s)-$(uname -m)." >&2; exit 2 ;;
esac
radice="${RUNNER_TOOL_CACHE:-${RUNNER_TEMP:-/tmp}}/febe-dotnet"
mkdir -p "$radice"
temporanea="$(mktemp -d "$radice/.scarico-XXXXXX")"
trap 'rm -rf "$temporanea"' EXIT
echo "== SDK .NET $canale"
curl -fsSL --retry 3 --retry-delay 5 --max-time 120 -o "$temporanea/releases.json" \
"https://builds.dotnet.microsoft.com/dotnet/release-metadata/$canale/releases.json"
scelta=$(LC_ALL=C awk -v rid="$rid" -f "$qui/json.awk" -f "$qui/dotnet-sdk.awk" "$temporanea/releases.json")
IFS=$'\t' read -r versione indirizzo sha512 <<< "$scelta"
[[ "$versione" =~ ^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.]+)?$ ]] || { echo "Versione dell'SDK non valida: «$versione»." >&2; exit 1; }
[[ "$versione" == "$canale".* ]] || { echo "L'SDK $versione non è del canale $canale." >&2; exit 1; }
cartella="$radice/$versione"
if [[ -x "$cartella/dotnet" && -f "$cartella/.febe-sha512" && "$(cat "$cartella/.febe-sha512")" == "$sha512" ]]; then
echo " $versione già installato in $cartella"
else
echo " $versione da $indirizzo"
curl -fsSL --retry 3 --retry-delay 5 --max-time 900 -o "$temporanea/sdk.tar.gz" "$indirizzo"
if ! echo "$sha512 $temporanea/sdk.tar.gz" | sha512sum -c --quiet -; then
echo "L'impronta SHA-512 dell'SDK $versione non è quella dei metadati di Microsoft: non si installa." >&2
exit 1
fi
mkdir "$temporanea/sdk"
tar -xzf "$temporanea/sdk.tar.gz" -C "$temporanea/sdk"
echo "$sha512" > "$temporanea/sdk/.febe-sha512"
rm -rf "$cartella"
mv "$temporanea/sdk" "$cartella"
fi
# Le versioni precedenti, che nessun lavoro userà più (la CI fa un lavoro alla volta), e gli scarichi interrotti.
for vecchia in "$radice"/* "$radice"/.scarico-*; do
[[ -d "$vecchia" && "$vecchia" != "$cartella" && "$vecchia" != "$temporanea" ]] || continue
rm -rf "$vecchia"
done
"$cartella/dotnet" --version
if [[ -n "${GITHUB_PATH:-}" ]]; then
echo "$cartella" >> "$GITHUB_PATH"
echo "DOTNET_ROOT=$cartella" >> "$GITHUB_ENV"
else
echo "$cartella"
fi
+22
View File
@@ -0,0 +1,22 @@
# Checks that every file named is a valid JSON text (controlli.sh), with json.awk:
#
# LC_ALL=C awk -f json.awk -f json-valido.awk <file.json>...
#
# Prints «file: reason» for each file that is not, and on stderr how many were checked; exits with 1 if one is not.
function json_begin(file) {}
function json_open(kind) {}
function json_close(kind) {}
function json_scalar(kind, value) {}
function json_end(file, error) {
checked++
if (error != "") {
print file ": " error
broken++
}
}
END {
printf " %d file controllati\n", checked > "/dev/stderr"
exit (broken > 0 ? 1 : 0)
}
+226
View File
@@ -0,0 +1,226 @@
# Reader of JSON texts (RFC 8259) for the scripts of the CI, in plain POSIX awk (mawk, gawk, busybox awk): no jq, no
# Node. Every file named on the command line is one JSON text. The program that includes this file (awk -f json.awk
# -f <program>.awk) defines five hooks, called while a file is read:
#
# json_begin(file) before the first value of the file
# json_open(kind) a container opens: kind "a" (array) or "o" (object); json_depth is now its level (the
# root is level 1) and json_stack[d] the kind of the container at level d
# json_close(kind) the container at level json_depth closes (json_depth drops after the call)
# json_scalar(kind, value) a value that is not a container: kind "s" string (decoded), "n" number (its text), "t"
# true, "f" false, "z" null
# json_end(file, error) after the file: error is "" for a valid JSON text, otherwise the reason (with the line)
#
# Where a value is: inside the container at level d it is at json_at[d], its key (object, decoded) or its index from 0
# (array). A scalar inside the container at level json_depth is at json_at[json_depth]; at the root json_depth is 0.
# After an error the rest of that file is skipped and only json_end follows; an empty file is an error, as for every
# JSON parser. The hooks must not call exit: the program records what it needs and decides in its own END, which runs
# after the END of this file (it comes first on the command line).
#
# Run with LC_ALL=C: the text is read as bytes, a leading BOM is skipped and a string may hold any byte from 0x20 on
# (UTF-8 is not checked). \uXXXX escapes below 0x80 are decoded; the others stay as they are written, which is enough
# for the names, versions, dates and addresses the CI compares. Tokens never span lines in JSON (a string cannot hold a
# raw line break), so each line is cut once at the quotes and once at the punctuation: the work grows with the size of
# the text, never with its square.
BEGIN {
json_file = ""
json_control = "[" sprintf("%c", 1) "-" sprintf("%c", 31) "]"
json_escape = "\\\\([\"\\\\/bfnrt]|u[0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f])"
json_number = "^-?(0|[1-9][0-9]*)([.][0-9]+)?([eE][-+]?[0-9]+)?$"
}
FNR == 1 {
if (json_file != "") json_finish()
json_start(FILENAME)
if (substr($0, 1, 3) == "\357\273\277") $0 = substr($0, 4)
}
{
if (json_error == "") json_line($0)
}
END {
if (json_file != "") json_finish()
for (json_i = 1; json_i < ARGC; json_i++) {
json_f = ARGV[json_i]
if (json_f == "" || (json_f in json_seen) || json_f ~ /^[A-Za-z_][A-Za-z0-9_]*=/) continue
json_start(json_f)
json_fail("file vuoto")
json_finish()
}
}
function json_start(file) {
json_file = file
json_seen[file] = 1
json_depth = 0
json_state = "V"
json_error = ""
json_instring = 0
json_buffer = ""
json_lineno = 0
json_begin(file)
}
function json_finish() {
if (json_error == "") {
if (json_instring) json_fail("stringa non chiusa")
else if (json_state != "E") json_fail(json_depth > 0 || json_state != "V" ? "testo interrotto" : "file vuoto")
}
json_end(json_file, json_error)
json_file = ""
}
function json_fail(message) {
if (json_error == "") json_error = (json_lineno > 0 ? "riga " json_lineno ": " : "") message
return 0
}
# One line: the parts between quotes alternate between text outside and inside strings, except where a quote is
# escaped (an odd number of backslashes before it), which stays in the string.
function json_line(line, n, parts, i) {
json_lineno = FNR
n = split(line, parts, "\"")
for (i = 1; i <= n; i++) {
if (json_instring) {
json_buffer = json_buffer parts[i]
if (i == n) return json_fail("stringa non chiusa a fine riga")
if (json_escaped(json_buffer)) {
json_buffer = json_buffer "\""
continue
}
json_instring = 0
json_string(json_buffer)
} else {
json_plain(parts[i])
if (i < n && json_error == "") {
json_instring = 1
json_buffer = ""
}
}
if (json_error != "") return 0
}
return 1
}
function json_escaped(text) {
return match(text, /[\\]+$/) && RLENGTH % 2 == 1
}
# Text outside strings: punctuation, numbers, true, false, null and the four blanks of JSON.
function json_plain(text, n, tokens, i) {
gsub(/\{/, " { ", text)
gsub(/\}/, " } ", text)
gsub(/\[/, " [ ", text)
gsub(/\]/, " ] ", text)
gsub(/,/, " , ", text)
gsub(/:/, " : ", text)
gsub(/\r/, " ", text)
n = split(text, tokens, " ")
for (i = 1; i <= n; i++) {
json_token(tokens[i])
if (json_error != "") return 0
}
return 1
}
function json_token(token, kind) {
if (token == "{" || token == "[") {
if (json_state != "V" && json_state != "VA") return json_fail("«" token "» inatteso")
json_enter()
json_depth++
json_stack[json_depth] = token == "{" ? "o" : "a"
json_index[json_depth] = 0
json_at[json_depth] = ""
json_state = token == "{" ? "KO" : "VA"
json_open(json_stack[json_depth])
return 1
}
if (token == "}" || token == "]") {
kind = token == "}" ? "o" : "a"
if (json_depth == 0 || json_stack[json_depth] != kind) return json_fail("«" token "» inatteso")
if (json_state != "N" && !(kind == "o" && json_state == "KO") && !(kind == "a" && json_state == "VA")) return json_fail("«" token "» inatteso")
json_close(kind)
json_depth--
json_state = json_depth > 0 ? "N" : "E"
return 1
}
if (token == ",") {
if (json_state != "N") return json_fail("«,» inattesa")
if (json_stack[json_depth] == "o") {
json_state = "K"
} else {
json_index[json_depth]++
json_state = "V"
}
return 1
}
if (token == ":") {
if (json_state != ":") return json_fail("«:» inattesi")
json_state = "V"
return 1
}
if (token == "true") kind = "t"
else if (token == "false") kind = "f"
else if (token == "null") kind = "z"
else if (token ~ json_number) kind = "n"
else return json_fail("«" substr(token, 1, 20) "» non è un valore JSON")
if (json_state != "V" && json_state != "VA") return json_fail("«" substr(token, 1, 20) "» inatteso")
json_enter()
json_scalar(kind, token)
json_state = json_depth > 0 ? "N" : "E"
return 1
}
# A whole string, without its quotes: a key or a value.
function json_string(raw, rest, value) {
if (raw ~ json_control) return json_fail("carattere di controllo in una stringa")
rest = raw
gsub(json_escape, "", rest)
if (index(rest, "\\") > 0) return json_fail("sequenza «\\» non valida in una stringa")
value = json_unescape(raw)
if (json_state == "K" || json_state == "KO") {
json_at[json_depth] = value
json_state = ":"
return 1
}
if (json_state != "V" && json_state != "VA") return json_fail("stringa inattesa")
json_enter()
json_scalar("s", value)
json_state = json_depth > 0 ? "N" : "E"
return 1
}
# A value starts inside the current container: in an array its place is the running index.
function json_enter() {
if (json_depth > 0 && json_stack[json_depth] == "a") json_at[json_depth] = json_index[json_depth]
}
function json_unescape(text, out, i, c, code) {
if (index(text, "\\") == 0) return text
out = ""
while ((i = index(text, "\\")) > 0) {
out = out substr(text, 1, i - 1)
c = substr(text, i + 1, 1)
if (c == "u") {
code = json_hex(substr(text, i + 2, 4))
out = out (code > 0 && code < 128 ? sprintf("%c", code) : "\\u" substr(text, i + 2, 4))
text = substr(text, i + 6)
} else {
if (c == "b") c = "\b"
else if (c == "f") c = "\f"
else if (c == "n") c = "\n"
else if (c == "r") c = "\r"
else if (c == "t") c = "\t"
out = out c
text = substr(text, i + 2)
}
}
return out text
}
function json_hex(digits, value, i) {
value = 0
for (i = 1; i <= length(digits); i++) value = value * 16 + index("0123456789abcdef", tolower(substr(digits, i, 1))) - 1
return value
}
+102 -36
View File
@@ -36,8 +36,9 @@
# stretta di prima del 21 ottobre 2026, ora solo a mano
# pulizia-docker.sh completa residui, febe:ci, resti di act_runner, le immagini che nessun contenitore
# usa create più di 24 ore fa, la cache di costruzione non usata da 24 ore e,
# con REGISTRY_TOKEN, le etichette sha- del registro oltre le 10 più recenti
# (flusso «pulizia», ogni lunedì e a mano)
# con REGISTRY_TOKEN, le etichette sha- del registro oltre le 10 più recenti e
# gli artefatti della CI (febe-ci) di più di 14 giorni (flusso «pulizia», ogni
# lunedì e a mano)
# pulizia-docker.sh <modo> --prova elenca che cosa toglierebbe e non toglie nulla: solo comandi che leggono
# (sul registro solo GET)
#
@@ -49,7 +50,8 @@
# il filtro delle 24 ore; mai un contenitore, un volume o una rete che non sia della CI. Le immagini le toglie Docker
# stesso (image prune), che non toglie mai un'immagine usata da un contenitore, nemmeno fermo; con -a, però, le toglie i
# nomi in più, e lo script li scrive (nella prova li stima, secondo lo store). Sul registro mai main, latest o una
# versione X.Y.Z: solo le etichette sha-<esadecimale> della verifica.
# versione X.Y.Z: solo le etichette sha-<esadecimale> della verifica e gli artefatti <x.y.z>-ci.<n> e
# <x.y.z>-rilascio.<n> del pacchetto generico febe-ci.
#
# Nei modi «residui», «settimanale» e «completa» un contenitore di prova si toglie solo se è fermo. Uno ancora acceso
# dopo 90 minuti (il suo lavoro è stato ucciso proprio durante la prova del contenitore) resta dov'è: lo si segnala, con
@@ -63,7 +65,7 @@
#
# Variabili per il registro (modo «completa»): REGISTRY_TOKEN (token con «package: read and write», mai stampato),
# GITEA_API (l'API del server, per esempio https://gitea.example/api/v1) e PROPRIETARIO (il proprietario del pacchetto
# febe). La scelta delle versioni da togliere sta in versioni-registro.js, accanto a questo script.
# febe). La scelta delle versioni da togliere sta in versioni-registro.sh, accanto a questo script.
set -uo pipefail
uso() {
@@ -103,9 +105,9 @@ tipi=()
note=()
# La cache di costruzione che si pota è quella del builder del demone, «default». docker builder è un alias di docker
# buildx quando c'è il plugin, e buildx lavora sul builder corrente: nel lavoro «immagine» è quello dell'esecuzione
# (setup-buildx-action lo crea con --use), che il modo «esecuzione» ha appena tolto. Gli altri comandi buildx di questo
# script indicano il builder per nome.
# buildx quando c'è il plugin, e buildx lavora sul builder corrente: se qualcuno avesse reso corrente il builder
# dell'esecuzione (costruisci-immagine.sh builder non lo fa), il modo «esecuzione» l'avrebbe appena tolto. Gli altri
# comandi buildx di questo script indicano il builder per nome.
export BUILDX_BUILDER=default
avviso() {
@@ -693,11 +695,16 @@ spiega() {
# ne arriva una vuota (il server può darne
# meno di 50 per pagina)
# DELETE /api/v1/packages/{proprietario}/container/febe/{versione} una versione (risponde 204)
# Quali togliere lo sceglie versioni-registro.js; qui si ricontrolla la forma sha-<esadecimale> prima di ogni DELETE.
# Ogni rifiuto dell'API è un avviso che non fa diventare rosso il lavoro. Le versioni sha256:… senza etichetta (i
# Quali togliere lo sceglie versioni-registro.sh (awk POSIX con json.awk: niente Node, niente jq); qui si ricontrolla
# la forma sha-<esadecimale> prima di ogni DELETE. Ogni rifiuto dell'API è un avviso che non fa diventare rosso il
# lavoro, e dopo un rifiuto il registro non si tocca più (il token è lo stesso). Le versioni sha256:… senza etichetta (i
# manifest figli di un indice, con gli strati) non si toccano mai: l'API non dice se un'etichetta le usa ancora. Si
# dice solo quante sono; la CI pubblica manifest semplici (costruisci-immagine.sh), quindi non dovrebbero essercene, e
# quelle che nessuna etichetta usa le toglie una regola di pulizia di Gitea (docs/processo.md, «Registro dei container»).
# Poi gli artefatti della CI (artefatti.sh): le versioni del pacchetto generico febe-ci create più di 14 giorni fa,
# GET /api/v1/packages/{proprietario}/generic/febe-ci?page=N&limit=50
# DELETE /api/v1/packages/{proprietario}/generic/febe-ci/{versione} la versione con i suoi file (204)
# solo con la forma <x.y.z>-ci.<n> o <x.y.z>-rilascio.<n>, ricontrollata prima di ogni DELETE.
registro() {
local tenere=10
echo "== Registro: le etichette sha- del pacchetto febe oltre le $tenere più recenti"
@@ -710,40 +717,58 @@ registro() {
return 0
fi
local programma
for programma in curl node; do
for programma in curl awk sort; do
command -v "$programma" > /dev/null || { segnala "Manca $programma: il registro non si tocca."; return 0; }
done
local base="${GITEA_API%/}/packages/$PROPRIETARIO/container/febe" cartella pagina codice scelte
local base="${GITEA_API%/}/packages/$PROPRIETARIO/container/febe" cartella codice scelte esito
cartella=$(mktemp -d) || { segnala "Non riesco a creare una cartella temporanea: il registro non si tocca."; return 0; }
for ((pagina = 1; ; pagina++)); do
if ((pagina > 200)); then
segnala "Più di 200 pagine di versioni sul registro: il registro non si tocca."
rm -rf "$cartella"
return 0
fi
codice=$(chiedi GET "$base?page=$pagina&limit=50" "$cartella/pagina-$pagina.json")
if [[ "$codice" == 404 && "$pagina" == 1 ]]; then
echo " Il pacchetto febe non è ancora sul registro: niente da togliere."
rm -rf "$cartella"
return 0
fi
if [[ "$codice" != 200 ]]; then
segnala "L'API dei pacchetti di Gitea risponde $(spiega "$codice") alla pagina $pagina delle versioni: il registro non si tocca."
rm -rf "$cartella"
return 0
fi
case "$(tr -d '[:space:]' < "$cartella/pagina-$pagina.json")" in
"[]" | null) break ;;
esac
done
local senza_etichetta quante
if ! scelte=$(node "$cartella_script/versioni-registro.js" "$tenere" "$cartella"/pagina-*.json) \
|| ! senza_etichetta=$(node "$cartella_script/versioni-registro.js" senza-etichetta "$cartella"/pagina-*.json); then
segnala "Non riesco a leggere le versioni del pacchetto febe: il registro non si tocca."
esito=0
pagine "$base" "$cartella" febe || esito=$?
if ((esito == 2)); then
rm -rf "$cartella"
return 0
fi
if ((esito == 1)); then
echo " Il pacchetto febe non è ancora sul registro: niente da togliere."
else
contenitore "$base" "$cartella"
fi
rm -rf "$cartella"
artefatti_della_ci
}
# Le pagine delle versioni di un pacchetto nella cartella, pagina-<n>.json, fino alla prima vuota (il server può darne
# meno di 50 per pagina). Esce con 0 se le ha lette, 1 se il pacchetto non c'è (404 alla prima pagina), 2 se l'API
# rifiuta (e lo segnala).
pagine() {
local base="$1" cartella="$2" nome="$3" pagina codice
for ((pagina = 1; ; pagina++)); do
if ((pagina > 200)); then
segnala "Più di 200 pagine di versioni di $nome sul registro: il registro non si tocca."
return 2
fi
codice=$(chiedi GET "$base?page=$pagina&limit=50" "$cartella/pagina-$pagina.json")
if [[ "$codice" == 404 && "$pagina" == 1 ]]; then
return 1
fi
if [[ "$codice" != 200 ]]; then
segnala "L'API dei pacchetti di Gitea risponde $(spiega "$codice") alla pagina $pagina delle versioni di $nome: il registro non si tocca."
return 2
fi
case "$(tr -d '[:space:]' < "$cartella/pagina-$pagina.json")" in
"[]" | null) return 0 ;;
esac
done
}
# Le etichette sha- del contenitore febe, dalle pagine già lette.
contenitore() {
local base="$1" cartella="$2" scelte senza_etichetta quante codice
if ! scelte=$(bash "$cartella_script/versioni-registro.sh" "$tenere" "$cartella"/pagina-*.json) \
|| ! senza_etichetta=$(bash "$cartella_script/versioni-registro.sh" senza-etichetta "$cartella"/pagina-*.json); then
segnala "Non riesco a leggere le versioni del pacchetto febe: il registro non si tocca."
return 0
fi
quante=$(grep -c . <<< "$senza_etichetta")
if ((quante > 0)); then
echo " $quante versioni senza etichetta (sha256:…, i manifest di un indice con i loro strati): restano, questa pulizia non le tocca mai (docs/processo.md, «Registro dei container»)"
@@ -775,6 +800,47 @@ registro() {
done <<< "$scelte"
}
# Gli artefatti della CI (artefatti.sh): le versioni del pacchetto generico febe-ci create più di 14 giorni fa, come la
# scadenza degli artefatti di una volta.
artefatti_della_ci() {
local giorni=14 base="${GITEA_API%/}/packages/$PROPRIETARIO/generic/febe-ci" cartella esito scelte versione creata codice
echo "== Registro: gli artefatti della CI (pacchetto febe-ci) creati più di $giorni giorni fa"
cartella=$(mktemp -d) || { segnala "Non riesco a creare una cartella temporanea: gli artefatti restano."; return 0; }
esito=0
pagine "$base" "$cartella" febe-ci || esito=$?
if ((esito == 1)); then
echo " Il pacchetto febe-ci non è ancora sul registro: niente da togliere."
elif ((esito == 0)) && ! scelte=$(bash "$cartella_script/versioni-registro.sh" scadute "$giorni" "$(date +%s)" "$cartella"/pagina-*.json); then
segnala "Non riesco a leggere le versioni del pacchetto febe-ci: gli artefatti restano."
esito=3
fi
rm -rf "$cartella"
((esito == 0)) || return 0
if [[ -z "${scelte:-}" ]]; then
echo " niente da togliere"
return 0
fi
while IFS=$'\t' read -r versione creata; do
[[ -n "${versione:-}" ]] || continue
if [[ ! "$versione" =~ ^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?-(ci|rilascio)\.[0-9]+$ ]]; then
segnala "Versione inattesa «$versione» fra gli artefatti da togliere: resta."
continue
fi
if ((prova)); then
echo " toglierei febe-ci $versione (caricata il $creata)"
conta "artefatti della CI sul registro"
continue
fi
codice=$(chiedi DELETE "$base/$versione" /dev/null)
if [[ "$codice" == 204 ]]; then
echo " febe-ci $versione tolta (caricata il $creata)"
conta "artefatti della CI sul registro"
else
segnala "Non riesco a togliere febe-ci $versione dal registro: l'API risponde $(spiega "$codice")."
fi
done <<< "$scelte"
}
# La cache con lo stesso limite del lunedì: senza, a ogni push di ogni ramo se ne andrebbero gli strati intermedi e le
# cache montate (RUN --mount=type=cache) che le costruzioni degli altri progetti hanno appena usato.
penzolanti() {
+2 -2
View File
@@ -6,7 +6,7 @@
# .gitea/scripts/riepilogo-prove.sh <cartella dei .trx> [saltate ammesse]
#
# Esce con 1 se una prova è fallita, se le saltate sono più di quelle ammesse (predefinito 0: nella CI ci sono
# Chromium, Xvfb, ffmpeg e Node, quindi nessuna prova ha motivo di saltarsi) o se non c'è nessun risultato.
# Chromium, Xvfb e ffmpeg, quindi nessuna prova ha motivo di saltarsi) o se non c'è nessun risultato.
set -euo pipefail
cartella="${1:?Indica la cartella con i file .trx.}"
@@ -96,7 +96,7 @@ if (( fallite_totali > 0 )); then
esito=1
fi
if (( saltate_totali > ammesse )); then
echo "Prove saltate: $saltate_totali, più delle $ammesse ammesse. Qui ci sono Chromium, Xvfb, ffmpeg e Node: una prova che si salta segnala un ambiente rotto, non una prova superata." >&2
echo "Prove saltate: $saltate_totali, più delle $ammesse ammesse. Qui ci sono Chromium, Xvfb e ffmpeg: una prova che si salta segnala un ambiente rotto, non una prova superata." >&2
esito=1
fi
+148
View File
@@ -0,0 +1,148 @@
# For versioni-registro.sh, with json.awk: the versions of one package of Gitea's registry in the pages of
# GET /api/v1/packages/{owner}/{type}/{name} of Gitea 28, given as files:
#
# LC_ALL=C awk -v tipo=container -v nome=febe -f json.awk -f versioni-registro.awk <page.json>...
#
# A page is a list of versions with «type», «name», «version», «created_at» and «id»; an empty page may be «[]» or
# «null». Only the versions whose type and name are those asked count, and a version found in two pages counts once
# (the last one read wins, in the place of the first). For each it prints, in the order first met:
#
# <milliseconds since 1970 UTC, or «-» when created_at is not a date that can be read><TAB><id><TAB><order>
# <TAB><version><TAB><created_at as written>
#
# created_at is read as ISO 8601 / RFC 3339 like JavaScript's Date.parse: a date, or a date and time with «Z» or an
# offset (+02:00), seconds and fractions optional. A time without a zone is local time for JavaScript and would depend
# on the machine: here it is not a date, and in doubt nothing is removed. If a file is not JSON, or not a list (nor
# null), it prints nothing, says why on stderr and exits with 2.
function json_begin(file) {
root = ""
inside = 0
}
function json_open(kind) {
if (json_depth == 1) {
root = kind
} else if (json_depth == 2 && root == "a" && kind == "o") {
inside = 1
split("", field)
split("", seen)
}
}
function json_scalar(kind, value) {
if (json_depth == 0) {
root = kind == "z" ? "null" : "valore"
} else if (json_depth == 2 && inside) {
field[json_at[2]] = value
seen[json_at[2]] = kind
}
}
function json_close(kind) {
if (json_depth == 2 && inside) {
inside = 0
keep()
}
}
function json_end(file, error) {
if (error != "") {
problems = problems file ": " error "\n"
} else if (root != "a" && root != "null") {
problems = problems file ": non è un elenco di versioni\n"
}
}
function keep( version, created, id) {
if (seen["type"] != "s" || field["type"] != tipo || seen["name"] != "s" || field["name"] != nome) return
if (seen["version"] != "s") return
version = field["version"]
if (version ~ control) return
if (!("created_at" in seen)) created = "undefined"
else if (seen["created_at"] == "z") created = "null"
else if (seen["created_at"] == "t") created = "true"
else if (seen["created_at"] == "f") created = "false"
else created = field["created_at"]
gsub(control, "?", created)
id = 0
if (seen["id"] == "n" || (seen["id"] == "s" && field["id"] ~ /^[0-9]+$/)) id = field["id"] + 0
if (!(version in order)) order[version] = ++count
when[version] = seen["created_at"] == "s" ? milliseconds(field["created_at"]) : ""
number[version] = id
written[version] = created
}
# Milliseconds since 1970 UTC of an ISO 8601 date as Date.parse reads it, or "" if it is not one.
function milliseconds(text, y, mo, d, h, mi, s, ms, rest, offset, fraction) {
if (text !~ /^[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]/) return ""
y = substr(text, 1, 4) + 0
mo = substr(text, 6, 2) + 0
d = substr(text, 9, 2) + 0
h = mi = s = ms = offset = 0
rest = substr(text, 11)
if (rest != "") {
if (rest !~ /^T[0-9][0-9]:[0-9][0-9]/) return ""
h = substr(rest, 2, 2) + 0
mi = substr(rest, 5, 2) + 0
rest = substr(rest, 7)
if (rest ~ /^:[0-9][0-9]/) {
s = substr(rest, 2, 2) + 0
rest = substr(rest, 4)
if (match(rest, /^[.][0-9]+/)) {
fraction = substr(rest, 2, RLENGTH - 1) "00"
ms = substr(fraction, 1, 3) + 0
rest = substr(rest, RLENGTH + 1)
}
}
if (rest == "Z") offset = 0
else if (rest ~ /^[-+][0-9][0-9]:[0-9][0-9]$/) {
offset = substr(rest, 2, 2) * 60 + substr(rest, 5, 2)
if (substr(rest, 2, 2) + 0 > 23 || substr(rest, 5, 2) + 0 > 59) return ""
if (substr(rest, 1, 1) == "-") offset = -offset
} else return ""
}
if (mo < 1 || mo > 12 || d < 1 || d > days_in_month(y, mo)) return ""
if (h > 24 || mi > 59 || s > 59 || (h == 24 && (mi > 0 || s > 0 || ms > 0))) return ""
return ((days_from_civil(y, mo, d) * 86400 + h * 3600 + mi * 60 + s - offset * 60) * 1000 + ms)
}
function leap(y) {
return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0
}
function days_in_month(y, m) {
if (m == 2) return leap(y) ? 29 : 28
return (m == 4 || m == 6 || m == 9 || m == 11) ? 30 : 31
}
# Days from 1970-01-01 to a date of the proleptic Gregorian calendar (years 0 to 9999 here).
function days_from_civil(y, m, d, era, yoe, doy, doe) {
if (m <= 2) y--
era = int(y / 400)
if (y < 0 && y % 400 != 0) era--
yoe = y - era * 400
doy = int((153 * (m > 2 ? m - 3 : m + 9) + 2) / 5) + d - 1
doe = yoe * 365 + int(yoe / 4) - int(yoe / 100) + doy
return era * 146097 + doe - 719468
}
BEGIN {
control = "[" sprintf("%c", 1) "-" sprintf("%c", 31) "]"
if (tipo == "" || nome == "") {
print "versioni-registro.awk: servono -v tipo=… -v nome=…" > "/dev/stderr"
failed = 1
exit 2
}
}
END {
if (failed) exit 2
if (problems != "") {
printf "%s", problems > "/dev/stderr"
exit 2
}
for (version in order) {
printf "%s\t%.0f\t%d\t%s\t%s\n", when[version] == "" ? "-" : sprintf("%.0f", when[version]), number[version], order[version], version, written[version]
}
}
-82
View File
@@ -1,82 +0,0 @@
"use strict";
// Chooses the tags to remove from Gitea's container registry (pulizia-docker.sh, mode «completa»). It only reads the
// files it is given: no network, no writes, so it is tested with a JSON file.
//
// node versioni-registro.js <how many to keep> <page.json>...
// node versioni-registro.js senza-etichetta <page.json>...
//
// Each file is a page of the answer of GET /api/v1/packages/{owner}/container/febe of Gitea 28: a list of versions with
// «type», «name», «version» and «created_at» (an empty page may be «[]» or «null»). Only the versions of the container
// package «febe» count, and a version found in two pages counts once. Both forms print, oldest first and one per line,
// «version<TAB>created».
//
// With a number N: the sha-<7 to 40 hex digits> tags beyond the N newest by creation date. Everything else always
// stays: main, latest, the X.Y.Z releases (X.Y.Z-rc.N too), the digests (sha256:…), any other tag and a sha- tag
// without a date that can be read.
//
// With «senza-etichetta»: the untagged versions, sha256:<64 hex digits>. They are the manifests of an image index,
// which Gitea keeps as versions of their own with the configuration and the layers; nothing here removes them (Gitea
// cannot be asked through this API whether a tag still uses one), the cleanup only says how many there are.
//
// If a file is not a JSON list it exits with 2 and prints nothing: when in doubt nothing is removed.
// Messages are in Italian, like every message of the CI.
const fs = require("fs");
const [mode, ...pages] = process.argv.slice(2);
const untagged = mode === "senza-etichetta";
if (!(untagged || /^[0-9]+$/.test(mode || "")) || pages.length === 0) {
console.error("Uso: node versioni-registro.js <quante tenere> | senza-etichetta <pagina.json>...");
process.exit(2);
}
const shaTag = /^sha-[0-9a-f]{7,40}$/;
const digest = /^sha256:[0-9a-f]{64}$/;
const versions = new Map();
for (const file of pages) {
let page;
try {
page = JSON.parse(fs.readFileSync(file, "utf8").replace(/^/, ""));
} catch (error) {
console.error(`${file}: ${error.message}`);
process.exit(2);
}
if (page === null) {
continue;
}
if (!Array.isArray(page)) {
console.error(`${file}: non è un elenco di versioni`);
process.exit(2);
}
for (const version of page) {
if (version && version.type === "container" && version.name === "febe" && typeof version.version === "string") {
versions.set(version.version, version);
}
}
}
const dated = (version) => ({
name: version.version,
created: String(version.created_at),
time: Date.parse(version.created_at),
id: Number(version.id) || 0,
});
let chosen;
if (untagged) {
chosen = [...versions.values()]
.filter((version) => digest.test(version.version))
.map(dated)
.sort((a, b) => (Number.isFinite(a.time) ? a.time : 0) - (Number.isFinite(b.time) ? b.time : 0) || a.id - b.id);
} else {
chosen = [...versions.values()]
.filter((version) => shaTag.test(version.version))
.map(dated)
.filter((version) => Number.isFinite(version.time))
.sort((a, b) => b.time - a.time || b.id - a.id)
.slice(Number(mode))
.reverse();
}
for (const version of chosen) {
process.stdout.write(`${version.name}\t${version.created}\n`);
}
+68
View File
@@ -0,0 +1,68 @@
#!/usr/bin/env bash
# Sceglie le versioni da togliere dal registro dei pacchetti di Gitea (pulizia-docker.sh, modo «completa»). Legge solo
# i file che riceve, con json.awk e versioni-registro.awk (awk POSIX: niente jq, niente Node): niente rete, niente
# scritture, quindi si prova con un file JSON (PipelineTests).
#
# versioni-registro.sh <quante tenere> <pagina.json>... le etichette sha-<da 7 a 40 cifre esadecimali>
# del contenitore febe oltre le N più recenti
# versioni-registro.sh senza-etichetta <pagina.json>... le versioni sha256:<64 cifre> del contenitore
# febe (i manifest di un indice: solo da contare)
# versioni-registro.sh scadute <giorni> <adesso> <pagina.json>... le versioni <x.y.z>-ci.<n> e
# <x.y.z>-rilascio.<n> del pacchetto generico
# febe-ci (gli artefatti della CI, artefatti.sh)
# create più di <giorni> giorni prima di <adesso>,
# in secondi dal 1970
#
# Ogni pagina è una risposta di GET /api/v1/packages/{proprietario}/{tipo}/{nome} di Gitea 28. Stampa, dalla più
# vecchia e una per riga, «versione<TAB>creata». Tutto il resto resta sempre: main, latest, le versioni X.Y.Z (anche
# X.Y.Z-rc.N), i digest, ogni altra etichetta, una sha- o un artefatto senza una data che si legga. Fra le sha- contano
# le date, non il testo; a parità di data l'identificativo. Se un file non è un elenco JSON esce con 2 e non stampa
# nulla: nel dubbio non si toglie niente.
set -euo pipefail
qui="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
uso() {
echo "Uso: versioni-registro.sh <quante tenere> | senza-etichetta | scadute <giorni> <adesso> <pagina.json>..." >&2
exit 2
}
modo="${1:-}"
(($# > 0)) && shift
case "$modo" in
senza-etichetta) tipo=container nome=febe ;;
scadute)
(($# >= 2)) || uso
giorni="$1" adesso="$2"
shift 2
[[ "$giorni" =~ ^[0-9]{1,5}$ && "$adesso" =~ ^[0-9]{1,12}$ ]] || uso
tipo=generic nome=febe-ci
;;
*)
[[ "$modo" =~ ^[0-9]{1,6}$ ]] || uso
tipo=container nome=febe
;;
esac
(($# > 0)) || uso
export LC_ALL=C
tab=$'\t'
versioni=$(awk -v tipo="$tipo" -v nome="$nome" -f "$qui/json.awk" -f "$qui/versioni-registro.awk" "$@") || exit 2
# Righe: millisecondi (o «-»), identificativo, ordine, versione, data come scritta.
case "$modo" in
senza-etichetta)
awk -F "$tab" -v OFS="$tab" '$4 ~ /^sha256:[0-9a-f]+$/ && length($4) == 71 { if ($1 == "-") $1 = 0; print }' <<< "$versioni" \
| sort -t "$tab" -k1,1n -k2,2n -k3,3n | cut -f4,5
;;
scadute)
awk -F "$tab" -v limite="$(((adesso - giorni * 86400) * 1000))" \
'$1 != "-" && $1 + 0 < limite + 0 && $4 ~ /^[0-9]+[.][0-9]+[.][0-9]+(-[0-9A-Za-z.-]+)?-(ci|rilascio)[.][0-9]+$/' <<< "$versioni" \
| sort -t "$tab" -k1,1n -k2,2n -k3,3n | cut -f4,5
;;
*)
# Le più recenti prima (data, poi identificativo), si saltano le prime N, il resto dalla più vecchia.
awk -F "$tab" '$1 != "-" && $4 ~ /^sha-[0-9a-f]+$/ && length($4) >= 11 && length($4) <= 44' <<< "$versioni" \
| sort -t "$tab" -k1,1nr -k2,2nr -k3,3n | tail -n "+$((modo + 1))" \
| awk '{ righe[NR] = $0 } END { for (i = NR; i > 0; i--) print righe[i] }' | cut -f4,5
;;
esac
+23 -3
View File
@@ -11,8 +11,9 @@
# vecchi di 90 minuti;
# - le immagini che nessun contenitore usa, né acceso né fermo, create più di 24 ore fa (di un'immagine in uso Docker
# toglie i nomi in più), e la cache di costruzione del demone non usata da 24 ore. Le immagini di base
# (node:24-trixie, moby/buildkit, …) si riscaricano alla prima esecuzione che le chiede;
# - con il segreto REGISTRY_TOKEN, le etichette sha- del registro oltre le 10 più recenti; mai main, latest o X.Y.Z.
# (debian:trixie, moby/buildkit, …) si riscaricano alla prima esecuzione che le chiede;
# - con il segreto REGISTRY_TOKEN, le etichette sha- del registro oltre le 10 più recenti, mai main, latest o X.Y.Z,
# e gli artefatti della CI (pacchetto generico febe-ci, artefatti.sh) creati più di 14 giorni fa.
# Mai system prune, container prune, volume prune o network prune; mai un contenitore, un volume o una rete che non sia
# della CI. Un contenitore di prova ancora acceso si segnala e il lavoro diventa rosso; un rifiuto dell'API del
# registro è solo un avviso. Dettagli in .gitea/scripts/pulizia-docker.sh e in docs/processo.md, «Pulizia».
@@ -45,7 +46,26 @@ jobs:
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- uses: actions/checkout@v4
- name: Sorgenti
env:
TOKEN: ${{ gitea.token }}
SERVER: ${{ gitea.server_url }}
REPOSITORY: ${{ gitea.repository }}
PROFONDITA: "1"
run: |
git config --global --add safe.directory "$PWD"
git init -q .
git remote add origin "$SERVER/$REPOSITORY.git" 2> /dev/null || git remote set-url origin "$SERVER/$REPOSITORY.git"
GIT_CONFIG_VALUE_0="Authorization: basic $(printf 'x-access-token:%s' "$TOKEN" | base64 -w0)"
export GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0=http.extraHeader GIT_CONFIG_VALUE_0
profondita=()
[ "$PROFONDITA" = 0 ] || profondita=(--depth "$PROFONDITA")
if ! git fetch -q --no-tags "${profondita[@]}" origin "$GITHUB_SHA"; then
echo "Il server non dà il commit per identificativo: prendo $GITHUB_REF con tutta la storia."
git fetch -q --no-tags origin "+$GITHUB_REF:refs/remotes/origin/lavoro"
fi
git checkout -q --force --detach "$GITHUB_SHA"
git log -1 --format='Commit %h: %s'
# Gitea 28 mette nell'evento la casella «prova» come testo, "true" o "false"; il lunedì l'evento non ha input e
# la pulizia è quella vera. Un avvio con l'API passa il valore così com'è: qualunque altro («True», «1») ferma il
+127 -48
View File
@@ -2,16 +2,22 @@
# 1. prove: il tag coincide con <Version> di Directory.Build.props, la soluzione si compila con gli avvisi come errori
# e tutte le prove passano. Senza prove verdi non si costruisce né si rilascia nulla;
# 2. windows: Febe.exe in un file solo, il programma di installazione nostro (src/Febe.Installer) e lo zip portabile
# (installer/costruisci.sh, gira su Linux con il solo .NET SDK);
# (installer/costruisci.sh, gira su Linux con il solo .NET SDK): il cancello prima dell'immagine;
# 3. immagine: dopo l'installatore, l'immagine Docker (le prove girano anche dentro la build), provata senza rete e
# scansionata con Trivy come nella verifica (una CRITICAL con correzione ferma tutto), poi pubblicata sul registro
# dei container di Gitea come <registro>/<proprietario>/febe:X.Y.Z e :latest (solo per le versioni senza
# trattino). Il lavoro dice se l'ha pubblicata, e alla fine toglie sempre immagini, contenitori, cache e builder
# dell'esecuzione, poi le immagini senza nome e la cache di costruzione penzolante non usata da 24 ore di tutti i
# progetti del demone;
# 4. release: solo dopo le prove, l'installatore e l'immagine. Crea la release (o la completa, se esiste già) con
# installatore, zip portabile, modello Unraid e l'archivio per Docker Compose (compose.yml con il profilo seccomp
# accanto); le note dicono dove sta l'immagine, o che non è stata pubblicata.
# 4. release: solo dopo le prove, l'installatore e l'immagine. Ricostruisce installatore e zip dallo stesso commit con
# lo stesso script (senza azioni non c'è un passaggio di artefatti fra i lavori che non dipenda da REGISTRY_TOKEN,
# e la release deve uscire anche senza), poi crea la release (o la completa, se esiste già) con installatore, zip
# portabile, modello Unraid e l'archivio per Docker Compose (compose.yml con il profilo seccomp accanto); le note
# dicono dove sta l'immagine, o che non è stata pubblicata.
#
# Niente azioni, come nella verifica (decisione del 18 novembre 2026): sorgenti con git e il gettone del lavoro, SDK con
# .gitea/scripts/dotnet.sh, builder buildx con costruisci-immagine.sh builder, risultati delle prove e rapporto di Trivy
# nel pacchetto generico febe-ci (versione <versione>-rilascio.<numero>, con REGISTRY_TOKEN; artefatti.sh).
#
# Segreto del repository (Impostazioni ▸ Actions ▸ Segreti): REGISTRY_TOKEN, un token dell'utente con i permessi
# «package: read and write». Senza, l'immagine si costruisce e si prova ma non si pubblica: la release esce lo stesso,
@@ -29,21 +35,46 @@ on:
push:
tags: ["v*"]
env:
DOTNET_NOLOGO: "1"
DOTNET_CLI_TELEMETRY_OPTOUT: "1"
DOTNET_SKIP_FIRST_TIME_EXPERIENCE: "1"
jobs:
prove:
runs-on: ubuntu-latest
timeout-minutes: 60
env:
NUMERO: ${{ gitea.run_number }}
steps:
- uses: actions/checkout@v4
- name: Sorgenti
env:
TOKEN: ${{ gitea.token }}
SERVER: ${{ gitea.server_url }}
REPOSITORY: ${{ gitea.repository }}
PROFONDITA: "1"
run: |
git config --global --add safe.directory "$PWD"
git init -q .
git remote add origin "$SERVER/$REPOSITORY.git" 2> /dev/null || git remote set-url origin "$SERVER/$REPOSITORY.git"
GIT_CONFIG_VALUE_0="Authorization: basic $(printf 'x-access-token:%s' "$TOKEN" | base64 -w0)"
export GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0=http.extraHeader GIT_CONFIG_VALUE_0
profondita=()
[ "$PROFONDITA" = 0 ] || profondita=(--depth "$PROFONDITA")
if ! git fetch -q --no-tags "${profondita[@]}" origin "$GITHUB_SHA"; then
echo "Il server non dà il commit per identificativo: prendo $GITHUB_REF con tutta la storia."
git fetch -q --no-tags origin "+$GITHUB_REF:refs/remotes/origin/lavoro"
fi
git checkout -q --force --detach "$GITHUB_SHA"
git log -1 --format='Commit %h: %s'
- name: Versione coerente con il tag
run: |
V=$(sed -n 's:.*<Version>\(.*\)</Version>.*:\1:p' Directory.Build.props | head -n 1)
[ "v$V" = "${GITHUB_REF_NAME}" ] || { echo "Il tag ${GITHUB_REF_NAME} non coincide con <Version> $V"; exit 1; }
- uses: actions/setup-dotnet@v4
with:
dotnet-version: "10.0.x"
- name: SDK .NET 10
run: bash .gitea/scripts/dotnet.sh 10.0
- name: Compilazione (avvisi = errori)
run: dotnet build Febe.slnx -c Release -nologo -warnaserror
@@ -53,39 +84,51 @@ jobs:
dotnet test tests/Febe.Tests -c Release --no-build --nologo
--logger "trx;LogFileName=prove.trx" --results-directory out/prove
- name: Risultati
- name: Risultati (pacchetto febe-ci)
if: always()
uses: actions/upload-artifact@v3
with:
name: risultati-prove
path: out/prove/*.trx
if-no-files-found: ignore
env:
REGISTRY_TOKEN: ${{ secrets.REGISTRY_TOKEN }}
GITEA_URL: ${{ gitea.server_url }}
PROPRIETARIO: ${{ gitea.repository_owner }}
run: |
[ -f out/prove/prove.trx ] || { echo "Nessun risultato delle prove."; exit 0; }
bash .gitea/scripts/artefatti.sh rilascio out/prove/prove.trx
windows:
runs-on: ubuntu-latest
needs: prove
timeout-minutes: 30
steps:
- uses: actions/checkout@v4
- name: Sorgenti
env:
TOKEN: ${{ gitea.token }}
SERVER: ${{ gitea.server_url }}
REPOSITORY: ${{ gitea.repository }}
PROFONDITA: "1"
run: |
git config --global --add safe.directory "$PWD"
git init -q .
git remote add origin "$SERVER/$REPOSITORY.git" 2> /dev/null || git remote set-url origin "$SERVER/$REPOSITORY.git"
GIT_CONFIG_VALUE_0="Authorization: basic $(printf 'x-access-token:%s' "$TOKEN" | base64 -w0)"
export GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0=http.extraHeader GIT_CONFIG_VALUE_0
profondita=()
[ "$PROFONDITA" = 0 ] || profondita=(--depth "$PROFONDITA")
if ! git fetch -q --no-tags "${profondita[@]}" origin "$GITHUB_SHA"; then
echo "Il server non dà il commit per identificativo: prendo $GITHUB_REF con tutta la storia."
git fetch -q --no-tags origin "+$GITHUB_REF:refs/remotes/origin/lavoro"
fi
git checkout -q --force --detach "$GITHUB_SHA"
git log -1 --format='Commit %h: %s'
- name: Versione
run: echo "VERSION=${GITHUB_REF_NAME#v}" >> "$GITHUB_ENV"
- uses: actions/setup-dotnet@v4
with:
dotnet-version: "10.0.x"
- name: SDK .NET 10
run: bash .gitea/scripts/dotnet.sh 10.0
- name: Febe.exe, programma di installazione e zip portabile
run: bash installer/costruisci.sh "$VERSION"
- uses: actions/upload-artifact@v3
with:
name: windows
path: |
out/Febe-Setup-*.exe
out/Febe-*-portabile.zip
if-no-files-found: error
immagine:
runs-on: ubuntu-latest
# Dopo l'installatore: :X.Y.Z e :latest escono solo se anche la release potrà uscire.
@@ -94,6 +137,7 @@ jobs:
env:
FLUSSO: rilascio
ESECUZIONE: ${{ gitea.run_id }}
NUMERO: ${{ gitea.run_number }}
BUILDER: febe-ci-${{ gitea.run_id }}
PROVA: febe-ci:${{ gitea.run_id }}
outputs:
@@ -101,7 +145,26 @@ jobs:
pubblicata: ${{ steps.pubblicazione.outputs.pubblicata }}
motivo: ${{ steps.segreto.outputs.motivo }}
steps:
- uses: actions/checkout@v4
- name: Sorgenti
env:
TOKEN: ${{ gitea.token }}
SERVER: ${{ gitea.server_url }}
REPOSITORY: ${{ gitea.repository }}
PROFONDITA: "1"
run: |
git config --global --add safe.directory "$PWD"
git init -q .
git remote add origin "$SERVER/$REPOSITORY.git" 2> /dev/null || git remote set-url origin "$SERVER/$REPOSITORY.git"
GIT_CONFIG_VALUE_0="Authorization: basic $(printf 'x-access-token:%s' "$TOKEN" | base64 -w0)"
export GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0=http.extraHeader GIT_CONFIG_VALUE_0
profondita=()
[ "$PROFONDITA" = 0 ] || profondita=(--depth "$PROFONDITA")
if ! git fetch -q --no-tags "${profondita[@]}" origin "$GITHUB_SHA"; then
echo "Il server non dà il commit per identificativo: prendo $GITHUB_REF con tutta la storia."
git fetch -q --no-tags origin "+$GITHUB_REF:refs/remotes/origin/lavoro"
fi
git checkout -q --force --detach "$GITHUB_SHA"
git log -1 --format='Commit %h: %s'
# Ciò che un'esecuzione interrotta non ha potuto togliere, e un tentativo precedente di questa stessa esecuzione.
- name: Resti di esecuzioni interrotte
@@ -122,18 +185,11 @@ jobs:
echo "ARCHIVIO=${RUNNER_TEMP:-/tmp}/febe-$ESECUZIONE.tar" >> "$GITHUB_ENV"
echo "REGISTRY=$REGISTRY" >> "$GITHUB_ENV"
echo "IMAGE=$REGISTRY/$OWNER/febe" >> "$GITHUB_ENV"
echo "registro=$REGISTRY" >> "$GITHUB_OUTPUT"
echo "immagine=$REGISTRY/$OWNER/febe" >> "$GITHUB_OUTPUT"
# Un builder buildx proprio, che sa che il registro di casa risponde in HTTP.
- 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: Builder buildx dell'esecuzione
run: bash .gitea/scripts/costruisci-immagine.sh builder "$REGISTRY"
# Gli stessi argomenti ed etichette della pubblicazione (costruisci-immagine.sh): quella esce dalla cache di questa.
- name: Costruzione dell'immagine (le prove girano dentro la build)
@@ -147,13 +203,15 @@ jobs:
- name: Vulnerabilità dell'immagine (Trivy)
run: bash .gitea/scripts/scansione-immagine.sh "$ARCHIVIO" out/sicurezza
- name: Rapporto di Trivy
- name: Rapporto di Trivy (pacchetto febe-ci)
if: ${{ !cancelled() }}
uses: actions/upload-artifact@v3
with:
name: sicurezza-immagine
path: out/sicurezza/trivy.json
if-no-files-found: ignore
env:
REGISTRY_TOKEN: ${{ secrets.REGISTRY_TOKEN }}
GITEA_URL: ${{ gitea.server_url }}
PROPRIETARIO: ${{ gitea.repository_owner }}
run: |
[ -f out/sicurezza/trivy.json ] || { echo "Nessun rapporto di Trivy."; exit 0; }
bash .gitea/scripts/artefatti.sh rilascio out/sicurezza/trivy.json
- name: Segreto per il registro
id: segreto
@@ -216,14 +274,35 @@ jobs:
# mancanza del segreto (il lavoro «immagine» lo dice e le note lo riportano). Se la costruzione, la prova del
# contenitore, la scansione o la spinta sul registro falliscono, non esce nessuna release.
needs: [prove, windows, immagine]
timeout-minutes: 15
timeout-minutes: 40
steps:
- uses: actions/checkout@v4
- name: Sorgenti
env:
TOKEN: ${{ gitea.token }}
SERVER: ${{ gitea.server_url }}
REPOSITORY: ${{ gitea.repository }}
PROFONDITA: "1"
run: |
git config --global --add safe.directory "$PWD"
git init -q .
git remote add origin "$SERVER/$REPOSITORY.git" 2> /dev/null || git remote set-url origin "$SERVER/$REPOSITORY.git"
GIT_CONFIG_VALUE_0="Authorization: basic $(printf 'x-access-token:%s' "$TOKEN" | base64 -w0)"
export GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0=http.extraHeader GIT_CONFIG_VALUE_0
profondita=()
[ "$PROFONDITA" = 0 ] || profondita=(--depth "$PROFONDITA")
if ! git fetch -q --no-tags "${profondita[@]}" origin "$GITHUB_SHA"; then
echo "Il server non dà il commit per identificativo: prendo $GITHUB_REF con tutta la storia."
git fetch -q --no-tags origin "+$GITHUB_REF:refs/remotes/origin/lavoro"
fi
git checkout -q --force --detach "$GITHUB_SHA"
git log -1 --format='Commit %h: %s'
- uses: actions/download-artifact@v3
with:
name: windows
path: out
- name: SDK .NET 10
run: bash .gitea/scripts/dotnet.sh 10.0
# Lo stesso commit e lo stesso script del lavoro «windows», che ha già fatto da cancello prima dell'immagine.
- name: Febe.exe, programma di installazione e zip portabile per la release
run: bash installer/costruisci.sh "${GITHUB_REF_NAME#v}"
- name: Release con installatore, zip portabile, modello Unraid e archivio per Compose
env:
+156 -65
View File
@@ -1,26 +1,33 @@
# 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);
# controlli sintassi degli script, flussi in YAML a blocchi e senza azioni, 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 e Node veri in un contenitore Debian 13: nessuna prova deve saltarsi.
# Chromium, Xvfb e ffmpeg 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-<versione>-ci.<numero>.exe (il programma di installazione nostro, src/Febe.Installer) e
# lo zip portabile, artefatti per 14 giorni; serve solo il .NET SDK;
# lo zip portabile; serve solo il .NET SDK;
# immagine dopo l'installatore: 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, poi le immagini senza nome e la
# cache di costruzione penzolante non usata da 24 ore di tutti i progetti del demone.
#
# Niente azioni (decisione di Alberto del 18 novembre 2026: niente componenti esterni): ogni passo è un comando. I
# sorgenti arrivano con git e il gettone del lavoro, l'SDK .NET con .gitea/scripts/dotnet.sh (verificato con l'impronta
# dei metadati di Microsoft), il builder buildx con costruisci-immagine.sh builder. Gli artefatti (risultati delle
# prove, installatore e zip, rapporti di gitleaks e di Trivy) vanno nel registro dei pacchetti di Gitea, pacchetto
# generico febe-ci, versione <versione>-ci.<numero>, con REGISTRY_TOKEN (.gitea/scripts/artefatti.sh); la pulizia del
# lunedì toglie quelli di più di 14 giorni. Senza il segreto un avviso, e il lavoro resta verde. Nessun passo usa Node.
#
# 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.
# Che cosa di Gitea 28 si usa e perché: docs/decisioni.md (20 ottobre e 18 novembre 2026) e docs/processo.md.
name: verifica
on:
@@ -57,11 +64,32 @@ jobs:
controlli:
runs-on: ubuntu-latest
timeout-minutes: 10
env:
NUMERO: ${{ gitea.run_number }}
steps:
# Tutta la storia: gitleaks legge ogni commit da cui discende quello verificato.
- uses: actions/checkout@v4
with:
fetch-depth: 0
# I sorgenti del commit con git e il gettone del lavoro, che vale solo finché il lavoro gira e non resta nella
# configurazione del repository. Qui tutta la storia (PROFONDITA 0): gitleaks legge ogni commit da cui discende
# quello verificato. Lo stesso passo, lettera per lettera, apre ogni lavoro (lo controlla PipelineTests).
- name: Sorgenti
env:
TOKEN: ${{ gitea.token }}
SERVER: ${{ gitea.server_url }}
REPOSITORY: ${{ gitea.repository }}
PROFONDITA: "0"
run: |
git config --global --add safe.directory "$PWD"
git init -q .
git remote add origin "$SERVER/$REPOSITORY.git" 2> /dev/null || git remote set-url origin "$SERVER/$REPOSITORY.git"
GIT_CONFIG_VALUE_0="Authorization: basic $(printf 'x-access-token:%s' "$TOKEN" | base64 -w0)"
export GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0=http.extraHeader GIT_CONFIG_VALUE_0
profondita=()
[ "$PROFONDITA" = 0 ] || profondita=(--depth "$PROFONDITA")
if ! git fetch -q --no-tags "${profondita[@]}" origin "$GITHUB_SHA"; then
echo "Il server non dà il commit per identificativo: prendo $GITHUB_REF con tutta la storia."
git fetch -q --no-tags origin "+$GITHUB_REF:refs/remotes/origin/lavoro"
fi
git checkout -q --force --detach "$GITHUB_SHA"
git log -1 --format='Commit %h: %s'
- name: Script, flussi, conflitti, versione, soluzione e JSON
run: bash .gitea/scripts/controlli.sh
@@ -69,33 +97,60 @@ jobs:
- name: Segreti in tutta la storia (gitleaks)
run: bash .gitea/scripts/segreti.sh out/sicurezza
- name: Rapporto di gitleaks (segreti oscurati)
- name: Rapporto di gitleaks (segreti oscurati, pacchetto febe-ci)
if: failure()
uses: actions/upload-artifact@v3
with:
name: rapporto-gitleaks
path: out/sicurezza/gitleaks.json
retention-days: 14
if-no-files-found: ignore
env:
REGISTRY_TOKEN: ${{ secrets.REGISTRY_TOKEN }}
GITEA_URL: ${{ gitea.server_url }}
PROPRIETARIO: ${{ gitea.repository_owner }}
run: |
[ -f out/sicurezza/gitleaks.json ] || { echo "Nessun rapporto di gitleaks."; exit 0; }
bash .gitea/scripts/artefatti.sh verifica out/sicurezza/gitleaks.json
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.
# Debian 13, nient'altro: Chromium vero della distribuzione, come nell'immagine di Febe (su Ubuntu è uno snap). Senza
# azioni non serve Node: git e curl prima dei sorgenti, il resto da ambiente-prove.sh, l'SDK da dotnet.sh.
# Memoria condivisa più ampia dei 64 MB predefiniti: le prove dell'interfaccia usano un Chromium senza finestra.
container:
image: node:24-trixie
image: debian:trixie
options: --shm-size=1g
env:
FEBE_CHROMIUM: /usr/bin/chromium
SEME_RICHIESTO: ${{ gitea.event.inputs.seme }}
NUMERO: ${{ gitea.run_number }}
steps:
- uses: actions/checkout@v4
- name: Git e curl per i sorgenti
run: |
export DEBIAN_FRONTEND=noninteractive
apt-get update -qq
apt-get install -y -qq --no-install-recommends git curl ca-certificates > /dev/null
git --version
# Prima di tutto, così un seme chiesto a mano e sbagliato ferma subito il lavoro.
- name: Sorgenti
env:
TOKEN: ${{ gitea.token }}
SERVER: ${{ gitea.server_url }}
REPOSITORY: ${{ gitea.repository }}
PROFONDITA: "1"
run: |
git config --global --add safe.directory "$PWD"
git init -q .
git remote add origin "$SERVER/$REPOSITORY.git" 2> /dev/null || git remote set-url origin "$SERVER/$REPOSITORY.git"
GIT_CONFIG_VALUE_0="Authorization: basic $(printf 'x-access-token:%s' "$TOKEN" | base64 -w0)"
export GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0=http.extraHeader GIT_CONFIG_VALUE_0
profondita=()
[ "$PROFONDITA" = 0 ] || profondita=(--depth "$PROFONDITA")
if ! git fetch -q --no-tags "${profondita[@]}" origin "$GITHUB_SHA"; then
echo "Il server non dà il commit per identificativo: prendo $GITHUB_REF con tutta la storia."
git fetch -q --no-tags origin "+$GITHUB_REF:refs/remotes/origin/lavoro"
fi
git checkout -q --force --detach "$GITHUB_SHA"
git log -1 --format='Commit %h: %s'
# Prima di tutto il resto, così un seme chiesto a mano e sbagliato ferma subito il lavoro.
- name: Semi del mondo sintetico
id: semi
run: |
@@ -112,9 +167,8 @@ jobs:
- name: Chromium, Xvfb, ffmpeg e lingua italiana
run: bash .gitea/scripts/ambiente-prove.sh
- uses: actions/setup-dotnet@v4
with:
dotnet-version: "10.0.x"
- name: SDK .NET 10
run: bash .gitea/scripts/dotnet.sh 10.0
- name: Compilazione di tutta la soluzione (avvisi = errori)
run: dotnet build Febe.slnx -c Release -nologo -warnaserror
@@ -136,14 +190,17 @@ jobs:
if: ${{ !cancelled() }}
run: bash .gitea/scripts/riepilogo-prove.sh out/prove 0
- name: Risultati delle prove
- name: Risultati delle prove (pacchetto febe-ci)
if: ${{ !cancelled() }}
uses: actions/upload-artifact@v3
with:
name: risultati-prove
path: out/prove/*.trx
retention-days: 14
if-no-files-found: warn
env:
REGISTRY_TOKEN: ${{ secrets.REGISTRY_TOKEN }}
GITEA_URL: ${{ gitea.server_url }}
PROPRIETARIO: ${{ gitea.repository_owner }}
run: |
shopt -s nullglob
risultati=(out/prove/*.trx)
((${#risultati[@]} > 0)) || { echo "::warning::Nessun risultato delle prove da conservare."; exit 0; }
bash .gitea/scripts/artefatti.sh verifica "${risultati[@]}"
installatore:
needs: prove
@@ -152,11 +209,29 @@ jobs:
env:
NUMERO: ${{ gitea.run_number }}
steps:
- uses: actions/checkout@v4
- name: Sorgenti
env:
TOKEN: ${{ gitea.token }}
SERVER: ${{ gitea.server_url }}
REPOSITORY: ${{ gitea.repository }}
PROFONDITA: "1"
run: |
git config --global --add safe.directory "$PWD"
git init -q .
git remote add origin "$SERVER/$REPOSITORY.git" 2> /dev/null || git remote set-url origin "$SERVER/$REPOSITORY.git"
GIT_CONFIG_VALUE_0="Authorization: basic $(printf 'x-access-token:%s' "$TOKEN" | base64 -w0)"
export GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0=http.extraHeader GIT_CONFIG_VALUE_0
profondita=()
[ "$PROFONDITA" = 0 ] || profondita=(--depth "$PROFONDITA")
if ! git fetch -q --no-tags "${profondita[@]}" origin "$GITHUB_SHA"; then
echo "Il server non dà il commit per identificativo: prendo $GITHUB_REF con tutta la storia."
git fetch -q --no-tags origin "+$GITHUB_REF:refs/remotes/origin/lavoro"
fi
git checkout -q --force --detach "$GITHUB_SHA"
git log -1 --format='Commit %h: %s'
- uses: actions/setup-dotnet@v4
with:
dotnet-version: "10.0.x"
- name: SDK .NET 10
run: bash .gitea/scripts/dotnet.sh 10.0
- name: Febe.exe, programma di installazione e zip portabile (versione di prova)
run: |
@@ -164,15 +239,16 @@ jobs:
echo "Versione di questa esecuzione: $V-ci.$NUMERO"
bash installer/costruisci.sh "$V-ci.$NUMERO"
- name: Artefatti per Windows
uses: actions/upload-artifact@v3
with:
name: windows
path: |
out/Febe-Setup-*.exe
out/Febe-*-portabile.zip
retention-days: 14
if-no-files-found: error
- name: Artefatti per Windows (pacchetto febe-ci)
env:
REGISTRY_TOKEN: ${{ secrets.REGISTRY_TOKEN }}
GITEA_URL: ${{ gitea.server_url }}
PROPRIETARIO: ${{ gitea.repository_owner }}
run: |
shopt -s nullglob
artefatti=(out/Febe-Setup-*.exe out/Febe-*-portabile.zip)
((${#artefatti[@]} == 2)) || { echo "Servono il programma di installazione e lo zip portabile, non: ${artefatti[*]:-niente}." >&2; exit 1; }
bash .gitea/scripts/artefatti.sh verifica "${artefatti[@]}"
# Dopo l'installatore, non solo dopo le prove: :main e :sha- escono solo da un commit con tutta la verifica verde.
# Sull'unico runner i lavori vanno comunque uno alla volta, quindi la durata non cambia.
@@ -187,7 +263,26 @@ jobs:
BUILDER: febe-ci-${{ gitea.run_id }}
PROVA: febe-ci:${{ gitea.run_id }}
steps:
- uses: actions/checkout@v4
- name: Sorgenti
env:
TOKEN: ${{ gitea.token }}
SERVER: ${{ gitea.server_url }}
REPOSITORY: ${{ gitea.repository }}
PROFONDITA: "1"
run: |
git config --global --add safe.directory "$PWD"
git init -q .
git remote add origin "$SERVER/$REPOSITORY.git" 2> /dev/null || git remote set-url origin "$SERVER/$REPOSITORY.git"
GIT_CONFIG_VALUE_0="Authorization: basic $(printf 'x-access-token:%s' "$TOKEN" | base64 -w0)"
export GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0=http.extraHeader GIT_CONFIG_VALUE_0
profondita=()
[ "$PROFONDITA" = 0 ] || profondita=(--depth "$PROFONDITA")
if ! git fetch -q --no-tags "${profondita[@]}" origin "$GITHUB_SHA"; then
echo "Il server non dà il commit per identificativo: prendo $GITHUB_REF con tutta la storia."
git fetch -q --no-tags origin "+$GITHUB_REF:refs/remotes/origin/lavoro"
fi
git checkout -q --force --detach "$GITHUB_SHA"
git log -1 --format='Commit %h: %s'
# Ciò che un'esecuzione interrotta (annullata, scaduta) non ha potuto togliere, e un tentativo precedente di
# questa stessa esecuzione.
@@ -198,7 +293,6 @@ jobs:
# 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 }}
@@ -215,19 +309,11 @@ jobs:
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
run: bash .gitea/scripts/costruisci-immagine.sh builder "$REGISTRY"
- name: Costruzione dell'immagine (dentro girano compilazione e prove)
run: |
@@ -240,14 +326,15 @@ jobs:
- name: Vulnerabilità dell'immagine (Trivy)
run: bash .gitea/scripts/scansione-immagine.sh "$ARCHIVIO" out/sicurezza
- name: Rapporto di Trivy
- name: Rapporto di Trivy (pacchetto febe-ci)
if: ${{ !cancelled() }}
uses: actions/upload-artifact@v3
with:
name: sicurezza-immagine
path: out/sicurezza/trivy.json
retention-days: 14
if-no-files-found: ignore
env:
REGISTRY_TOKEN: ${{ secrets.REGISTRY_TOKEN }}
GITEA_URL: ${{ gitea.server_url }}
PROPRIETARIO: ${{ gitea.repository_owner }}
run: |
[ -f out/sicurezza/trivy.json ] || { echo "Nessun rapporto di Trivy."; exit 0; }
bash .gitea/scripts/artefatti.sh verifica out/sicurezza/trivy.json
- name: Pubblicare?
id: segreto
@@ -271,6 +358,7 @@ jobs:
env:
TOKEN: ${{ secrets.REGISTRY_TOKEN }}
UTENTE: ${{ gitea.actor }}
GITEA_TOKEN: ${{ gitea.token }}
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.
@@ -282,9 +370,12 @@ jobs:
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.
# Il passo gira con «bash -e -o pipefail»: senza «|| CIMA=""» un errore di ls-remote chiuderebbe il passo
# prima dell'avviso, e non uscirebbe nemmeno la :sha-.
CIMA=$(git ls-remote origin refs/heads/main 2> /dev/null | cut -f1) || CIMA=""
# Il gettone del lavoro solo nell'ambiente di git, come per i sorgenti. Il passo gira con «bash -e -o
# pipefail»: senza «|| CIMA=""» un errore di ls-remote chiuderebbe il passo prima dell'avviso, e non
# uscirebbe nemmeno la :sha-.
INTESTAZIONE="Authorization: basic $(printf 'x-access-token:%s' "$GITEA_TOKEN" | base64 -w0)"
CIMA=$(GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0=http.extraHeader GIT_CONFIG_VALUE_0="$INTESTAZIONE" \
git ls-remote origin refs/heads/main 2> /dev/null | cut -f1) || CIMA=""
if [ "$CIMA" = "$GITHUB_SHA" ]; then
NOMI+=("$IMAGE:main")
elif [ -z "$CIMA" ]; then
+7
View File
@@ -424,3 +424,10 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15).
| 2026-11-18 | Le 70 icone sono disegnate per Febe: un SVG per icona in `wwwroot/icone`, griglia di 24, solo tratti (linee, cerchi, rettangoli, poligoni, archi semplici), spessore 1,75 dal foglio di stile; stessi nomi e stesso significato di prima, così `icon('nome')` non cambia; tolte le icone Lucide e la loro licenza | Stessa decisione; i nomi restano identificativi interni. Una prova fallisce se nei file del programma ricompare un riferimento al carattere o alle icone di prima |
| 2026-11-18 | Il programma di installazione per Windows è nostro: `src/Febe.Installer`, un programma .NET pubblicato per win-x64 autosufficiente, in un file solo, ridotto con il trimming e compresso, a cui lo stesso progetto (compilato per il sistema che costruisce: `--impacchetta`, `--verifica`, `--zip`) appende `Febe.exe` compresso con Brotli (qualità 5, finestra di 16 MB), la versione e un piè di pagina di 80 byte con lunghezze e SHA-256. Fa ciò che faceva lo script di prima: per utente in `%LOCALAPPDATA%\Programs\Febe`, collegamenti con l'oggetto ShellLink di Windows (interop COM generata da .NET), voce in App installate sotto HKCU, controllo di WebView2, rifiuto con Febe aperto, disinstallazione che non tocca dati né libreria; pagine con la finestra di dialogo delle attività di Windows (TaskDialog); `/S`, `/D=` e, per le prove, `/PROVA=`. Tolti `installer/febe.nsi`, NSIS e `zip` dalla CI e dai documenti; lo zip portabile lo scrive `ZipArchive` | Decisione di Alberto del 18 novembre 2026: niente componenti esterni. Il trimming e il pacchetto del runtime vengono dallo SDK di .NET (come i runtime per win-x64 che `Febe.exe` già usa), non sono codice di terzi; senza trimming il programma con il suo runtime supererebbe con `Febe.exe` i 100 MB degli allegati di Gitea (oggi 91,4 MB in tutto). Brotli 5 invece di 11: 80,8 MB invece di 79,7, in 3 secondi invece di 6 minuti |
| 2026-11-18 | La disinstallazione si copia in `%TEMP%` (`Febe-disinstalla-<processo>.exe`), avvia la copia con la cartella del programma e il proprio numero di processo e finisce; la copia aspetta che finisca, fa il lavoro e resta in `%TEMP%` finché un avvio successivo dell'installazione o della disinstallazione non la toglie | Un eseguibile in esecuzione non può cancellare il proprio file; senza permessi di amministratore Windows non cancella un file al riavvio. `/S` della disinstallazione esce quindi subito con 0 |
| 2026-11-18 | I flussi della CI sono fatti solo di comandi: nessun `uses:` (né `actions/checkout`, `setup-dotnet`, `upload-artifact`, `download-artifact`, né `docker/setup-buildx-action`) e nessun Node, né nei lavori né negli script; `controlli.sh` rifiuta un flusso con `uses:` e `PipelineTests` un comando `node`, `npm` o `npx` | Decisione di Alberto del 18 novembre 2026: niente componenti esterni. Le azioni sono programmi JavaScript di terzi che vogliono Node. Restano gli unici strumenti esterni approvati, gitleaks e Trivy, scaricati e verificati da `strumento.sh` come prima |
| 2026-11-18 | Sorgenti: in ogni lavoro lo stesso passo «Sorgenti», `git init`, `git fetch` del commit (`GITHUB_SHA`; se Gitea non lo dà per identificativo, il riferimento `GITHUB_REF` con tutta la storia) e `checkout --detach`, con il gettone del lavoro (`gitea.token`) in un'intestazione `Authorization: basic` passata a git solo con `GIT_CONFIG_COUNT`/`KEY_0`/`VALUE_0` nell'ambiente del passo; tutta la storia in `controlli`, profondità 1 altrove. Allo stesso modo `git ls-remote` della cima di `main` prima di pubblicare `:main` | Il gettone non finisce in `.git/config` né nel registro del lavoro (`PipelineTests` controlla che non vada in `echo`/`printf`); gitleaks ha bisogno di tutta la storia, come con `fetch-depth: 0` |
| 2026-11-18 | SDK .NET: `.gitea/scripts/dotnet.sh <canale>` prende da `builds.dotnet.microsoft.com/dotnet/release-metadata/<canale>/releases.json` l'ultimo SDK (`latest-sdk`), ne scarica l'archivio per `linux-x64` o `linux-arm64` solo dagli host di Microsoft e lo installa solo se l'SHA-512 coincide con quello dei metadati; lo tiene in `RUNNER_TOOL_CACHE/febe-dotnet/<versione>` (il volume `act-toolcache`) e toglie le versioni precedenti | Lo stesso di `setup-dotnet` con `10.0.x`, ma verificato; mai uno script di installazione scaricato al volo. La scelta la fa `dotnet-sdk.awk`, provato su metadati scritti nella prova |
| 2026-11-18 | Builder buildx: `costruisci-immagine.sh builder <registro>` scrive la configurazione di BuildKit (`[registry."<registro>"]` con `http` e `insecure`), crea il builder `febe-ci-<esecuzione>` con il driver `docker-container` (`--buildkitd-config`, o `--config` per un buildx più vecchio di 0.13) e lo avvia | Ciò che faceva `docker/setup-buildx-action`; la pulizia lo toglie per nome come prima |
| 2026-11-18 | Artefatti della CI nel registro dei pacchetti di Gitea, pacchetto generico `febe-ci`, una versione per esecuzione (`<versione>-ci.<numero>` dalla verifica, `<versione>-rilascio.<numero>` dal rilascio), con `.gitea/scripts/artefatti.sh` e `REGISTRY_TOKEN` (PUT su `/api/packages/<proprietario>/generic/febe-ci/<versione>/<file>`; un file già caricato da un tentativo precedente si toglie e si ricarica). Senza il segreto un avviso e nessun artefatto. La pulizia del lunedì toglie le versioni di quella forma create più di 14 giorni prima (`versioni-registro.sh scadute 14`). Il lavoro `release` ricostruisce `Febe.exe`, installatore e zip invece di riceverli dal lavoro `windows` | I 14 giorni di `retention-days` di prima. Senza azioni non c'è un deposito di artefatti fra i lavori: il registro dei pacchetti è di Gitea, già usato per l'immagine. Ricostruire nella release costa qualche minuto a ogni tag, ma non la fa dipendere dal segreto |
| 2026-11-18 | JSON nella CI letto con `.gitea/scripts/json.awk`, un lettore in awk POSIX con funzioni di richiamo (`json-valido.awk` per il controllo di ogni file JSON del repository, `versioni-registro.awk` per la scelta delle versioni del registro); tolti `versioni-registro.js` e il controllo `node --check`. Prende il posto del motivo «Node e non jq» della riga del 21 ottobre sul registro e della riga sul controllo degli script Node | Niente Node nella CI. awk c'è nell'immagine dei lavori, in Debian e in Git Bash; il lettore dà gli stessi esiti di `JSON.parse` sui casi difficili provati (gawk normale e `--posix`) e sui 46 file JSON del repository, e la scelta delle versioni coincide con quella dello script Node sul file di prova |
| 2026-11-18 | Lavoro «prove» nel contenitore `debian:trixie` invece di `node:24-trixie`: git, curl e certificati nel primo passo, il resto da `ambiente-prove.sh` (anche le librerie di sistema dell'SDK), che si ferma se nel contenitore c'è `node`. La prova della pagina di accesso (`return-path.js`) gira in Chromium con il protocollo DevTools, come le altre prove dell'interfaccia, invece che in Node | Prende il posto della riga del 20 ottobre sul contenitore: le azioni, che volevano Node lì dentro, non ci sono più. Chromium è già fra ciò che Febe usa, ed è il motore che esegue davvero quel modulo |
+6 -3
View File
@@ -192,14 +192,17 @@ da sole). Vedi [Installazione con Docker e Unraid](Installazione-Docker-e-Unraid
Il repository è sul Gitea di casa (<https://gitea.encke-hake.ts.net/Alby96/Febe>); la CI usa Gitea Actions in
`.gitea/workflows/`, con il codice comune in `.gitea/scripts/`. Il processo completo (nomi dei rami, commit,
richieste di unione, protezione di `main`, rilievi di sicurezza, rilasci, correzioni urgenti) è in `docs/processo.md`.
I flussi sono fatti solo di comandi: nessuna azione (`uses:`) e niente Node; i sorgenti si prendono con git, l'SDK
.NET con `.gitea/scripts/dotnet.sh` e gli artefatti vanno nel pacchetto generico `febe-ci` del registro di Gitea
(proprietario ▸ Pacchetti), con il segreto `REGISTRY_TOKEN`.
- `verifica.yml`, a ogni push su qualunque ramo e a mano (non sui tag, non sulle richieste di unione, che mostrano lo
stato del loro ultimo commit). Quattro lavori, che sono i controlli richiesti per unire in `main`:
- `controlli`: sintassi degli script, file di testo, versione, progetti della soluzione, JSON, e nessun segreto in
tutta la storia (gitleaks);
- `prove`: compilazione di tutta la soluzione con gli avvisi come errori e tutte le prove di `tests/Febe.Tests` in
un contenitore Debian con Chromium, Xvfb, ffmpeg e Node veri: nessuna prova si salta;
- `installatore`: `Febe-Setup-<versione>-ci.<numero>.exe` e lo zip portabile, fra gli artefatti per 14 giorni;
un contenitore Debian con Chromium, Xvfb e ffmpeg veri, senza Node: nessuna prova si salta;
- `installatore`: `Febe-Setup-<versione>-ci.<numero>.exe` e lo zip portabile, nel pacchetto `febe-ci` per 14 giorni;
- `immagine`, dopo l'installatore: l'immagine Docker, provata senza rete (parte, diventa «healthy», si ferma) e
scansionata con Trivy; dopo un push su `main` va sul registro come `:main` e `:sha-<commit>`. Alla fine si toglie
tutto ciò che l'esecuzione ha creato sul demone Docker, che è condiviso con gli altri progetti, e poi, di tutti, le
@@ -208,7 +211,7 @@ richieste di unione, protezione di `main`, rilievi di sicurezza, rilasci, correz
`:X.Y.Z` e `:latest` (solo per le versioni senza trattino), poi la release;
- `pulizia.yml`, ogni lunedì e a mano: i resti delle esecuzioni interrotte e dei lavori di act_runner, le immagini che
nessun contenitore usa e la cache di costruzione più vecchie di 24 ore, di tutti i progetti, e sul registro le
`:sha-` oltre le 10 più recenti; mai un contenitore, un volume o una rete che non sia della CI. A mano, con «Solo
`:sha-` oltre le 10 più recenti e gli artefatti di `febe-ci` di più di 14 giorni; mai un contenitore, un volume o una rete che non sia della CI. A mano, con «Solo
prova», elenca che cosa toglierebbe e non toglie nulla (`docs/processo.md`, «Pulizia»).
Nella CI le prove del sito di prova (categoria `SitoDiProva`) girano due volte: con il seme 13 e con un seme diverso
+45 -14
View File
@@ -84,11 +84,29 @@ Gitea Actions su un solo act_runner (etichetta `ubuntu-latest`, un lavoro alla v
Docker del server, lo stesso che costruisce Encelado, Mimante e gli altri progetti di Alberto. I flussi stanno in
`.gitea/workflows/`, il codice comune in `.gitea/scripts/` (si lancia anche a mano).
Dal 18 novembre 2026 i flussi sono fatti **solo di comandi**: nessuna azione (`uses:`), perché quelle di GitHub e di
Gitea sono programmi JavaScript che vogliono Node, e nella CI di Febe non gira Node in nessuna forma (decisione di
Alberto, nessun componente esterno). Al posto delle azioni:
| Prima | Ora |
|---|---|
| `actions/checkout` | il passo «Sorgenti», uguale lettera per lettera in ogni lavoro: `git init` e `git fetch` del commit con il gettone del lavoro (`gitea.token`), passato a git solo nell'ambiente di quel passo (`GIT_CONFIG_*`), mai scritto nella configurazione del repository; tutta la storia in `controlli` (gitleaks), un solo commit altrove |
| `actions/setup-dotnet` | `.gitea/scripts/dotnet.sh 10.0`: l'ultimo SDK del canale dai metadati dei rilasci di Microsoft, scaricato da `builds.dotnet.microsoft.com` e installato solo se l'impronta SHA-512 coincide con quella dei metadati; resta nella cache degli strumenti del runner (`act-toolcache`) e non si riscarica finché non esce un SDK nuovo |
| `docker/setup-buildx-action` | `costruisci-immagine.sh builder <registro>`: `docker buildx create` con il driver `docker-container` e il registro di casa in HTTP |
| `actions/upload-artifact` | `.gitea/scripts/artefatti.sh`: i file vanno nel registro dei pacchetti di Gitea, pacchetto generico `febe-ci`, una versione per esecuzione (`<versione>-ci.<numero>` dalla verifica, `<versione>-rilascio.<numero>` dal rilascio), con `REGISTRY_TOKEN`; si scaricano da proprietario ▸ Pacchetti ▸ `febe-ci`, e la pulizia del lunedì toglie quelle di più di 14 giorni |
| `actions/download-artifact` (rilascio) | nessun passaggio di file fra lavori: il lavoro `release` ricostruisce `Febe.exe`, installatore e zip dallo stesso commit |
| Node per i JSON (`controlli`, pulizia del registro) | `.gitea/scripts/json.awk`, un lettore JSON in awk POSIX (con `json-valido.awk` per i controlli, `versioni-registro.awk` per il registro) |
Il contenitore del lavoro `prove` è `debian:trixie` (prima `node:24-trixie`): git e curl si installano nel primo passo,
tutto il resto da `ambiente-prove.sh`, che si ferma se trova `node`. La regola della pagina di accesso
(`return-path.js`) si prova in Chromium, come tutte le prove dell'interfaccia. `PipelineTests` controlla che nessun
flusso usi `uses:` e che nessuno script chiami `node`, `npm` o `npx`.
| Lavoro | Quando | Che cosa garantisce |
|---|---|---|
| `controlli` | ogni push | sintassi di tutti gli script di shell (`bash -n`, `sh -n`) e righe Unix; flussi senza tabulazioni; nessun segno di conflitto; versione in `Directory.Build.props` valida; ogni progetto di `Febe.slnx` esiste; ogni JSON si legge; nessun segreto in tutta la storia (gitleaks 8.30.1, `--redact`) |
| `prove` | dopo `controlli` | in un contenitore Debian 13 (`node:24-trixie`) con Chromium della distribuzione, Xvfb, ffmpeg, Node e la lingua italiana: tutta la soluzione compila con gli avvisi come errori e **tutte** le prove di `tests/Febe.Tests` passano senza saltarsi; quelle della categoria `SitoDiProva` passano anche con il seme dell'esecuzione. Risultati `.trx` fra gli artefatti (14 giorni) |
| `installatore` | dopo `prove` | `Febe.exe` in un file solo, `Febe-Setup-<versione>-ci.<numero>.exe` e lo zip portabile si costruiscono, ciascuno sotto i 100 MB; artefatti per 14 giorni |
| `controlli` | ogni push | sintassi di tutti gli script di shell (`bash -n`, `sh -n`) e righe Unix, anche dei programmi awk; flussi senza tabulazioni né righe Windows, con i rientri di due spazi, `on:` e `jobs:`, e senza `uses:`; nessun segno di conflitto; versione in `Directory.Build.props` valida; ogni progetto di `Febe.slnx` esiste; ogni JSON si legge (`json.awk`); nessun segreto in tutta la storia (gitleaks 8.30.1, `--redact`; il rapporto, se trova qualcosa, nel pacchetto `febe-ci`) |
| `prove` | dopo `controlli` | in un contenitore Debian 13 (`debian:trixie`) con Chromium della distribuzione, Xvfb, ffmpeg e la lingua italiana, senza Node, e l'SDK di `dotnet.sh`: tutta la soluzione compila con gli avvisi come errori e **tutte** le prove di `tests/Febe.Tests` passano senza saltarsi; quelle della categoria `SitoDiProva` passano anche con il seme dell'esecuzione. Risultati `.trx` nel pacchetto `febe-ci` (14 giorni, con `REGISTRY_TOKEN`) |
| `installatore` | dopo `prove` | `Febe.exe` in un file solo, `Febe-Setup-<versione>-ci.<numero>.exe` e lo zip portabile si costruiscono, ciascuno sotto i 100 MB; installatore e zip nel pacchetto `febe-ci` per 14 giorni |
| `immagine` | dopo `installatore` (così `:main` e `:sha-` escono solo da un commit con tutta la verifica verde) | l'immagine si costruisce con buildx (dentro girano compilazione e prove), il contenitore parte **senza rete** come dice la guida e diventa «healthy», Chromium e la lingua italiana ci sono, si ferma entro 30 secondi; Trivy 0.75.0 non trova vulnerabilità CRITICAL con correzione disponibile. Solo dopo un push su `main`: pubblicazione `:main` e `:sha-<commit>` |
La verifica gira a ogni push su qualunque ramo e a mano (Actions ▸ verifica ▸ Esegui, con un seme facoltativo). Su un
@@ -114,7 +132,11 @@ FEBE_SEME_PROVA=<seme> dotnet test tests/Febe.Tests --filter "TestCategory=SitoD
### Segreti e variabili
- `REGISTRY_TOKEN` (segreto del repository): token di Alberto con «package: read and write». Senza, `verifica` e
`rilascio` costruiscono, provano e scansionano l'immagine ma non la pubblicano, con un avviso, e restano verdi.
`rilascio` costruiscono, provano e scansionano l'immagine ma non la pubblicano, con un avviso, e restano verdi. Lo
stesso token carica gli artefatti nel pacchetto `febe-ci`: senza, un avviso per ogni passo che li caricherebbe, e
nessun artefatto (il lavoro resta verde).
- `gitea.token` (il gettone del lavoro, di Gitea): solo per leggere i sorgenti e la cima di `main`, nell'ambiente di git
e mai su disco.
- `REGISTRY` (variabile, facoltativa): il registro come lo raggiunge il runner (`192.168.30.23:3000`); se manca si usa
l'host dell'indirizzo del server Gitea.
- Le credenziali vanno nella configurazione del client Docker del lavoro, mai nel demone, e si tolgono alla fine.
@@ -186,12 +208,12 @@ quell'immagine ha più nomi, `image prune -a` le toglie quelli in più (vedi «C
|---|---|
| alla fine di ogni lavoro «immagine» (verifica e rilascio), sempre | il contenitore di prova con i suoi volumi anonimi, l'immagine provata, il builder buildx dell'esecuzione con la sua cache, l'archivio dell'immagine, le credenziali del registro; poi, di tutti i progetti, le immagini senza nome che nessun contenitore usa e la cache di costruzione penzolante del demone, cioè quella che nessuna immagine condivide, non usata da 24 ore (`pulizia-docker.sh penzolanti`). Un errore qui è solo un avviso: il lavoro non diventa rosso |
| all'inizio di ogni lavoro «immagine» | i resti di esecuzioni interrotte più vecchi di 90 minuti (un lavoro dura al massimo 60 minuti): contenitori di prova **fermi**, immagini `febe-ci:`, builder; e ciò che ha lasciato un tentativo precedente della stessa esecuzione |
| ogni lunedì alle 4:17 e a mano (`pulizia.yml`, `pulizia-docker.sh completa`) | gli stessi resti e l'immagine `febe:ci` del vecchio flusso; i resti di act_runner; **le immagini che nessun contenitore usa create più di 24 ore fa**, di tutti i progetti, anche col nome del registro; la cache di costruzione del demone non usata da più di 24 ore; con il segreto `REGISTRY_TOKEN`, sul registro le `:sha-` oltre le 10 più recenti. Prima e dopo `docker system df`, alla fine un riepilogo di che cosa è andato via |
| mai | `docker system prune`, `container prune`, `volume prune`, `network prune`; un contenitore, un volume o una rete che non sia della CI: un Febe vero, anche se porta le etichette `febe.ci.*`, le applicazioni di Unraid, i volumi con i dati, `act-toolcache`; un contenitore di prova ancora acceso di un'altra esecuzione (si segnala con un avviso e il comando per toglierlo: il flusso del lunedì diventa rosso); un'immagine usata da un contenitore, anche fermo (i suoi nomi in più sì: vedi sotto); `image prune -a` e `builder prune -a` senza il filtro delle 24 ore; sul registro `:main`, `:latest` e le versioni `X.Y.Z` |
| ogni lunedì alle 4:17 e a mano (`pulizia.yml`, `pulizia-docker.sh completa`) | gli stessi resti e l'immagine `febe:ci` del vecchio flusso; i resti di act_runner; **le immagini che nessun contenitore usa create più di 24 ore fa**, di tutti i progetti, anche col nome del registro; la cache di costruzione del demone non usata da più di 24 ore; con il segreto `REGISTRY_TOKEN`, sul registro le `:sha-` oltre le 10 più recenti e, del pacchetto generico `febe-ci`, le versioni `<x.y.z>-ci.<n>` e `<x.y.z>-rilascio.<n>` create più di 14 giorni prima (gli artefatti scaduti). Prima e dopo `docker system df`, alla fine un riepilogo di che cosa è andato via |
| mai | `docker system prune`, `container prune`, `volume prune`, `network prune`; un contenitore, un volume o una rete che non sia della CI: un Febe vero, anche se porta le etichette `febe.ci.*`, le applicazioni di Unraid, i volumi con i dati, `act-toolcache`; un contenitore di prova ancora acceso di un'altra esecuzione (si segnala con un avviso e il comando per toglierlo: il flusso del lunedì diventa rosso); un'immagine usata da un contenitore, anche fermo (i suoi nomi in più sì: vedi sotto); `image prune -a` e `builder prune -a` senza il filtro delle 24 ore; sul registro `:main`, `:latest` e le versioni `X.Y.Z`, e ogni pacchetto che non sia `febe` o `febe-ci`; in `febe-ci` una versione di un'altra forma o senza una data leggibile con il fuso |
Che cosa costa:
- le immagini di base che fra un lavoro e l'altro nessun contenitore usa (`node:24-trixie` del lavoro «prove»,
- le immagini di base che fra un lavoro e l'altro nessun contenitore usa (`debian:trixie` del lavoro «prove»,
`moby/buildkit` dei builder, quelle dei lavori degli altri progetti) si riscaricano alla prima esecuzione che le
chiede dopo il lunedì: qualche minuto e qualche centinaio di MB in più, una volta. L'immagine dei lavori
(`ubuntu-latest`) resta, perché durante la pulizia la usa il lavoro stesso;
@@ -220,7 +242,7 @@ Che cosa costa:
**Prova senza togliere nulla.** Actions ▸ pulizia ▸ Esegui, con «Solo prova» spuntato: il registro del lavoro elenca
che cosa toglierebbe (le immagini con dimensione ed età, i nomi in più delle immagini in uso, la cache di costruzione, i
resti della CI di Febe e di act_runner, le `:sha-` del registro) e non toglie nulla: solo comandi che leggono, e sul
resti della CI di Febe e di act_runner, le `:sha-` e gli artefatti scaduti del registro) e non toglie nulla: solo comandi che leggono, e sul
registro solo GET. Si lancia prima della prima pulizia vera e dopo ogni cambio dello script. Dal server, nella cartella
del repository:
`bash .gitea/scripts/pulizia-docker.sh completa --prova` (il registro solo con `REGISTRY_TOKEN`, `GITEA_API` e
@@ -243,14 +265,14 @@ lavoro.
Gitea dalle impostazioni dell'utente) e se ne crea uno nuovo: toglierlo dalla storia non basta, perché qualcuno può
averlo già. Solo dopo, se serve, si riscrive la storia, d'accordo con Alberto. Un falso allarme (un dato di prova
finto, già controllato) si toglie aggiungendo la sua impronta («Fingerprint», nel registro del lavoro o nel
rapporto `rapporto-gitleaks`) a `.gitleaksignore`, con un commento sulla riga sopra: che cos'è, chi l'ha
rapporto `gitleaks.json` del pacchetto `febe-ci`) a `.gitleaksignore`, con un commento sulla riga sopra: che cos'è, chi l'ha
controllato, quando. Mai disattivare una regola.
- **Trivy** (lavoro `immagine`, anche nel rilascio). Una vulnerabilità CRITICAL con correzione disponibile ferma il
lavoro e l'immagine non si pubblica. Che cosa fare: per un pacchetto di Debian di solito basta rilanciare (il
Dockerfile applica gli aggiornamenti della distribuzione); per una dipendenza .NET si aggiorna la sua versione in
`Directory.Packages.props` (una dipendenza nuova va chiesta ad Alberto); per il runtime .NET si ricostruisce con
l'SDK aggiornato. Le HIGH, e le CRITICAL ancora senza correzione, non fermano nulla ma si guardano nel rapporto
`sicurezza-immagine` (`trivy.json`) e, se riguardano ciò che Febe usa, diventano una segnalazione. Un'eccezione si
`trivy.json` del pacchetto `febe-ci` e, se riguardano ciò che Febe usa, diventano una segnalazione. Un'eccezione si
scrive solo in `.trivyignore`, alla radice: l'identificativo con una scadenza (`CVE-AAAA-NNNN exp:AAAA-MM-GG`, al
massimo 90 giorni) e, sulla riga sopra, il motivo e chi l'ha deciso.
- Strumenti: gitleaks e Trivy sono gli unici strumenti esterni della CI, approvati da Alberto, e girano solo nella
@@ -282,10 +304,19 @@ lavoro.
Qui non ci sono runner né demone Docker: i flussi sono stati controllati come testo (struttura, espressioni, `bash -n`
di ogni blocco `run`), gli script con un client Docker finto. Restano da vedere alla prima esecuzione: il contenitore
`node:24-trixie` con le azioni dentro; le prove con il browser nel contenitore (nessuna saltata); `upload-artifact@v3`
con `retention-days`; la concorrenza; il builder buildx con il nome dell'esecuzione; la prova del contenitore senza
rete fino a «healthy»; il download e la scansione di Trivy (e se trova CRITICAL da correggere); gitleaks sulla storia;
la pubblicazione su `main` con il segreto.
`debian:trixie` con git e curl installati nel primo passo; le prove con il browser nel contenitore (nessuna saltata); la
concorrenza; il builder buildx con il nome dell'esecuzione; la prova del contenitore senza rete fino a «healthy»; il
download e la scansione di Trivy (e se trova CRITICAL da correggere); gitleaks sulla storia; la pubblicazione su `main`
con il segreto.
Della CI senza azioni del 18 novembre 2026 (script provati con file di prova e un curl finto, mai contro la rete)
restano da vedere: che Gitea accetti il gettone del lavoro come password di base per `git fetch` e dia il commit per
identificativo (se no, il passo «Sorgenti» lo dice e prende il ramo con tutta la storia); che act_runner monti
`act-toolcache` anche nel contenitore delle prove (`RUNNER_TOOL_CACHE`; senza, l'SDK si riscarica a ogni lavoro);
il formato vero di `releases.json` di Microsoft per `dotnet-sdk.awk` (provato solo su metadati scritti nella prova);
`docker buildx create` con `--buildkitd-config` sul client Docker del runner; il caricamento nel pacchetto generico
`febe-ci` (PUT con risposta 201, 409 per un file già caricato) e la sua pulizia dopo 14 giorni; `mawk` (le prove e i
controlli locali usano gawk, anche in modo `--posix`).
Della pulizia del 21 ottobre 2026 (script e API provati con un client Docker e un curl finti) restano da vedere: la
casella «Solo prova» di Gitea che arriva al lavoro come «true»; i nomi che questo act_runner dà ai suoi contenitori,
+8 -3
View File
@@ -148,11 +148,16 @@ public sealed partial class PackagingTests
// The registry at home answers in HTTP: buildx with its own builder, told so, and no «docker login». The push is
// the same build as the tested one (.gitea/scripts/costruisci-immagine.sh, shared with the verification).
StringAssert.Contains(image, "uses: docker/setup-buildx-action@v3");
StringAssert.Contains(image, "http = true");
StringAssert.Contains(image, "insecure = true");
StringAssert.Contains(image, "bash .gitea/scripts/costruisci-immagine.sh builder \"$REGISTRY\"");
StringAssert.Contains(Step(image, "Pubblicazione sul registro di Gitea"), "bash .gitea/scripts/costruisci-immagine.sh pubblica");
var build = File.ReadAllText(Repository.PathOf(".gitea", "scripts", "costruisci-immagine.sh"));
StringAssert.Contains(build, "http = true");
StringAssert.Contains(build, "insecure = true");
// No artifact goes from one job to the next (that would take an action): the release builds Febe.exe, the
// installer and the zip again from the same commit, as the windows job did before it.
StringAssert.Contains(release, "bash installer/costruisci.sh \"${GITHUB_REF_NAME#v}\"");
StringAssert.Contains(release, "bash .gitea/scripts/dotnet.sh 10.0");
StringAssert.Contains(build, "docker buildx build \"${comuni[@]}\" \"${etichette[@]}\" --push .");
foreach (var text in new[] { image, build })
{
@@ -0,0 +1,332 @@
using System.Text.RegularExpressions;
using Febe.Tests.Desktop.Support;
using Febe.Tests.Support;
namespace Febe.Tests.Packaging;
/// <summary>
/// The CI is made only of commands (decision of 18 November 2026): no action (the JavaScript ones want Node) and no
/// Node anywhere. Every job fetches its sources with git and the token of the job, installs the .NET SDK with
/// .gitea/scripts/dotnet.sh (checked against Microsoft's SHA-512) before any dotnet, and keeps its artifacts in the
/// generic package febe-ci; the quick checks read the workflows and the JSON files with awk. The scripts run here against
/// files of the test and a fake curl, never against the network.
/// </summary>
public sealed partial class PipelineTests
{
private static readonly string[] Workflows = ["verifica.yml", "rilascio.yml", "pulizia.yml"];
[TestMethod]
public void NoActionAndNoNodeRunInTheCi()
{
foreach (var name in Workflows)
{
var code = Code(Workflow(name));
Assert.IsFalse(UsesLine().IsMatch(code), $"{name}: «uses:» calls an action; the CI is made of commands");
Assert.IsFalse(Regex.IsMatch(code, @"image:\s*node\b"), $"{name}: no container with Node");
}
foreach (var (name, text) in AllCiFiles())
{
foreach (var line in Code(text).Split('\n'))
{
Assert.IsFalse(NodeCommand().IsMatch(line) && !line.Contains("command -v node", StringComparison.Ordinal), $"{name}: «{line.Trim()}» runs Node");
}
}
foreach (var file in Directory.EnumerateFiles(CiPath(), "*", SearchOption.AllDirectories))
{
Assert.IsFalse(Regex.IsMatch(file, @"\.(?:js|mjs|cjs|ts)$"), $"{file}: no JavaScript in the CI");
}
// The container of the tests has no Node, and says so if an image ever brings it.
StringAssert.Contains(Script("ambiente-prove.sh"), "if command -v node > /dev/null; then");
}
[TestMethod]
public void EveryJobFetchesItsSourcesWithGitAndTheTokenOfTheJob()
{
var model = Normalized(Step(Job(Workflow("verifica.yml"), "controlli"), "Sorgenti"));
StringAssert.Contains(model, "TOKEN: ${{ gitea.token }}");
StringAssert.Contains(model, "export GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0=http.extraHeader GIT_CONFIG_VALUE_0");
StringAssert.Contains(model, "git checkout -q --force --detach \"$GITHUB_SHA\"");
// The token lives only in the environment of git for that step: never in a configuration file of the repository.
Assert.DoesNotContain("credential", model);
Assert.IsFalse(Regex.IsMatch(model, @"git config[^\n]*(?:extraheader|http\.)", RegexOptions.IgnoreCase), "the header is never written to .git/config");
foreach (var name in Workflows)
{
var text = Workflow(name);
foreach (Match header in JobHeader().Matches(text))
{
var job = Job(text, header.Groups["name"].Value);
var steps = StepName().Matches(job).Select(m => m.Groups["name"].Value).ToList();
var where = $"{name}: {header.Groups["name"].Value}";
// First, or right after the step that brings git into the bare Debian container of the tests.
var first = steps.FirstOrDefault() == "Git e curl per i sorgenti" ? 1 : 0;
Assert.IsGreaterThan(first, steps.Count, where);
Assert.AreEqual("Sorgenti", steps[first], $"{where}: the sources come first");
Assert.AreEqual(model, Normalized(Step(job, "Sorgenti")), $"{where}: the same step as everywhere else");
}
}
static string Normalized(string step) => Regex.Replace(Code(step).TrimEnd(), "PROFONDITA: \"[0-9]+\"", "PROFONDITA: …");
}
[TestMethod]
public void TheSdkIsInstalledAndCheckedBeforeAnyDotnet()
{
foreach (var name in Workflows)
{
var text = Workflow(name);
foreach (Match header in JobHeader().Matches(text))
{
var job = Code(Job(text, header.Groups["name"].Value));
var use = DotnetUse().Match(job);
if (!use.Success)
{
continue;
}
var install = job.IndexOf("bash .gitea/scripts/dotnet.sh 10.0", StringComparison.Ordinal);
Assert.IsTrue(install >= 0 && install < use.Index, $"{name}: {header.Groups["name"].Value} uses «{use.Value}» before dotnet.sh");
}
}
var installer = Code(Script("dotnet.sh"));
StringAssert.Contains(installer, "https://builds.dotnet.microsoft.com/dotnet/release-metadata/$canale/releases.json");
StringAssert.Contains(installer, "sha512sum -c");
StringAssert.Contains(installer, "-f \"$qui/json.awk\" -f \"$qui/dotnet-sdk.awk\"");
Assert.DoesNotContain("dotnet-install", installer, "no installation script fetched on the fly");
}
[TestMethod]
[Timeout(120_000, CooperativeCancellation = true)]
public async Task TheSdkComesOnlyFromMicrosoftWithTheHashOfItsMetadata()
{
var bash = RequireBash();
CiPath("scripts", "dotnet-sdk.awk");
using var folder = new TempFolder("febe-sdk");
var hash = string.Concat(Enumerable.Repeat("AB", 64));
var other = new string('c', 128);
const string sdk = "https://builds.dotnet.microsoft.com/dotnet/Sdk";
// The metadata of a channel as Microsoft writes them: latest-sdk at the root, the files of each SDK with url and
// hash. Another rid, a zip, an older SDK and a copy on another host are there too.
string Metadata(string latest, string host, string digest) => $$$"""
{"channel-version": "10.0", "latest-release": "10.0.5", "latest-sdk": "{{{latest}}}", "releases": [
{"release-version": "10.0.5", "sdk": {"version": "10.0.201", "files": [
{"name": "dotnet-sdk-linux-arm64.tar.gz", "rid": "linux-arm64", "url": "{{{sdk}}}/10.0.201/dotnet-sdk-10.0.201-linux-arm64.tar.gz", "hash": "{{{other}}}"},
{"name": "dotnet-sdk-linux-x64.tar.gz", "rid": "linux-x64", "url": "{{{host}}}/10.0.201/dotnet-sdk-10.0.201-linux-x64.tar.gz", "hash": "{{{digest}}}"},
{"name": "dotnet-sdk-linux-x64.zip", "rid": "linux-x64", "url": "{{{sdk}}}/10.0.201/dotnet-sdk-10.0.201-linux-x64.zip", "hash": "{{{other}}}"}]}},
{"release-version": "10.0.4", "sdk": {"version": "10.0.105", "files": [
{"name": "dotnet-sdk-linux-x64.tar.gz", "rid": "linux-x64", "url": "{{{sdk}}}/10.0.105/dotnet-sdk-10.0.105-linux-x64.tar.gz", "hash": "{{{other}}}"}]}}]}
""";
async Task<(int Code, string Output, string Errors)> ChooseAsync(string json)
{
var file = Path.Combine(folder.Path, $"releases-{Guid.NewGuid():N}.json");
await File.WriteAllTextAsync(file, json, TestContext.CancellationToken);
return await RunProcessAsync(bash, ["-c", "LC_ALL=C awk -v rid=linux-x64 -f .gitea/scripts/json.awk -f .gitea/scripts/dotnet-sdk.awk \"$1\"", "bash", file.Replace('\\', '/')]);
}
var chosen = await ChooseAsync(Metadata("10.0.201", sdk, hash));
Assert.AreEqual(0, chosen.Code, chosen.Errors);
Assert.AreEqual($"10.0.201\t{sdk}/10.0.201/dotnet-sdk-10.0.201-linux-x64.tar.gz\t{hash.ToLowerInvariant()}\n", chosen.Output);
// No archive of the newest SDK for this rid, an archive on another host, a short hash, no latest-sdk, broken
// JSON: nothing is chosen, and the step stops.
foreach (var (json, why) in new[]
{
(Metadata("10.0.300", sdk, hash), "archivio"),
(Metadata("10.0.201", "https://esempio.invalid/dotnet/Sdk", hash), "archivio"),
(Metadata("10.0.201", "http://builds.dotnet.microsoft.com/dotnet/Sdk", hash), "archivio"),
(Metadata("10.0.201", sdk, hash[..64]), "archivio"),
(Metadata("", sdk, hash), "latest-sdk"),
(Metadata("10.0.201", sdk, hash)[..200], "non validi"),
})
{
var refused = await ChooseAsync(json);
Assert.AreEqual(1, refused.Code, $"{why}\n{refused.Output}");
Assert.IsEmpty(refused.Output, why);
StringAssert.Contains(refused.Errors, why);
}
}
[TestMethod]
[Timeout(120_000, CooperativeCancellation = true)]
public async Task TheChecksStopActionsBadIndentationAndBrokenJson()
{
var bash = RequireBash();
CiPath("scripts", "controlli.sh");
const string good = """
name: prova
on:
push:
branches: ["**"]
jobs:
uno:
runs-on: ubuntu-latest
steps:
- name: Passo
run: |
echo ciao
un rientro libero dentro il blocco di testo
- name: Altro
run: >-
echo uno
due
""";
var passed = await RunChecksAsync(bash, good, "{\"a\": [1, 2.5e3, \"x\\u00e8\"], \"b\": null}");
Assert.AreEqual(0, passed.Code, passed.Output + passed.Errors);
StringAssert.Contains(passed.Output, "Controlli superati.");
foreach (var (workflow, json, expected) in new[]
{
(good.Replace(" - name: Altro", " - uses: actions/checkout@v4\n - name: Altro", StringComparison.Ordinal), "{}", "«uses:» (nessuna azione: solo comandi)"),
(good.Replace(" runs-on:", " runs-on:", StringComparison.Ordinal), "{}", "rientro dispari"),
(good.Replace(" runs-on:", "\truns-on:", StringComparison.Ordinal), "{}", "tabulazioni"),
(good.Replace("jobs:", "lavori:", StringComparison.Ordinal), "{}", "manca «jobs:»"),
(good, "{\"a\": 1,}", "JSON non valido"),
(good, "{\"a\": 01}", "JSON non valido"),
})
{
var failed = await RunChecksAsync(bash, workflow, json);
Assert.AreEqual(1, failed.Code, $"{expected}\n{failed.Output}");
StringAssert.Contains(failed.Errors, expected, failed.Output);
}
}
[TestMethod]
[Timeout(120_000, CooperativeCancellation = true)]
public async Task TheArtifactsGoToThePackageOfTheRunAndTheTokenNeverToTheLog()
{
var bash = RequireBash();
CiPath("scripts", "artefatti.sh");
using var folder = new TempFolder("febe-artefatti-su");
var bin = folder.Combine("bin");
var world = folder.Combine("registro");
Directory.CreateDirectory(bin);
Directory.CreateDirectory(world);
InstallFake("fake-curl.sh", Path.Combine(bin, "curl"));
await File.WriteAllTextAsync(Path.Combine(world, "token"), RegistryToken, TestContext.CancellationToken);
const string server = "http://gitea.invalid";
var upload = $"{server}/api/packages/Alby96/generic/febe-ci";
await File.WriteAllTextAsync(Path.Combine(world, "upload"), upload, TestContext.CancellationToken);
var results = new[] { folder.Combine("prove-seme-13.trx"), folder.Combine("prove-seme-1042.trx") };
foreach (var file in results)
{
await File.WriteAllTextAsync(file, "<TestRun />\n", TestContext.CancellationToken);
}
var version = Regex.Match(Read(Repository.PathOf("Directory.Build.props")), "<Version>(?<v>[^<]+)</Version>").Groups["v"].Value + "-ci.77";
var files = results.Select(f => f.Replace('\\', '/')).ToArray();
async Task<(int Code, string Output, string Errors, List<string> Calls)> SendAsync(string? token, string flow = "verifica", string? number = "77", params string[] paths)
{
File.Delete(Path.Combine(world, "calls"));
string[] script = ["-c", "bin=\"$FAKE_BIN\"; if command -v cygpath > /dev/null; then bin=\"$(cygpath -u \"$bin\")\"; fi; PATH=\"$bin:$PATH\"; exec bash \"$@\"", "bash", ".gitea/scripts/artefatti.sh", flow];
var run = await RunProcessAsync(bash, [.. script, .. paths.Length > 0 ? paths : files], start =>
{
start.Environment["FAKE_BIN"] = bin;
start.Environment["FAKE_CURL_WORLD"] = world.Replace('\\', '/');
start.Environment["GITEA_URL"] = server + "/";
start.Environment["PROPRIETARIO"] = "Alby96";
start.Environment.Remove("REGISTRY_TOKEN");
start.Environment.Remove("NUMERO");
if (token is not null)
{
start.Environment["REGISTRY_TOKEN"] = token;
}
if (number is not null)
{
start.Environment["NUMERO"] = number;
}
});
Assert.DoesNotContain(RegistryToken, run.Output + run.Errors, "the token never reaches the log");
Assert.DoesNotContain("fake curl:", run.Errors);
Assert.DoesNotContain("curl: (", run.Errors, "a real curl was called");
return (run.Code, run.Output, run.Errors, await ReadLinesAsync(Path.Combine(world, "calls")));
}
// Without the secret: a warning, nothing sent, the job green.
var without = await SendAsync(token: null);
Assert.AreEqual(0, without.Code, without.Errors);
StringAssert.Contains(without.Output, "::warning::Manca il segreto REGISTRY_TOKEN");
Assert.IsEmpty(without.Calls);
// With it: one PUT per file, into the version of the run.
var sent = await SendAsync(RegistryToken);
Assert.AreEqual(0, sent.Code, sent.Errors);
CollectionAssert.AreEqual(new[] { $"PUT {upload}/{version}/prove-seme-13.trx", $"PUT {upload}/{version}/prove-seme-1042.trx" }, sent.Calls);
Assert.AreEqual("<TestRun />\n", (await File.ReadAllTextAsync(Path.Combine(world, "uploaded", version, "prove-seme-13.trx"), TestContext.CancellationToken)).Replace("\r\n", "\n", StringComparison.Ordinal));
StringAssert.Contains(sent.Output, $"Artefatti: {server}/Alby96/-/packages/generic/febe-ci/{version}");
// A new attempt of the same run: Gitea answers 409, the old copy goes and the new one takes its place.
var again = await SendAsync(RegistryToken, paths: [files[0]]);
Assert.AreEqual(0, again.Code, again.Errors);
CollectionAssert.AreEqual(new[] { $"PUT {upload}/{version}/prove-seme-13.trx", $"DELETE {upload}/{version}/prove-seme-13.trx", $"PUT {upload}/{version}/prove-seme-13.trx" }, again.Calls);
// The release keeps its own versions.
var release = await SendAsync(RegistryToken, "rilascio", paths: [files[1]]);
Assert.AreEqual(0, release.Code, release.Errors);
CollectionAssert.AreEqual(new[] { $"PUT {upload}/{version.Replace("-ci.", "-rilascio.", StringComparison.Ordinal)}/prove-seme-1042.trx" }, release.Calls);
// A missing file, a refusal, a token Gitea does not know: the step fails. Without the number of the run, or with
// a flow of another name, nothing is sent.
var missing = await SendAsync(RegistryToken, paths: [folder.Combine("non-c-e.trx").Replace('\\', '/')]);
Assert.AreEqual(1, missing.Code, missing.Output);
Assert.IsEmpty(missing.Calls);
var unknown = await SendAsync("un-altro-gettone-finto");
Assert.AreEqual(1, unknown.Code, unknown.Output);
StringAssert.Contains(unknown.Errors, "risponde 401");
Assert.DoesNotContain("un-altro-gettone-finto", unknown.Output + unknown.Errors);
foreach (var (flow, number) in new[] { ("verifica", (string?)null), ("verifica", "7a"), ("prova", "77") })
{
var refused = await SendAsync(RegistryToken, flow, number);
Assert.AreEqual(2, refused.Code, $"{flow} {number}");
Assert.IsEmpty(refused.Calls, $"{flow} {number}");
}
}
/// <summary>controlli.sh in a repository of its own: the scripts it needs, one workflow, one JSON file.</summary>
private async Task<(int Code, string Output, string Errors)> RunChecksAsync(string bash, string workflow, string json)
{
using var folder = new TempFolder("febe-controlli");
var root = folder.Path;
foreach (var script in new[] { "controlli.sh", "json.awk", "json-valido.awk" })
{
var target = Path.Combine(root, ".gitea", "scripts", script);
Directory.CreateDirectory(Path.GetDirectoryName(target)!);
await File.WriteAllTextAsync(target, Read(CiPath("scripts", script)), TestContext.CancellationToken);
}
Directory.CreateDirectory(Path.Combine(root, ".gitea", "workflows"));
Directory.CreateDirectory(Path.Combine(root, "src"));
await File.WriteAllTextAsync(Path.Combine(root, ".gitea", "workflows", "prova.yml"), workflow.Replace("\r\n", "\n", StringComparison.Ordinal) + "\n", TestContext.CancellationToken);
await File.WriteAllTextAsync(Path.Combine(root, "dati.json"), json, TestContext.CancellationToken);
await File.WriteAllTextAsync(Path.Combine(root, "Directory.Build.props"), "<Project>\n <PropertyGroup>\n <Version>0.1.2</Version>\n </PropertyGroup>\n</Project>\n", TestContext.CancellationToken);
await File.WriteAllTextAsync(Path.Combine(root, "Febe.slnx"), "<Solution>\n <Project Path=\"src/Uno.csproj\" />\n</Solution>\n", TestContext.CancellationToken);
await File.WriteAllTextAsync(Path.Combine(root, "src", "Uno.csproj"), "<Project />\n", TestContext.CancellationToken);
var prepared = await RunProcessAsync(bash, ["-c", "git -c init.defaultBranch=main init -q . && git -c core.autocrlf=false add -A"], start => start.WorkingDirectory = root);
Assert.AreEqual(0, prepared.Code, prepared.Errors);
return await RunProcessAsync(bash, [".gitea/scripts/controlli.sh"], start => start.WorkingDirectory = root);
}
[GeneratedRegex(@"(?m)^\s*(?:-\s+)?uses\s*:")]
private static partial Regex UsesLine();
// A command named node, npm, npx, corepack or nodejs: at the start of a command, not a word in a message.
[GeneratedRegex(@"(?:^|[;&|({]|\$\(|\b(?:then|do|else|run:|exec|command)\s)\s*(?:node|nodejs|npm|npx|corepack)(?=\s|$|[;&|)])")]
private static partial Regex NodeCommand();
[GeneratedRegex(@"(?m)^ - name: (?<name>.+)$")]
private static partial Regex StepName();
// Where a job uses the SDK: dotnet itself, or the installer build, which runs dotnet publish.
[GeneratedRegex(@"(?m)^\s*(?:run:\s*(?:>-?|\|)?\s*)?(?:dotnet\s+(?:build|test|publish|run|restore|pack)\b|bash installer/costruisci\.sh)")]
private static partial Regex DotnetUse();
}
@@ -7,8 +7,9 @@ using Febe.Tests.Support;
namespace Febe.Tests.Packaging;
/// <summary>
/// The cleanup of the CI: .gitea/scripts/pulizia-docker.sh, its choice of registry tags (versioni-registro.js) and the
/// steps that run it. The Docker daemon is shared with Alberto's other projects, very likely with his Unraid apps, and
/// The cleanup of the CI: .gitea/scripts/pulizia-docker.sh, its choice of registry versions (versioni-registro.sh, awk
/// with json.awk: no Node, no jq) and the steps that run it. The Docker daemon is shared with Alberto's other projects,
/// very likely with his Unraid apps, and
/// may run a real Febe. Since 21 October 2026 the cleanup removes what the CI of Febe made and what nothing uses any
/// more, of any project; never a container, a volume or a network that is not the CI's, never main, latest or a
/// release on the registry, never the token in the log; with --prova it removes nothing at all. The script runs against
@@ -34,6 +35,12 @@ public sealed partial class PipelineTests
"sha256:d0e666bf0a465af6218c1825f3fd72143e2f9ddfc038a8cda19b0504656e0647",
];
/// <summary>
/// The versions of the generic package febe-ci in artefatti-registro.json created more than 14 days ago, oldest
/// first: those of 2020 with the shape of an artifact of the CI and a date with its zone.
/// </summary>
private static readonly string[] ExpiredArtifacts = ["0.1.2-rilascio.3", "0.1.2-ci.40", "0.2.0-rc.1-ci.7"];
[TestMethod]
public void TheCleanupNeverPrunesBlindlyAndChoosesOnlyByTheMarksOfTheCiOrByUse()
{
@@ -80,9 +87,13 @@ public sealed partial class PipelineTests
Assert.IsFalse(ForcedImageRemoval().IsMatch(cleanup), "an image is never removed by force");
StringAssert.Contains(cleanup, "[[ \"$riferimento\" =~ ^febe-ci:[0-9]+$ ]]");
// On the registry only the shape of a sha- tag of the verification, checked again before every DELETE.
// On the registry only the shape of a sha- tag of the verification, or of an artifact of the CI, checked again
// before every DELETE.
StringAssert.Contains(cleanup, "[[ ! \"$versione\" =~ ^sha-[0-9a-f]{7,40}$ ]]");
StringAssert.Contains(Script("versioni-registro.js"), "/^sha-[0-9a-f]{7,40}$/");
StringAssert.Contains(cleanup, "[[ ! \"$versione\" =~ ^[0-9]+\\.[0-9]+\\.[0-9]+(-[0-9A-Za-z.-]+)?-(ci|rilascio)\\.[0-9]+$ ]]");
var chooser = Script("versioni-registro.sh");
StringAssert.Contains(chooser, "$4 ~ /^sha-[0-9a-f]+$/ && length($4) >= 11 && length($4) <= 44");
Assert.DoesNotContain("node", Code(Script("pulizia-docker.sh")) + Code(chooser), "the registry is read with awk, not with Node");
}
[TestMethod]
@@ -321,7 +332,6 @@ public sealed partial class PipelineTests
public async Task TheDryRunListsWhatTheCleanupWouldTakeAndTouchesNothing()
{
var bash = RequireBash();
RequireNode();
var world = SharedDaemon.World with { Registry = new FakeRegistry(RegistryToken) };
var tried = await RunCleanupAsync(bash, world, "completa", "--prova");
Assert.AreEqual(0, tried.Code, tried.Report);
@@ -336,7 +346,14 @@ public sealed partial class PipelineTests
Assert.IsTrue(tried.RegistryCalls.Count > 0 && tried.RegistryCalls.All(c => c.StartsWith("GET ", StringComparison.Ordinal)), tried.Report);
Assert.IsEmpty(tried.Deleted, tried.Report);
Assert.IsEmpty(tried.DeletedArtifacts, tried.Report);
Assert.DoesNotContain(RegistryToken, tried.Output + tried.Errors, "the token never reaches the log");
foreach (var version in ExpiredArtifacts)
{
StringAssert.Contains(tried.Output, $" toglierei febe-ci {version} (caricata il ", tried.Report);
}
Assert.AreEqual(ExpiredArtifacts.Length.ToString(System.Globalization.CultureInfo.InvariantCulture), SummaryCount(tried.Output, "artefatti della CI sul registro"), tried.Report);
// What it lists, with size and age: also what becomes unused once the leftovers it lists are gone.
Assert.DoesNotContain("solo indicativo", tried.Output, "with the classic store the ages are those «until» uses");
@@ -428,21 +445,22 @@ public sealed partial class PipelineTests
[Timeout(60_000, CooperativeCancellation = true)]
public async Task TheRegistryKeepsMainLatestTheReleasesAndTheTenNewestShaTags()
{
var node = RequireNode();
var script = CiPath("scripts", "versioni-registro.js");
var bash = RequireBash();
CiPath("scripts", "versioni-registro.sh");
const string script = ".gitea/scripts/versioni-registro.sh";
using var folder = new TempFolder("febe-registro");
var pages = await WriteRegistryPagesAsync(folder.Path);
// Of fourteen sha- tags the four oldest go. sha-3d4e5f6 (23:30 UTC) is newer than sha-4e5f6a7 (01:00 in Italy,
// 23:00 UTC): dates, not text. main, latest, the releases, digests, malformed sha- tags, one without a date and
// other packages stay, though they are older; a tag in two pages counts once.
var chosen = await RunProcessAsync(node, [script, "10", .. pages]);
var chosen = await RunProcessAsync(bash, [script, "10", .. pages]);
Assert.AreEqual(0, chosen.Code, chosen.Errors);
CollectionAssert.AreEqual(OldShaTags, Lines(chosen.Output).Select(l => l.Split('\t')[0]).ToList(), chosen.Output);
StringAssert.Contains(chosen.Output, "sha-2c3d4e5\t2026-10-03T07:00:00Z\n");
// Keeping none: every well formed sha- tag of the container febe, and nothing else.
var all = await RunProcessAsync(node, [script, "0", .. pages]);
var all = await RunProcessAsync(bash, [script, "0", .. pages]);
Assert.HasCount(14, Lines(all.Output), all.Output);
foreach (var line in Lines(all.Output))
{
@@ -451,20 +469,63 @@ public sealed partial class PipelineTests
// The untagged versions, the manifests of an index with their layers: listed only to be counted, oldest first,
// those of the container febe and no other package.
var untagged = await RunProcessAsync(node, [script, "senza-etichetta", .. pages]);
var untagged = await RunProcessAsync(bash, [script, "senza-etichetta", .. pages]);
Assert.AreEqual(0, untagged.Code, untagged.Errors);
CollectionAssert.AreEqual(UntaggedDigests, Lines(untagged.Output).Select(l => l.Split('\t')[0]).ToList(), untagged.Output);
// Keeping more than there are: nothing. An empty page of Gitea is fine; a page that is not a list stops
// everything, so in doubt nothing goes.
// Keeping more than there are: nothing. An empty page of Gitea is fine; a page that is not a list, or not JSON,
// stops everything, so in doubt nothing goes. So does a mode written another way.
var empty = Path.Combine(folder.Path, "vuota.json");
await File.WriteAllTextAsync(empty, "null", TestContext.CancellationToken);
Assert.IsEmpty((await RunProcessAsync(node, [script, "20", .. pages, empty])).Output);
Assert.IsEmpty((await RunProcessAsync(bash, [script, "20", .. pages, empty])).Output);
var broken = Path.Combine(folder.Path, "rotta.json");
await File.WriteAllTextAsync(broken, "{\"message\":\"internal error\"}", TestContext.CancellationToken);
var refused = await RunProcessAsync(node, [script, "10", .. pages, broken]);
Assert.AreEqual(2, refused.Code, refused.Errors);
Assert.IsEmpty(refused.Output);
var cut = Path.Combine(folder.Path, "tagliata.json");
await File.WriteAllTextAsync(cut, "[{\"type\":\"container\",\"name\":\"febe\",\"version\":\"sha-0a1b2c3\"", TestContext.CancellationToken);
foreach (var bad in new[] { broken, cut })
{
var refused = await RunProcessAsync(bash, [script, "10", .. pages, bad]);
Assert.AreEqual(2, refused.Code, refused.Errors);
Assert.IsEmpty(refused.Output);
StringAssert.Contains(refused.Errors, Path.GetFileName(bad));
}
foreach (var mode in new[] { "dieci", "-1", "senza_etichetta" })
{
var wrong = await RunProcessAsync(bash, [script, mode, .. pages]);
Assert.AreEqual(2, wrong.Code, mode);
Assert.IsEmpty(wrong.Output, mode);
}
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task OnlyTheArtifactsOfTheCiOlderThanTheirDaysExpire()
{
var bash = RequireBash();
CiPath("scripts", "versioni-registro.sh");
const string script = ".gitea/scripts/versioni-registro.sh";
using var folder = new TempFolder("febe-artefatti");
var pages = await WriteArtifactPagesAsync(folder.Path, "pagina-");
var now = DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString(System.Globalization.CultureInfo.InvariantCulture);
// Those of 2020 with the shape <x.y.z>-ci.<n> or <x.y.z>-rilascio.<n>, oldest first. The one of 2099, a release
// version, a date that does not read or has no zone, another package, a container and a strange name stay.
var expired = await RunProcessAsync(bash, [script, "scadute", "14", now, .. pages]);
Assert.AreEqual(0, expired.Code, expired.Errors);
CollectionAssert.AreEqual(ExpiredArtifacts, Lines(expired.Output).Select(l => l.Split('\t')[0]).ToList(), expired.Output);
StringAssert.Contains(expired.Output, "0.2.0-rc.1-ci.7\t2020-04-01T00:00:00.250Z\n");
// On the first of April 2020 at noon only those created more than a day before have expired.
var early = await RunProcessAsync(bash, [script, "scadute", "1", "1585742400", .. pages]);
CollectionAssert.AreEqual(new[] { "0.1.2-rilascio.3", "0.1.2-ci.40" }, Lines(early.Output).Select(l => l.Split('\t')[0]).ToList(), early.Output);
foreach (var arguments in new[] { new[] { "scadute", "14" }, ["scadute", "quattordici", now], ["scadute", "14", "ieri"] })
{
var wrong = await RunProcessAsync(bash, [script, .. arguments, .. pages]);
Assert.AreEqual(2, wrong.Code, string.Join(' ', arguments));
Assert.IsEmpty(wrong.Output);
}
}
[TestMethod]
@@ -472,41 +533,54 @@ public sealed partial class PipelineTests
public async Task TheRegistryCleanupDeletesOnlyTheChosenTagsNeverPrintsTheTokenAndARefusalIsOnlyAWarning()
{
var bash = RequireBash();
RequireNode();
// A daemon with almost nothing on it: here only the registry counts.
var quiet = new World(["c-encelado|encelado|exited|5000|encelado:latest|img-encelado|"], ["img-encelado|encelado:latest|5000||250MB"], [], []);
var run = await RunCleanupAsync(bash, quiet with { Registry = new FakeRegistry(RegistryToken) }, "completa");
Assert.AreEqual(0, run.Code, run.Report);
CollectionAssert.AreEqual(OldShaTags, run.Deleted, run.Report);
CollectionAssert.AreEqual(ExpiredArtifacts, run.DeletedArtifacts, run.Report);
var package = $"{RegistryApi}/packages/Alby96/container/febe";
var artifacts = $"{RegistryApi}/packages/Alby96/generic/febe-ci";
CollectionAssert.AreEqual(
new[] { $"GET {package}?page=1&limit=50", $"GET {package}?page=2&limit=50", $"GET {package}?page=3&limit=50" }
.Concat(OldShaTags.Select(tag => $"DELETE {package}/{tag}")).ToList(),
.Concat(OldShaTags.Select(tag => $"DELETE {package}/{tag}"))
.Concat([$"GET {artifacts}?page=1&limit=50", $"GET {artifacts}?page=2&limit=50", $"GET {artifacts}?page=3&limit=50"])
.Concat(ExpiredArtifacts.Select(version => $"DELETE {artifacts}/{version}")).ToList(),
run.RegistryCalls,
run.Report);
Assert.DoesNotContain(RegistryToken, run.Output + run.Errors, "the token never reaches the log");
Assert.AreEqual("4", SummaryCount(run.Output, "etichette sha- sul registro"), run.Report);
Assert.AreEqual("3", SummaryCount(run.Output, "artefatti della CI sul registro"), run.Report);
// The untagged versions stay, and the log says how many there are: their layers are freed only by a cleanup
// rule of Gitea, which knows whether a tag still uses them.
Assert.IsFalse(run.RegistryCalls.Any(c => c.Contains("sha256:", StringComparison.Ordinal)), run.Report);
StringAssert.Contains(run.Output, $" {UntaggedDigests.Length} versioni senza etichetta (sha256:…, i manifest di un indice con i loro strati): restano", run.Report);
// No package febe-ci yet (404): nothing to remove there, and no warning.
var without = await RunCleanupAsync(bash, quiet with { Registry = new FakeRegistry(RegistryToken, Artifacts: false) }, "completa");
Assert.AreEqual(0, without.Code, without.Report);
StringAssert.Contains(without.Output, "Il pacchetto febe-ci non è ancora sul registro: niente da togliere.", without.Report);
Assert.IsEmpty(without.DeletedArtifacts, without.Report);
Assert.IsFalse(WarningLine().IsMatch(without.Output), without.Report);
// The API refuses (a token without the permission) or does not know the token: a warning, nothing deleted,
// and the weekly job stays green.
// the registry is not asked again with the same token, and the weekly job stays green.
foreach (var registry in new[] { new FakeRegistry(RegistryToken, Refuse: true), new FakeRegistry(RegistryToken, Sent: "un-altro-gettone-finto") })
{
var refused = await RunCleanupAsync(bash, quiet with { Registry = registry }, "completa");
Assert.AreEqual(0, refused.Code, refused.Report);
StringAssert.Contains(refused.Output, "::warning::L'API dei pacchetti di Gitea risponde 40", refused.Report);
Assert.IsEmpty(refused.Deleted, refused.Report);
Assert.IsEmpty(refused.DeletedArtifacts, refused.Report);
Assert.HasCount(1, refused.RegistryCalls, refused.Report);
Assert.DoesNotContain(RegistryToken, refused.Output + refused.Errors);
Assert.DoesNotContain("un-altro-gettone-finto", refused.Output + refused.Errors);
}
}
/// <summary>
/// The daemon of <see cref="OnADaemonSharedWithARealFebeTheCleanupOfTheCiTakesOnlyWhatTheCiMade"/> (format in
/// fake-docker.sh). A real Febe started from :latest and one from :main carry the febe.ci.* labels of their images,
@@ -714,10 +788,11 @@ public sealed partial class PipelineTests
}
/// <summary>
/// The packages API of Gitea with the pages of versioni-registro.json, for the token given. Sent is the token the
/// cleanup gets (the same, if null); Refuse answers 403 to everything.
/// The packages API of Gitea with the pages of versioni-registro.json and, with Artifacts, the generic package
/// febe-ci of artefatti-registro.json, for the token given. Sent is the token the cleanup gets (the same, if null);
/// Refuse answers 403 to everything.
/// </summary>
private sealed record FakeRegistry(string Token, bool Refuse = false, string? Sent = null);
private sealed record FakeRegistry(string Token, bool Refuse = false, string? Sent = null, bool Artifacts = true);
private sealed record CleanupRun(int Code, string Output, string Errors)
{
@@ -740,6 +815,9 @@ public sealed partial class PipelineTests
/// <summary>The versions deleted from the registry.</summary>
public List<string> Deleted { get; init; } = [];
/// <summary>The versions of the generic package febe-ci deleted from the registry.</summary>
public List<string> DeletedArtifacts { get; init; } = [];
public List<string> ImageIds => [.. Images.Select(i => i.Split('|')[0])];
public string Report => $"codice {Code}\n{Output}\n{Errors}";
@@ -794,6 +872,11 @@ public sealed partial class PipelineTests
}
await WriteRegistryPagesAsync(registry);
if (fake.Artifacts)
{
await File.WriteAllTextAsync(Path.Combine(registry, "base-ci"), $"{RegistryApi}/packages/Alby96/generic/febe-ci", TestContext.CancellationToken);
await WriteArtifactPagesAsync(registry, "ci-page-");
}
}
// The fakes go first on the PATH from inside bash: Git Bash puts its own folders (with a real curl) before the
@@ -826,6 +909,7 @@ public sealed partial class PipelineTests
Calls = await ReadLinesAsync(folder.Combine("calls")),
RegistryCalls = await ReadLinesAsync(Path.Combine(registry, "calls")),
Deleted = await ReadLinesAsync(Path.Combine(registry, "deleted")),
DeletedArtifacts = await ReadLinesAsync(Path.Combine(registry, "deleted-ci")),
};
if (touchesDocker)
{
@@ -879,6 +963,23 @@ public sealed partial class PipelineTests
return files;
}
/// <summary>The pages of artefatti-registro.json (the generic package febe-ci) as Gitea would answer them, one
/// file each, named prefix plus the page number.</summary>
private async Task<List<string>> WriteArtifactPagesAsync(string folder, string prefix)
{
var fixture = await File.ReadAllTextAsync(Repository.PathOf("tests", "Febe.Tests", "Packaging", "artefatti-registro.json"), TestContext.CancellationToken);
using var pages = JsonDocument.Parse(fixture);
var files = new List<string>();
foreach (var page in pages.RootElement.EnumerateArray())
{
var file = Path.Combine(folder, $"{prefix}{files.Count + 1}.json");
await File.WriteAllTextAsync(file, page.GetRawText(), TestContext.CancellationToken);
files.Add(file);
}
return files;
}
private static void InstallFake(string name, string path)
{
File.Copy(Repository.PathOf("tests", "Febe.Tests", "Packaging", name), path);
@@ -935,22 +1036,6 @@ public sealed partial class PipelineTests
return bash;
}
/// <summary>node from the PATH: the registry part of the cleanup reads JSON with it, in the CI as here.</summary>
private static string RequireNode()
{
var names = OperatingSystem.IsWindows() ? new[] { "node.exe" } : ["node"];
var node = (Environment.GetEnvironmentVariable("PATH") ?? string.Empty)
.Split(Path.PathSeparator, StringSplitOptions.RemoveEmptyEntries)
.SelectMany(folder => names.Select(name => Path.Combine(folder.Trim('"'), name)))
.FirstOrDefault(File.Exists);
if (node is null)
{
Assert.Inconclusive("Manca node: la prova della scelta delle versioni del registro si salta.");
}
return node;
}
[GeneratedRegex(@"docker (?<what>[a-z]+) prune(?<args>[^\n]*)")]
private static partial Regex Prune();
+9 -6
View File
@@ -59,7 +59,7 @@ public sealed partial class PipelineTests
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, "container:\n image: debian:trixie", "Debian: Chromium is a real package there, a snap on Ubuntu; and no Node in it");
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");
@@ -114,9 +114,12 @@ public sealed partial class PipelineTests
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");
StringAssert.Contains(image, "BUILDER: febe-ci-${{ gitea.run_id }}");
StringAssert.Contains(image, "bash .gitea/scripts/costruisci-immagine.sh builder \"$REGISTRY\"");
var builder = Code(Script("costruisci-immagine.sh"));
StringAssert.Contains(builder, "http = true");
StringAssert.Contains(builder, "insecure = true");
StringAssert.Contains(builder, "--driver docker-container");
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" })
{
@@ -169,7 +172,7 @@ public sealed partial class PipelineTests
var secrets = Script("segreti.sh");
StringAssert.Contains(secrets, "--redact");
StringAssert.Contains(Job(Workflow("verifica.yml"), "controlli"), "fetch-depth: 0");
StringAssert.Contains(Step(Job(Workflow("verifica.yml"), "controlli"), "Sorgenti"), "PROFONDITA: \"0\"", "gitleaks reads the whole history");
var scan = Script("scansione-immagine.sh");
StringAssert.Contains(scan, "--severity CRITICAL --ignore-unfixed");
StringAssert.Contains(scan, "--exit-code 1");
@@ -264,7 +267,7 @@ public sealed partial class PipelineTests
[GeneratedRegex(@"\b(?:echo|printf)\b")]
private static partial Regex Printing();
[GeneratedRegex(@"\$\{?(?:TOKEN|FEBE_PASSWORD|AUTH|REGISTRY_TOKEN|PASSWORD)\b")]
[GeneratedRegex(@"\$\{?(?:TOKEN|FEBE_PASSWORD|AUTH|REGISTRY_TOKEN|GITEA_TOKEN|INTESTAZIONE|GIT_CONFIG_VALUE_0|PASSWORD)\b")]
private static partial Regex SecretReference();
[GeneratedRegex(@"\b[0-9a-f]{64}\b")]
@@ -0,0 +1,17 @@
[
[
{"id": 301, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "generic", "name": "febe-ci", "version": "0.1.2-ci.40", "html_url": "https://gitea.example/Alby96/-/packages/generic/febe-ci/0.1.2-ci.40", "created_at": "2020-03-01T10:00:00+01:00"},
{"id": 302, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "generic", "name": "febe-ci", "version": "0.1.2-ci.41", "html_url": "https://gitea.example/Alby96/-/packages/generic/febe-ci/0.1.2-ci.41", "created_at": "2099-03-01T10:00:00+01:00"},
{"id": 303, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "generic", "name": "febe-ci", "version": "0.1.2-rilascio.3", "html_url": "https://gitea.example/Alby96/-/packages/generic/febe-ci/0.1.2-rilascio.3", "created_at": "2020-02-01T10:00:00Z"},
{"id": 304, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "generic", "name": "febe-ci", "version": "0.1.2", "html_url": "https://gitea.example/Alby96/-/packages/generic/febe-ci/0.1.2", "created_at": "2020-01-01T00:00:00Z"},
{"id": 305, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "generic", "name": "febe-ci", "version": "0.1.2-ci.39", "html_url": "https://gitea.example/Alby96/-/packages/generic/febe-ci/0.1.2-ci.39", "created_at": "non è una data"},
{"id": 309, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "generic", "name": "febe-ci", "version": "0.1.2-ci.38", "html_url": "https://gitea.example/Alby96/-/packages/generic/febe-ci/0.1.2-ci.38", "created_at": "2020-01-15T10:00:00"}
],
[
{"id": 306, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "generic", "name": "altro", "version": "0.1.2-ci.1", "html_url": "https://gitea.example/Alby96/-/packages/generic/altro/0.1.2-ci.1", "created_at": "2020-01-01T00:00:00Z"},
{"id": 307, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe-ci", "version": "0.1.2-ci.2", "html_url": "https://gitea.example/Alby96/-/packages/container/febe-ci/0.1.2-ci.2", "created_at": "2020-01-01T00:00:00Z"},
{"id": 301, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "generic", "name": "febe-ci", "version": "0.1.2-ci.40", "html_url": "https://gitea.example/Alby96/-/packages/generic/febe-ci/0.1.2-ci.40", "created_at": "2020-03-01T10:00:00+01:00"},
{"id": 308, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "generic", "name": "febe-ci", "version": "0.2.0-rc.1-ci.7", "html_url": "https://gitea.example/Alby96/-/packages/generic/febe-ci/0.2.0-rc.1-ci.7", "created_at": "2020-04-01T00:00:00.250Z"},
{"id": 310, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "generic", "name": "febe-ci", "version": "0.1.2-ci.37;rm", "html_url": "https://gitea.example/Alby96/-/packages/generic/febe-ci/x", "created_at": "2020-01-01T00:00:00Z"}
]
]
+50 -15
View File
@@ -1,9 +1,17 @@
#!/usr/bin/env bash
# A fake curl for PipelineTests: the registry part of .gitea/scripts/pulizia-docker.sh talks to the packages API of
# Gitea 28 through it. No network. It knows only the options the cleanup uses and answers like Gitea:
# GET <base>?page=<n>&limit=50 the page $FAKE_CURL_WORLD/page-<n>.json, or [] after the last one (200)
# DELETE <base>/<version> 204, and the version is written to $FAKE_CURL_WORLD/deleted
# where <base> is the content of $FAKE_CURL_WORLD/base (…/api/v1/packages/<owner>/container/febe). Without the header
# A fake curl for PipelineTests: the registry part of .gitea/scripts/pulizia-docker.sh and .gitea/scripts/artefatti.sh
# talk to the packages API of Gitea 28 through it. No network. It knows only the options those scripts use and answers
# like Gitea:
# GET <base>?page=<n>&limit=50 the page $FAKE_CURL_WORLD/page-<n>.json, or [] after the last one (200)
# DELETE <base>/<version> 204, and the version is written to $FAKE_CURL_WORLD/deleted
# GET <ci>?page=<n>&limit=50 the page $FAKE_CURL_WORLD/ci-page-<n>.json, or [] after the last one (200)
# DELETE <ci>/<version> 204, and the version is written to $FAKE_CURL_WORLD/deleted-ci
# PUT <upload>/<version>/<file> with --upload-file: 201, the file copied to $FAKE_CURL_WORLD/uploaded/<version>/;
# 409 if that file is already there (as Gitea answers a second upload)
# DELETE <upload>/<version>/<file> 204, and the uploaded file goes
# where <base> is the content of $FAKE_CURL_WORLD/base (…/api/v1/packages/<owner>/container/febe), <ci> of
# $FAKE_CURL_WORLD/base-ci (…/api/v1/packages/<owner>/generic/febe-ci) and <upload> of $FAKE_CURL_WORLD/upload
# (…/api/packages/<owner>/generic/febe-ci); a base whose file is missing is unknown. Without the header
# «Authorization: token <content of $FAKE_CURL_WORLD/token>» it answers 401; with $FAKE_CURL_WORLD/refuse it answers
# 403 to every call; any other address is 404. Every call goes to $FAKE_CURL_WORLD/calls as «METHOD URL», never with
# its headers. Any other option is an error (exit 3).
@@ -11,7 +19,7 @@ set -uo pipefail
world="${FAKE_CURL_WORLD:?}"
token="$(cat "$world/token" 2> /dev/null)"
method=GET output="" write="" url="" authorized=0
method=GET output="" write="" url="" authorized=0 upload=""
while (($#)); do
case "$1" in
-s | -S | -sS) ;;
@@ -20,6 +28,7 @@ while (($#)); do
-H) [[ -n "$token" && "$2" == "Authorization: token $token" ]] && authorized=1; shift ;;
-o) output="$2"; shift ;;
-w) write="$2"; shift ;;
--upload-file) upload="$2"; shift ;;
-*) echo "fake curl: unexpected option $1" >&2; exit 3 ;;
*)
[[ -z "$url" ]] || { echo "fake curl: a second address $1" >&2; exit 3; }
@@ -30,6 +39,7 @@ while (($#)); do
done
printf '%s %s\n' "$method" "$url" >> "$world/calls"
[[ -z "$write" || "$write" == '%{http_code}' ]] || { echo "fake curl: unexpected -w $write" >&2; exit 3; }
[[ -z "$upload" || "$method" == PUT ]] || { echo "fake curl: --upload-file without -X PUT" >&2; exit 3; }
answer() {
local code="$1" body="${2:-}"
@@ -45,19 +55,44 @@ answer() {
[[ -f "$world/refuse" ]] && answer 403 '{"message":"token does not have at least one of required scope(s): [write:package]"}'
((authorized)) || answer 401 '{"message":"token is required"}'
base="$(cat "$world/base")"
known() { [[ -f "$world/$1" ]] && cat "$world/$1"; }
base="$(known base)" || base="//nessuna-base"
ci="$(known base-ci)" || ci="//nessuna-base"
send="$(known upload)" || send="//nessuna-base"
page() {
local prefix="$1" number="${url#*\?page=}"
number="${number%%&*}"
if [[ -f "$world/${prefix}page-$number.json" ]]; then
answer 200 "$(cat "$world/${prefix}page-$number.json")"
fi
answer 200 "[]"
}
case "$method $url" in
"GET $base?page="*"&limit=50")
page="${url#"$base?page="}"
page="${page%%&*}"
if [[ -f "$world/page-$page.json" ]]; then
answer 200 "$(cat "$world/page-$page.json")"
fi
answer 200 "[]"
;;
"GET $base?page="*"&limit=50") page "" ;;
"DELETE $base/"*)
echo "${url#"$base/"}" >> "$world/deleted"
answer 204
;;
"GET $ci?page="*"&limit=50") page "ci-" ;;
"DELETE $ci/"*)
echo "${url#"$ci/"}" >> "$world/deleted-ci"
answer 204
;;
"PUT $send/"*/*)
[[ -f "$upload" ]] || { echo "fake curl: no file to upload: $upload" >&2; exit 3; }
target="$world/uploaded/${url#"$send/"}"
[[ -f "$target" ]] && answer 409 '{"message":"package file already exists"}'
mkdir -p "$(dirname "$target")"
cp "$upload" "$target"
answer 201
;;
"DELETE $send/"*/*)
target="$world/uploaded/${url#"$send/"}"
[[ -f "$target" ]] || answer 404 '{"message":"The target couldn'"'"'t be found."}'
rm -f "$target"
answer 204
;;
*) answer 404 '{"message":"The target couldn'"'"'t be found."}' ;;
esac
+15 -42
View File
@@ -1,6 +1,6 @@
using System.Diagnostics;
using System.Net;
using System.Text.Json;
using System.Text.Json.Nodes;
using Febe.Tests.Desktop.Support;
using Febe.Tests.Support;
using Febe.Tests.Web.Support;
@@ -96,19 +96,14 @@ public sealed class LoginSecurityTests
}
[TestMethod]
public void TheLoginPageGoesBackOnlyToAPageOfTheInterface()
[Timeout(300_000, CooperativeCancellation = true)]
public async Task TheLoginPageGoesBackOnlyToAPageOfTheInterface()
{
var accesso = File.ReadAllText(Repository.PathOf("src", "Febe.Web", "wwwroot", "js", "accesso.js"));
StringAssert.Contains(accesso, "import { returnAddress } from './core/return-path.js';");
StringAssert.Contains(accesso, "location.href = returnAddress(");
Assert.DoesNotContain("startsWith('//')", accesso, "the old check let «/\\host» through");
var node = FindOnPath("node");
if (node is null)
{
Assert.Inconclusive("Node non è installato: la regola della pagina di accesso si prova solo dove c'è (CI, sviluppo).");
}
const string origin = "http://tower:8480";
List<(string? Value, string Expected)> cases =
[
@@ -121,23 +116,18 @@ public sealed class LoginSecurityTests
("/.//dentro", origin + "//dentro"),
];
using var temp = new TempFolder("accesso-js");
var script = temp.Combine("prova.mjs");
var module = new Uri(Repository.PathOf("src", "Febe.Web", "wwwroot", "js", "core", "return-path.js")).AbsoluteUri;
File.WriteAllText(script, $$"""
import { returnAddress } from '{{module}}';
const cases = JSON.parse(process.argv[2]);
console.log(JSON.stringify(cases.map(v => returnAddress(v, '{{origin}}'))));
""");
var start = new ProcessStartInfo(node) { RedirectStandardOutput = true, RedirectStandardError = true };
start.ArgumentList.Add(script);
start.ArgumentList.Add(JsonSerializer.Serialize(cases.Select(c => c.Value)));
using var process = Process.Start(start)!;
var output = process.StandardOutput.ReadToEnd();
var errors = process.StandardError.ReadToEnd();
process.WaitForExit();
Assert.AreEqual(0, process.ExitCode, errors);
var results = JsonSerializer.Deserialize<string[]>(output)!;
// The rule runs where it runs for real: in Chromium, in the module the login page imports, served by Febe to a
// browser that has not logged in yet. No other JavaScript engine: the CI has no Node.
await using var ui = await UiBrowser.StartAsync();
await using var server = await StartAsync(trustProxy: false);
var page = new Uri(server.Address, "/accesso");
var navigation = await ui.SendAsync("Page.navigate", new JsonObject { ["url"] = page.AbsoluteUri });
Assert.IsFalse(navigation.TryGetProperty("errorText", out var error) && error.GetString() is { Length: > 0 }, $"apertura di {page}: {error}");
await ui.WaitAsync("location.pathname === '/accesso' && document.readyState === 'complete'", "pagina di accesso");
var values = JsonSerializer.Serialize(cases.Select(c => c.Value));
var results = await ui.EvalAsync<string[]>(
$"import('/js/core/return-path.js').then((m) => {values}.map((v) => m.returnAddress(v, {JsonSerializer.Serialize(origin)})))");
Assert.HasCount(cases.Count, results, ui.Report());
for (var i = 0; i < cases.Count; i++)
{
Assert.AreEqual(cases[i].Expected, results[i], JsonSerializer.Serialize(cases[i].Value));
@@ -199,21 +189,4 @@ public sealed class LoginSecurityTests
private static bool IsSecure(string setCookie) =>
setCookie.Split(';').Any(part => string.Equals(part.Trim(), "secure", StringComparison.OrdinalIgnoreCase));
private static string? FindOnPath(string name)
{
foreach (var folder in (Environment.GetEnvironmentVariable("PATH") ?? string.Empty).Split(Path.PathSeparator, StringSplitOptions.RemoveEmptyEntries))
{
foreach (var candidate in new[] { name, name + ".exe" })
{
var path = Path.Combine(folder, candidate);
if (File.Exists(path))
{
return path;
}
}
}
return null;
}
}