La verifica girava solo su main e su un ramo che non esiste più, e saltava le 66 prove con browser, ffmpeg e makensis. Ora gira a ogni push su qualunque ramo (e a mano), in quattro lavori: controlli veloci e gitleaks su tutta la storia; compilazione di tutta la soluzione e tutte le prove di tests/Febe.Tests in un contenitore Debian con Chromium, Xvfb, ffmpeg, NSIS e Node veri, senza prove saltate, con il seme 13 e di nuovo con il seme dell'esecuzione per le prove del sito di prova; installatore e zip con la versione -ci.<numero> come artefatti per 14 giorni; immagine costruita con buildx, provata senza rete, scansionata con Trivy e, solo dopo un push su main e con il segreto, pubblicata come :main e :sha-<commit>. Senza il segreto un avviso e il lavoro resta verde; alla fine si toglie sempre ciò che l'esecuzione ha creato. Niente pull_request, che rifarebbe tutto sullo stesso commit. Le prove sui flussi tengono ferme queste regole. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
259 lines
13 KiB
C#
259 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 cleanup touches only what the CI of Febe made; the tried container never has a network.
|
|
/// </summary>
|
|
[TestClass]
|
|
public sealed partial class PipelineTests
|
|
{
|
|
private static readonly string[] Jobs = ["controlli", "prove", "installatore", "immagine"];
|
|
|
|
[TestMethod]
|
|
public void EveryPushOfEveryBranchIsVerifiedOnceAndTagsAreLeftToTheRelease()
|
|
{
|
|
var workflow = Workflow("verifica.yml");
|
|
StringAssert.Contains(workflow, "on:\n push:\n branches: [\"**\"]\n workflow_dispatch:");
|
|
var code = Code(workflow);
|
|
Assert.DoesNotContain("pull_request", code, "a PR shows the status of its head commit, already verified by the push");
|
|
Assert.DoesNotContain("tags:", code, "tags belong to rilascio.yml");
|
|
StringAssert.Contains(code, "cancel-in-progress: ${{ gitea.ref != 'refs/heads/main' }}", "every merge into main runs to the end");
|
|
}
|
|
|
|
[TestMethod]
|
|
public void TheJobsFollowOneAnotherAndEachHasATimeout()
|
|
{
|
|
var workflow = Workflow("verifica.yml");
|
|
foreach (var job in Jobs)
|
|
{
|
|
StringAssert.Contains(Job(workflow, job), "timeout-minutes:", job);
|
|
}
|
|
|
|
StringAssert.Contains(Job(workflow, "prove"), "needs: controlli");
|
|
StringAssert.Contains(Job(workflow, "installatore"), "needs: prove");
|
|
StringAssert.Contains(Job(workflow, "immagine"), "needs: prove");
|
|
foreach (var other in new[] { "rilascio.yml", "pulizia.yml" })
|
|
{
|
|
var text = Workflow(other);
|
|
foreach (Match job in JobHeader().Matches(text))
|
|
{
|
|
StringAssert.Contains(Job(text, job.Groups["name"].Value), "timeout-minutes:", $"{other}: {job.Groups["name"].Value}");
|
|
}
|
|
}
|
|
}
|
|
|
|
[TestMethod]
|
|
public void TheWholeSolutionIsBuiltAndTheTestsRunOnlyThroughTheTestProjectWithTheBrowser()
|
|
{
|
|
var prove = Job(Workflow("verifica.yml"), "prove");
|
|
StringAssert.Contains(prove, "container:\n image: node:24-trixie", "Debian: Chromium is a real package there, a snap on Ubuntu");
|
|
StringAssert.Contains(prove, "bash .gitea/scripts/ambiente-prove.sh");
|
|
StringAssert.Contains(prove, "dotnet build Febe.slnx -c Release -nologo -warnaserror");
|
|
StringAssert.Contains(prove, "bash .gitea/scripts/riepilogo-prove.sh out/prove 0", "no test may skip itself in the CI");
|
|
|
|
// The second pass: the tests of the synthetic world again, with the seed of the run in the variable the helper reads.
|
|
StringAssert.Contains(prove, $"{SyntheticSite.Variable}: ${{{{ steps.semi.outputs.seme }}}}");
|
|
StringAssert.Contains(prove, $"--filter \"TestCategory={SyntheticSite.Category}\"");
|
|
|
|
var environment = Script("ambiente-prove.sh");
|
|
foreach (var package in new[] { "chromium", "xvfb", "ffmpeg", "nsis", "locales" })
|
|
{
|
|
StringAssert.Contains(environment, package);
|
|
}
|
|
|
|
// tests/Febe.Tests.Windows runs only on Windows: never «dotnet test» on the solution or without a project.
|
|
foreach (var name in new[] { "verifica.yml", "rilascio.yml" })
|
|
{
|
|
foreach (Match test in DotnetTest().Matches(Code(Workflow(name))))
|
|
{
|
|
Assert.AreEqual("tests/Febe.Tests", test.Groups["target"].Value, $"{name}: {test.Value}");
|
|
}
|
|
}
|
|
}
|
|
|
|
[TestMethod]
|
|
public void TheImageIsPublishedOnlyAfterAPushToMainAsMainAndShaNeverAsLatest()
|
|
{
|
|
var image = Job(Workflow("verifica.yml"), "immagine");
|
|
var decision = Step(image, "Pubblicare?");
|
|
StringAssert.Contains(decision, "[ \"$EVENTO\" != push ] || [ \"$RIFERIMENTO\" != refs/heads/main ]");
|
|
StringAssert.Contains(decision, "::warning::Manca il segreto REGISTRY_TOKEN");
|
|
Assert.DoesNotContain("exit 1", decision, "without the secret the job stays green");
|
|
var publish = Step(image, "Pubblicazione come :main e :sha-<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");
|
|
Assert.DoesNotContain(":latest", Code(Workflow("verifica.yml")), ":latest belongs to the release");
|
|
|
|
// Built with buildx, tried without a network and scanned before anything is published; always cleaned up.
|
|
StringAssert.Contains(image, "uses: docker/setup-buildx-action@v3");
|
|
StringAssert.Contains(image, "http = true");
|
|
StringAssert.Contains(image, "insecure = true");
|
|
var decide = image.IndexOf("- name: Pubblicare?", StringComparison.Ordinal);
|
|
foreach (var gate in new[] { "bash .gitea/scripts/costruisci-immagine.sh archivio", "bash .gitea/scripts/prova-immagine.sh", "bash .gitea/scripts/scansione-immagine.sh" })
|
|
{
|
|
var at = image.IndexOf(gate, StringComparison.Ordinal);
|
|
Assert.IsTrue(at >= 0 && at < decide, $"«{gate}» comes before the publication");
|
|
}
|
|
var cleanup = Step(image, "Pulizia (sempre)");
|
|
StringAssert.Contains(cleanup, "if: always()");
|
|
StringAssert.Contains(cleanup, "bash .gitea/scripts/pulizia-docker.sh esecuzione \"$ESECUZIONE\"");
|
|
StringAssert.Contains(cleanup, ".auths |= del(.[$r])", "the credentials leave the client configuration");
|
|
}
|
|
|
|
[TestMethod]
|
|
public void SecretsAreNeverPrintedNorTheDaemonUsedForTheRegistry()
|
|
{
|
|
foreach (var (name, text) in AllCiFiles())
|
|
{
|
|
var code = Code(text);
|
|
Assert.DoesNotContain("docker login", code, name);
|
|
Assert.DoesNotContain("docker push", code, name);
|
|
Assert.IsFalse(Trace().IsMatch(code), $"{name}: no shell tracing (it would print secrets)");
|
|
|
|
// A secret goes into echo or printf only to be piped or redirected, never to the log.
|
|
foreach (var line in code.Split('\n').Where(l => Printing().IsMatch(l)))
|
|
{
|
|
var secret = SecretReference().Match(line);
|
|
if (secret.Success)
|
|
{
|
|
var after = line[secret.Index..];
|
|
Assert.IsTrue(after.Contains('|', StringComparison.Ordinal) || after.Contains('>', StringComparison.Ordinal), $"{name}: «{line.Trim()}» would print a secret");
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
[TestMethod]
|
|
public void TheExternalToolsArePinnedAndCheckedAndNoThirdPartyActionRunsThem()
|
|
{
|
|
var tool = Script("strumento.sh");
|
|
StringAssert.Contains(tool, "versione=\"8.30.1\"");
|
|
StringAssert.Contains(tool, "versione=\"0.75.0\"");
|
|
Assert.HasCount(2, Sha256().Matches(tool), "one SHA-256 per tool");
|
|
StringAssert.Contains(tool, "sha256sum -c");
|
|
Assert.DoesNotContain("latest", Code(tool));
|
|
foreach (var (name, text) in AllCiFiles())
|
|
{
|
|
Assert.DoesNotContain("trivy-action", Code(text), name);
|
|
Assert.DoesNotContain("gitleaks-action", Code(text), name);
|
|
}
|
|
|
|
var secrets = Script("segreti.sh");
|
|
StringAssert.Contains(secrets, "--redact");
|
|
StringAssert.Contains(Job(Workflow("verifica.yml"), "controlli"), "fetch-depth: 0");
|
|
var scan = Script("scansione-immagine.sh");
|
|
StringAssert.Contains(scan, "--severity CRITICAL --ignore-unfixed");
|
|
StringAssert.Contains(scan, "--exit-code 1");
|
|
}
|
|
|
|
[TestMethod]
|
|
public void TheCleanupTouchesOnlyWhatTheCiOfFebeMade()
|
|
{
|
|
var cleanup = Code(Script("pulizia-docker.sh"));
|
|
foreach (var forbidden in new[] { "system prune", "builder prune", "volume prune", "container prune", "image prune -a", "prune --all", "image prune -f -a" })
|
|
{
|
|
Assert.DoesNotContain(forbidden, cleanup, "the daemon is shared with Alberto's other projects");
|
|
}
|
|
|
|
Assert.HasCount(1, ImagePrune().Matches(cleanup), "only dangling images, older than three days");
|
|
StringAssert.Contains(cleanup, "docker image prune -f --filter \"until=72h\"");
|
|
StringAssert.Contains(cleanup, "--filter \"label=febe.ci.run=$run\"");
|
|
StringAssert.Contains(cleanup, "^buildx_buildkit_(febe-ci-[0-9]+)0$");
|
|
|
|
var weekly = Workflow("pulizia.yml");
|
|
StringAssert.Contains(weekly, "schedule:");
|
|
StringAssert.Contains(weekly, "workflow_dispatch:");
|
|
StringAssert.Contains(weekly, "bash .gitea/scripts/pulizia-docker.sh settimanale");
|
|
}
|
|
|
|
[TestMethod]
|
|
public void TheTriedContainerNeverHasANetwork()
|
|
{
|
|
var smoke = Code(Script("prova-immagine.sh"));
|
|
var runs = DockerRun().Matches(smoke);
|
|
Assert.IsGreaterThanOrEqualTo(4, runs.Count);
|
|
foreach (Match run in runs)
|
|
{
|
|
StringAssert.Contains(run.Value, "--network none", "rule 1: the image under test cannot reach any site");
|
|
}
|
|
}
|
|
|
|
/// <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 (?:image|container|volume|builder|system) prune")]
|
|
private static partial Regex ImagePrune();
|
|
|
|
[GeneratedRegex(@"docker run\b(?:[^\n]*\\\n)*[^\n]*")]
|
|
private static partial Regex DockerRun();
|
|
}
|