Files
Febe/tests/Febe.Tests/Packaging/PipelineTests.cs
T
Alby96andClaude Opus 5.5 0f11fc5220 CI: la pulizia toglie anche ciò che non serve più a nessuno
Alberto, 21/10: la pulizia della CI deve eliminare tutto quello che non
serve più, non solo ciò che la CI di Febe ha creato. pulizia-docker.sh ha
due modi nuovi. «penzolanti»: le immagini senza nome e la cache di
costruzione che nessuna immagine condivide, di tutti i progetti; un errore
è solo un avviso. «completa»: i resti della CI di Febe come prima, i resti
di act_runner (contenitori fermi, volumi e reti GITEA-ACTIONS-TASK-… che
nessuno usa), le immagini che nessun contenitore usa e la cache più
vecchie di 24 ore, e con REGISTRY_TOKEN le etichette sha- del registro
oltre le 10 più recenti. Mai system, container, volume o network prune,
mai un contenitore, un volume o una rete che non sia della CI. Con
--prova ogni modo elenca che cosa toglierebbe e non tocca nulla.

Le etichette del registro le sceglie versioni-registro.js, che si prova
con un JSON e senza rete; controlli.sh ne controlla la sintassi. Le prove
girano contro un docker e un curl finti, su un demone come quello del
runner: applicazioni di Unraid ferme, un Febe vero, il lavoro della
pulizia stessa, resti veri e finti di act_runner.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 10:36:59 +02:00

263 lines
13 KiB
C#

using System.Text.RegularExpressions;
using Febe.Tests.Desktop.Support;
using Febe.Tests.Support;
namespace Febe.Tests.Packaging;
/// <summary>
/// The CI of the repository (.gitea/workflows/verifica.yml, pulizia.yml and the scripts of .gitea/scripts), read as
/// text: the rules that must survive later edits. Every push of every branch is verified and nothing else triggers
/// it twice; the tests run only through tests/Febe.Tests, with the browser, and again with the seed of the run; the
/// image is published only from main and never as :latest; credentials are never printed; the external tools are
/// pinned and checked; the tried container never has a network. The cleanup, which runs against fake docker and curl
/// clients, is in PipelineTests.Pulizia.cs.
/// </summary>
[TestClass]
public sealed partial class PipelineTests
{
private static readonly string[] Jobs = ["controlli", "prove", "installatore", "immagine"];
public TestContext TestContext { get; set; } = null!;
[TestMethod]
public void EveryPushOfEveryBranchIsVerifiedOnceAndTagsAreLeftToTheRelease()
{
var workflow = Workflow("verifica.yml");
StringAssert.Contains(workflow, "on:\n push:\n branches: [\"**\"]\n workflow_dispatch:");
var code = Code(workflow);
Assert.DoesNotContain("pull_request", code, "a PR shows the status of its head commit, already verified by the push");
Assert.DoesNotContain("tags:", code, "tags belong to rilascio.yml");
StringAssert.Contains(code, "cancel-in-progress: ${{ gitea.ref != 'refs/heads/main' }}", "every merge into main runs to the end");
// A run started by hand never cancels the run of a push: only that one writes the statuses a merge needs.
StringAssert.Contains(code, "group: verifica-${{ gitea.event_name }}-${{ gitea.ref }}");
}
[TestMethod]
public void TheJobsFollowOneAnotherAndEachHasATimeout()
{
var workflow = Workflow("verifica.yml");
foreach (var job in Jobs)
{
StringAssert.Contains(Job(workflow, job), "timeout-minutes:", job);
}
StringAssert.Contains(Job(workflow, "prove"), "needs: controlli");
StringAssert.Contains(Job(workflow, "installatore"), "needs: prove");
StringAssert.Contains(Job(workflow, "immagine"), "needs: [prove, installatore]", ":main comes only from a commit whose whole verification is green");
foreach (var other in new[] { "rilascio.yml", "pulizia.yml" })
{
var text = Workflow(other);
foreach (Match job in JobHeader().Matches(text))
{
StringAssert.Contains(Job(text, job.Groups["name"].Value), "timeout-minutes:", $"{other}: {job.Groups["name"].Value}");
}
}
}
[TestMethod]
public void TheWholeSolutionIsBuiltAndTheTestsRunOnlyThroughTheTestProjectWithTheBrowser()
{
var prove = Job(Workflow("verifica.yml"), "prove");
StringAssert.Contains(prove, "container:\n image: node:24-trixie", "Debian: Chromium is a real package there, a snap on Ubuntu");
StringAssert.Contains(prove, "bash .gitea/scripts/ambiente-prove.sh");
StringAssert.Contains(prove, "dotnet build Febe.slnx -c Release -nologo -warnaserror");
StringAssert.Contains(prove, "bash .gitea/scripts/riepilogo-prove.sh out/prove 0", "no test may skip itself in the CI");
// The second pass: the tests of the synthetic world again, with the seed of the run in the variable the helper reads.
StringAssert.Contains(prove, $"{SyntheticSite.Variable}: ${{{{ steps.semi.outputs.seme }}}}");
StringAssert.Contains(prove, $"--filter \"TestCategory={SyntheticSite.Category}\"");
var environment = Script("ambiente-prove.sh");
foreach (var package in new[] { "chromium", "xvfb", "ffmpeg", "nsis", "locales" })
{
StringAssert.Contains(environment, package);
}
// tests/Febe.Tests.Windows runs only on Windows: never «dotnet test» on the solution or without a project.
foreach (var name in new[] { "verifica.yml", "rilascio.yml" })
{
foreach (Match test in DotnetTest().Matches(Code(Workflow(name))))
{
Assert.AreEqual("tests/Febe.Tests", test.Groups["target"].Value, $"{name}: {test.Value}");
}
}
}
[TestMethod]
public void TheImageIsPublishedOnlyAfterAPushToMainAsMainAndShaNeverAsLatest()
{
var image = Job(Workflow("verifica.yml"), "immagine");
var decision = Step(image, "Pubblicare?");
StringAssert.Contains(decision, "[ \"$EVENTO\" != push ] || [ \"$RIFERIMENTO\" != refs/heads/main ]");
StringAssert.Contains(decision, "::warning::Manca il segreto REGISTRY_TOKEN");
Assert.DoesNotContain("exit 1", decision, "without the secret the job stays green");
var publish = Step(image, "Pubblicazione come :main e :sha-<commit>");
StringAssert.Contains(publish, "if: steps.segreto.outputs.presente == 'si'");
StringAssert.Contains(publish, "\"$IMAGE:sha-${GITHUB_SHA::7}\"");
StringAssert.Contains(publish, "\"$IMAGE:main\"");
StringAssert.Contains(publish, "bash .gitea/scripts/costruisci-immagine.sh pubblica");
StringAssert.Contains(publish, "| cut -f1) || CIMA=\"\"", "under bash -e an unreadable main must reach the warning and still publish :sha-");
Assert.DoesNotContain(":latest", Code(Workflow("verifica.yml")), ":latest belongs to the release");
// Built with buildx, tried without a network and scanned before anything is published; always cleaned up.
StringAssert.Contains(image, "uses: docker/setup-buildx-action@v3");
StringAssert.Contains(image, "http = true");
StringAssert.Contains(image, "insecure = true");
var decide = image.IndexOf("- name: Pubblicare?", StringComparison.Ordinal);
foreach (var gate in new[] { "bash .gitea/scripts/costruisci-immagine.sh archivio", "bash .gitea/scripts/prova-immagine.sh", "bash .gitea/scripts/scansione-immagine.sh" })
{
var at = image.IndexOf(gate, StringComparison.Ordinal);
Assert.IsTrue(at >= 0 && at < decide, $"«{gate}» comes before the publication");
}
var cleanup = Step(image, "Pulizia (sempre)");
StringAssert.Contains(cleanup, "if: always()");
StringAssert.Contains(cleanup, "bash .gitea/scripts/pulizia-docker.sh esecuzione \"$ESECUZIONE\"");
StringAssert.Contains(cleanup, ".auths |= del(.[$r])", "the credentials leave the client configuration");
}
[TestMethod]
public void SecretsAreNeverPrintedNorTheDaemonUsedForTheRegistry()
{
foreach (var (name, text) in AllCiFiles())
{
var code = Code(text);
Assert.DoesNotContain("docker login", code, name);
Assert.DoesNotContain("docker push", code, name);
Assert.IsFalse(Trace().IsMatch(code), $"{name}: no shell tracing (it would print secrets)");
// A secret goes into echo or printf only to be piped or redirected, never to the log.
foreach (var line in code.Split('\n').Where(l => Printing().IsMatch(l)))
{
var secret = SecretReference().Match(line);
if (secret.Success)
{
var after = line[secret.Index..];
Assert.IsTrue(after.Contains('|', StringComparison.Ordinal) || after.Contains('>', StringComparison.Ordinal), $"{name}: «{line.Trim()}» would print a secret");
}
}
}
}
[TestMethod]
public void TheExternalToolsArePinnedAndCheckedAndNoThirdPartyActionRunsThem()
{
var tool = Script("strumento.sh");
StringAssert.Contains(tool, "versione=\"8.30.1\"");
StringAssert.Contains(tool, "versione=\"0.75.0\"");
Assert.HasCount(2, Sha256().Matches(tool), "one SHA-256 per tool");
StringAssert.Contains(tool, "sha256sum -c");
Assert.DoesNotContain("latest", Code(tool));
foreach (var (name, text) in AllCiFiles())
{
Assert.DoesNotContain("trivy-action", Code(text), name);
Assert.DoesNotContain("gitleaks-action", Code(text), name);
}
var secrets = Script("segreti.sh");
StringAssert.Contains(secrets, "--redact");
StringAssert.Contains(Job(Workflow("verifica.yml"), "controlli"), "fetch-depth: 0");
var scan = Script("scansione-immagine.sh");
StringAssert.Contains(scan, "--severity CRITICAL --ignore-unfixed");
StringAssert.Contains(scan, "--exit-code 1");
}
[TestMethod]
public void TheTriedContainerNeverHasANetworkAndAlwaysCarriesTheMarkNoImageHas()
{
var smoke = Code(Script("prova-immagine.sh"));
var runs = DockerRun().Matches(smoke);
Assert.IsGreaterThanOrEqualTo(4, runs.Count);
foreach (Match run in runs)
{
StringAssert.Contains(run.Value, "--network none", "rule 1: the image under test cannot reach any site");
StringAssert.Contains(run.Value, "\"${etichette[@]}\"", "every tried container carries the mark the cleanup looks for");
}
StringAssert.Contains(smoke, "etichette=(--label \"febe.ci.prova=$esecuzione\")");
StringAssert.Contains(smoke, "nome=\"febe-prova-$esecuzione\"");
// Docker copies the labels of an image into every container made from it: the mark must never be in an image.
Assert.DoesNotContain("febe.ci.prova", Code(Script("costruisci-immagine.sh")));
Assert.DoesNotContain("febe.ci.prova", Code(Read(Repository.PathOf("docker", "Dockerfile"))));
}
/// <summary>bash for the scripts of the CI: the system one on Linux, Git Bash on Windows (not the one of WSL).</summary>
private static string? BashForScripts()
{
if (OperatingSystem.IsWindows())
{
var git = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "Git", "bin", "bash.exe");
return File.Exists(git) ? git : null;
}
return new[] { "/bin/bash", "/usr/bin/bash" }.FirstOrDefault(File.Exists);
}
/// <summary>The workflows and the scripts of the CI, by name.</summary>
private static List<(string Name, string Text)> AllCiFiles() =>
[.. Directory.EnumerateFiles(CiPath("workflows")).Concat(Directory.EnumerateFiles(CiPath("scripts")))
.Select(file => (Path.GetFileName(file), Read(file)))];
private static string Workflow(string name) => Read(CiPath("workflows", name));
private static string Script(string name) => Read(CiPath("scripts", name));
private static string Read(string path) => File.ReadAllText(path).Replace("\r\n", "\n", StringComparison.Ordinal);
/// <summary>A path under .gitea; inconclusive in the build of the image, whose context leaves .gitea out.</summary>
private static string CiPath(params string[] parts)
{
var path = Repository.PathOf([".gitea", .. parts]);
var root = Repository.Root()!;
if (!File.Exists(path) && !Directory.Exists(path) && !Directory.Exists(Path.Combine(root, ".git")) && !File.Exists(Path.Combine(root, ".git")))
{
Assert.Inconclusive("Questa copia del repository non ha .gitea/ (costruzione dell'immagine Docker).");
}
return path;
}
/// <summary>The text without comment lines (YAML and shell): what runs, not what the comments say.</summary>
private static string Code(string text) =>
string.Join('\n', text.Replace("\r\n", "\n", StringComparison.Ordinal).Split('\n').Where(line => !line.TrimStart().StartsWith('#')));
/// <summary>The block of a job: from « name:» to the next job.</summary>
private static string Job(string workflow, string name)
{
var match = Regex.Match(workflow, $@"^ {Regex.Escape(name)}:\n(?<body>(?:(?: .*|\s*)\n)*)", RegexOptions.Multiline);
Assert.IsTrue(match.Success, $"manca il lavoro {name}");
return match.Groups["body"].Value;
}
/// <summary>The block of a step, from its «- name:» to the next step.</summary>
private static string Step(string job, string name)
{
var start = job.IndexOf("- name: " + name, StringComparison.Ordinal);
Assert.IsGreaterThanOrEqualTo(0, start, $"manca il passo «{name}»");
var next = job.IndexOf("\n - ", start + 1, StringComparison.Ordinal);
return next < 0 ? job[start..] : job[start..next];
}
[GeneratedRegex(@"(?<=^jobs:\n(?:.*\n)*?)^ (?<name>[a-z][\w-]*):$", RegexOptions.Multiline)]
private static partial Regex JobHeader();
[GeneratedRegex(@"dotnet test(?:\s+(?<target>[^\s-][^\s]*))?")]
private static partial Regex DotnetTest();
[GeneratedRegex(@"(?m)^\s*set\s+-[a-wyz]*x|\bbash\s+-x\b")]
private static partial Regex Trace();
[GeneratedRegex(@"\b(?:echo|printf)\b")]
private static partial Regex Printing();
[GeneratedRegex(@"\$\{?(?:TOKEN|FEBE_PASSWORD|AUTH|REGISTRY_TOKEN|PASSWORD)\b")]
private static partial Regex SecretReference();
[GeneratedRegex(@"\b[0-9a-f]{64}\b")]
private static partial Regex Sha256();
[GeneratedRegex(@"docker run\b(?:[^\n]*\\\n)*[^\n]*")]
private static partial Regex DockerRun();
}