Files
Febe/tests/Febe.Tests/Packaging/PipelineTests.cs
Alby96andClaude Opus 5.5 b23632fc96 Fotogrammi e contenitori più robusti dopo la revisione: punto di partenza vero, limiti di tempo e di riferimenti, file rovinati tollerati (#58)
Corregge i difetti confermati dalla revisione del decodificatore H.264 e dei lettori
di contenitori.

- Fotogrammi: un AVI senza idx1 (o OpenDML oltre il primo GB) segna ogni campione
  come chiave; ora si parte dall'immagine IDR più vicina (entro 300 campioni),
  altrimenti da un'immagine di slice I o dal primo campione. Oltre 300 campioni vale
  il fotogramma del punto di partenza; ogni chiamata ha al più 30 secondi, come
  l'estrattore con ffmpeg che sostituisce.
- H.264: una slice P/B senza riferimenti è un errore invece di una predizione da sé
  stessa; SPS con riferimenti oltre MaxDpbMbs del livello 6.2 rifiutato (1,4 GB da
  pochi byte); FrameNumOffset dei fotogrammi mancanti di un salto di frame_num;
  immagini ridondanti saltate e inizio d'immagine secondo §7.4.1.2.4; immagini non di
  riferimento non chieste non ricostruite; CABAC con finestra di 64 bit; unità NAL in
  un solo buffer. Il sommario non dice più verificato ciò che nessun MD5 verifica.
- Matroska: un blocco rovinato o troncato ferma la lettura e i blocchi letti restano;
  scala dei tempi esatta per ogni TimecodeScale.
- MP4: una traccia con tkhd/elst/mdhd/hdlr/esds rovinati si scarta senza perdere le
  altre; esds con limiti controllati; nei soli metadati niente copie delle tabelle né
  campioni dei frammenti.
- AVI: durata impossibile ignota senza perdere la data.
- Sonda dei metadati davvero asincrona, annullabile fra i frammenti.
- Prove nuove: flussi H.264 sintetici scritti bit per bit (salto di frame_num, immagine
  ridondante, P senza riferimenti, immagini saltate, SPS enormi con PPS e slice),
  AVI senza indice, blocchi Matroska rovinati, audio MP4 rovinato, durata AVI,
  TimecodeScale di 3 ms, trun sotto il limite ma oltre il file, limite di run e di
  tempo, i due MP4 x264 del sito di prova, ffmpeg/ffprobe fuori dal Dockerfile.
  Provate contro il codice senza le correzioni: falliscono tutte.
- decisioni.md: quattro righe del 18 novembre.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 14:13:45 +01:00

271 lines
14 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", "nsis", "locales" })
{
StringAssert.Contains(environment, package);
}
// Videos are read and decoded in house: no ffmpeg in the CI, nor in the image (Alberto, 18 November 2026).
var image = Code(Read(Repository.PathOf("docker", "Dockerfile")));
foreach (var program in new[] { "ffmpeg", "ffprobe" })
{
Assert.IsFalse(environment.Contains(program, StringComparison.Ordinal), $"{program} non serve più alle prove");
Assert.IsFalse(image.Contains(program, StringComparison.Ordinal), $"{program} non va nell'immagine");
}
// 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();
}