using System.Text; using System.Text.Json; using System.Text.RegularExpressions; using Febe.Tests.Desktop.Support; using Febe.Tests.Support; namespace Febe.Tests.Packaging; /// /// JSON in the CI without third-party programs (decision of 18 November 2026: only gitleaks and Trivy come from /// outside): .gitea/scripts/json.sh reads with json.awk and json-campi.awk and writes strings with json-stringa.awk, in /// place of jq for the release, the summaries of gitleaks and Trivy and the credentials of the registry. The credentials /// go into a client configuration of the publication only, never into the runner's. Every workflow runs its steps with /// bash, and the release tests run like those of the verification, in Debian with Chromium and no test skipped. /// public sealed partial class PipelineTests { [TestMethod] public void NoJqAnywhereInTheCiNorInTheBuild() { var files = AllCiFiles(); foreach (var path in new[] { Repository.PathOf("installer", "costruisci.sh"), Repository.PathOf("docker", "entrypoint.sh") }) { if (File.Exists(path)) { files.Add((Path.GetFileName(path), Read(path))); } } foreach (var (name, text) in files) { foreach (var line in Code(text).Split('\n')) { Assert.IsFalse(JqWord().IsMatch(line), $"{name}: «{line.Trim()}» uses jq, a program of others"); } } // What took its place is ours: the reader and the writer of json.sh, and nothing edits the client configuration // of the runner any more. StringAssert.Contains(Script("json.sh"), "-f \"$qui/json.awk\" -f \"$qui/json-campi.awk\""); StringAssert.Contains(Script("json.sh"), "awk -f \"$qui/json-stringa.awk\""); var release = Step(Job(Workflow("rilascio.yml"), "release"), "Release con installatore"); StringAssert.Contains(release, "bash .gitea/scripts/json.sh campi \"\" id \"$RISPOSTA\""); StringAssert.Contains(release, "bash .gitea/scripts/json.sh campi \"*\" name \"$RISPOSTA\""); StringAssert.Contains(release, "bash .gitea/scripts/json.sh stringa \"$NOTE\""); StringAssert.Contains(Script("segreti.sh"), "json.sh\" campi \"*\" RuleID,File,StartLine,Commit,Fingerprint"); StringAssert.Contains(Script("scansione-immagine.sh"), "json.sh\" campi \"Results/*/Vulnerabilities/*\" Severity,FixedVersion"); } [TestMethod] public void EveryWorkflowRunsItsStepsWithBash() { foreach (var name in Workflows) { var code = Code(Workflow(name)); StringAssert.Contains(code, "\ndefaults:\n run:\n shell: bash\n", $"{name}: bash -e -o pipefail whatever the default shell of the runner or of the container"); foreach (Match shell in Regex.Matches(code, @"^\s+shell:[ \t]*(?\S*)", RegexOptions.Multiline)) { Assert.AreEqual("bash", shell.Groups["shell"].Value, $"{name}: no step with another shell"); } } } [TestMethod] public void TheReleaseRunsTheTestsLikeTheVerificationWithTheBrowserAndNoneSkipped() { var verification = Job(Workflow("verifica.yml"), "prove"); var release = Job(Workflow("rilascio.yml"), "prove"); foreach (var rule in new[] { "container:\n image: debian:trixie\n options: --shm-size=1g", "FEBE_CHROMIUM: /usr/bin/chromium", "- name: Git e curl per i sorgenti", "bash .gitea/scripts/ambiente-prove.sh", "bash .gitea/scripts/riepilogo-prove.sh out/prove 0", }) { StringAssert.Contains(verification, rule, "verifica.yml: prove"); StringAssert.Contains(release, rule, "rilascio.yml: prove: the release gate exercises what the verification does (the login return among them)"); } var environment = release.IndexOf("bash .gitea/scripts/ambiente-prove.sh", StringComparison.Ordinal); var tests = release.IndexOf("dotnet test tests/Febe.Tests", StringComparison.Ordinal); var summary = release.IndexOf("riepilogo-prove.sh out/prove 0", StringComparison.Ordinal); Assert.IsTrue(environment < tests && tests < summary, "Chromium before the tests, the summary after them"); } [TestMethod] [Timeout(120_000, CooperativeCancellation = true)] public async Task TheJsonOfTheCiIsReadAndWrittenInHouse() { var bash = RequireBash(); CiPath("scripts", "json.sh"); using var folder = new TempFolder("febe-json"); async Task FileAsync(string name, string text) { var path = Path.Combine(folder.Path, name); await File.WriteAllTextAsync(path, text, new UTF8Encoding(false), TestContext.CancellationToken); return path.Replace('\\', '/'); } // The arguments through the environment: Git Bash started from Windows would expand an unquoted «*» itself. async Task<(int Code, string Output, string Errors)> JsonAsync(params string[] arguments) => await RunProcessAsync(bash, ["-c", "args=(); for ((i = 0; i < ARGOMENTI; i++)); do v=\"ARGOMENTO_$i\"; args+=(\"${!v}\"); done; exec bash .gitea/scripts/json.sh \"${args[@]}\""], start => { start.Environment["ARGOMENTI"] = arguments.Length.ToString(System.Globalization.CultureInfo.InvariantCulture); for (var i = 0; i < arguments.Length; i++) { start.Environment[$"ARGOMENTO_{i}"] = arguments[i]; } }); // A release of Gitea: the id at the root, a list inside it that is not read. var release = await FileAsync("release.json", """{"id": 4242, "tag_name": "v0.1.2", "assets": [{"id": 7, "name": "dentro.exe"}], "author": {"id": 3}}"""); var read = await JsonAsync("campi", "", "id", release); Assert.AreEqual(0, read.Code, read.Errors); Assert.AreEqual("4242\n", read.Output); // The assets of a release: one name per line, in order, with spaces; a tab or a line break in a value stays on // its line. A field missing or holding a container is empty; a scalar of the list is not an object. var assets = await FileAsync("assets.json", """[{"name": "Febe-Setup-0.1.2.exe", "size": 9}, {"name": "febe compose.tar.gz", "x": {"name": "no"}}, {"name": "a\tb\nc"}, {"size": [1]}, 3]"""); read = await JsonAsync("campi", "*", "name,size", assets); Assert.AreEqual(0, read.Code, read.Errors); Assert.AreEqual("Febe-Setup-0.1.2.exe\t9\nfebe compose.tar.gz\t\na b c\t\n\t\n", read.Output); // Trivy: every vulnerability of every result, with its fix (empty, null or missing when there is none). var trivy = await FileAsync("trivy.json", """ {"SchemaVersion": 2, "Results": [ {"Target": "debian", "Vulnerabilities": [{"VulnerabilityID": "CVE-1", "Severity": "HIGH", "FixedVersion": ""}, {"VulnerabilityID": "CVE-2", "Severity": "CRITICAL", "FixedVersion": "1.2-3"}]}, {"Target": "Febe.deps.json"}, {"Target": "altro", "Vulnerabilities": [{"Severity": "CRITICAL", "FixedVersion": null}, {"Severity": "CRITICAL"}]}]} """); read = await JsonAsync("campi", "Results/*/Vulnerabilities/*", "Severity,FixedVersion", trivy); Assert.AreEqual(0, read.Code, read.Errors); Assert.AreEqual("HIGH\t\nCRITICAL\t1.2-3\nCRITICAL\tnull\nCRITICAL\t\n", read.Output); // gitleaks: an empty report is an empty list, no line. read = await JsonAsync("campi", "*", "RuleID,File", await FileAsync("vuoto.json", "[]")); Assert.AreEqual((0, string.Empty), (read.Code, read.Output), read.Errors); // Broken JSON: nothing at all on the output (not even what came before the error), the reason, exit 2. A wrong // command line or a missing file too. read = await JsonAsync("campi", "*", "name", await FileAsync("rotto.json", """[{"name": "primo"}, {"name": """)); Assert.AreEqual(2, read.Code); Assert.IsEmpty(read.Output); StringAssert.Contains(read.Errors, "rotto.json"); foreach (var arguments in new[] { new[] { "campi", "*", "na me", release }, ["campi", "/x", "id", release], ["campi", "", "id", release + ".manca"], ["altro"] }) { read = await JsonAsync(arguments); Assert.AreEqual(2, read.Code, string.Join(' ', arguments)); Assert.IsEmpty(read.Output, string.Join(' ', arguments)); } // Writing: any text, as the notes of a release are, comes back identical from a JSON parser. var notes = "## 0.1.2\n\n- «Novità» con \"virgolette\", \\barre\\ e\ttabulazioni, un ritorno\r da solo\n- controllo \u0001 e \u001f, emoji 🙂, ünïcödé\n- fine"; var notesFile = await FileAsync("note.txt", notes); var written = await RunProcessAsync(bash, ["-c", "bash .gitea/scripts/json.sh stringa \"$(cat \"$1\")\"", "bash", notesFile]); Assert.AreEqual(0, written.Code, written.Errors); var literal = written.Output.TrimEnd('\n'); Assert.DoesNotContain("\n", literal, "one line"); Assert.AreEqual(notes, JsonDocument.Parse(literal).RootElement.GetString()); written = await JsonAsync("stringa", ""); Assert.AreEqual("\"\"\n", written.Output, written.Errors); // The body of a release as the step builds it is valid JSON with those values. var body = await RunProcessAsync(bash, ["-c", """ NOTE="$(cat "$1")" printf '{"tag_name":%s,"name":%s,"body":%s,"draft":false,"prerelease":%s}' \ "$(bash .gitea/scripts/json.sh stringa "v0.1.2")" "$(bash .gitea/scripts/json.sh stringa "Febe 0.1.2")" \ "$(bash .gitea/scripts/json.sh stringa "$NOTE")" true """, "bash", notesFile]); Assert.AreEqual(0, body.Code, body.Errors); using var parsed = JsonDocument.Parse(body.Output); Assert.AreEqual("v0.1.2", parsed.RootElement.GetProperty("tag_name").GetString()); Assert.AreEqual(notes, parsed.RootElement.GetProperty("body").GetString()); Assert.IsTrue(parsed.RootElement.GetProperty("prerelease").GetBoolean()); } [TestMethod] [Timeout(120_000, CooperativeCancellation = true)] public async Task TheCredentialsOfTheRegistryLiveOnlyInAConfigurationOfThePublicationAndGoAway() { var bash = RequireBash(); CiPath("scripts", "costruisci-immagine.sh"); using var folder = new TempFolder("febe-credenziali"); var bin = folder.Combine("bin"); var world = folder.Combine("mondo"); var temp = folder.Combine("temp"); var client = folder.Combine("client"); foreach (var made in new[] { bin, world, temp, Path.Combine(client, "cli-plugins"), Path.Combine(client, "buildx") }) { Directory.CreateDirectory(made); } // The runner's own client configuration: another registry, a context; it must come out byte for byte the same. var original = "{\"currentContext\": \"casa\", \"auths\": {\"altro.invalid\": {\"auth\": \"" + Convert.ToBase64String(Encoding.UTF8.GetBytes("altro:altro")) + "\"}}}\n"; await File.WriteAllTextAsync(Path.Combine(client, "config.json"), original, TestContext.CancellationToken); // A docker that records the configuration it is given while it runs. var docker = Path.Combine(bin, "docker"); await File.WriteAllTextAsync(docker, """ #!/usr/bin/env bash world="$FAKE_WORLD" printf 'docker %s\n' "$*" >> "$world/calls" printf '%s\n' "${DOCKER_CONFIG:-}" > "$world/config-dir" printf '%s\n' "${BUILDX_CONFIG:-}" > "$world/buildx-config" if [[ -f "${DOCKER_CONFIG:-/nessuna}/config.json" ]]; then cp "$DOCKER_CONFIG/config.json" "$world/config.json"; fi if [[ -e "${DOCKER_CONFIG:-/nessuna}/cli-plugins" ]]; then echo si > "$world/plugins"; fi exit "${FAKE_EXIT:-0}" """.Replace("\r\n", "\n", StringComparison.Ordinal), TestContext.CancellationToken); if (!OperatingSystem.IsWindows()) { File.SetUnixFileMode(docker, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute); } async Task<(int Code, string Output, string Errors)> PublishAsync(string? token, string exit = "0") { foreach (var file in Directory.EnumerateFiles(world)) { File.Delete(file); } 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/costruisci-immagine.sh", "pubblica", "registro.invalid:3000/alby96/febe:0.1.2"]; var run = await RunProcessAsync(bash, script, start => { start.Environment["FAKE_BIN"] = bin; start.Environment["FAKE_WORLD"] = world.Replace('\\', '/'); start.Environment["FAKE_EXIT"] = exit; start.Environment["RUNNER_TEMP"] = temp.Replace('\\', '/'); start.Environment["DOCKER_CONFIG"] = client.Replace('\\', '/'); start.Environment.Remove("BUILDX_CONFIG"); start.Environment["REGISTRY"] = "registro.invalid:3000"; start.Environment["REGISTRO_UTENTE"] = "Alby96"; start.Environment.Remove("REGISTRO_TOKEN"); if (token is not null) { start.Environment["REGISTRO_TOKEN"] = token; } foreach (var (key, value) in new[] { ("BUILDER", "febe-ci-7"), ("VERSIONE", "0.1.2"), ("GIT_COMMIT", "abc"), ("FLUSSO", "rilascio"), ("ESECUZIONE", "7") }) { start.Environment[key] = value; } }); Assert.DoesNotContain(RegistryToken, run.Output + run.Errors, "the token never reaches the log"); return run; } var published = await PublishAsync(RegistryToken); Assert.AreEqual(0, published.Code, published.Output + published.Errors); var calls = await ReadLinesAsync(Path.Combine(world, "calls")); Assert.HasCount(1, calls); StringAssert.Contains(calls[0], "docker buildx build --builder febe-ci-7 "); StringAssert.Contains(calls[0], "-t registro.invalid:3000/alby96/febe:0.1.2 --push ."); // While buildx ran: a configuration of its own, with only this registry and the context of the runner kept. var directory = (await File.ReadAllTextAsync(Path.Combine(world, "config-dir"), TestContext.CancellationToken)).Trim(); Assert.AreEqual(temp.Replace('\\', '/') + "/febe-docker-7", directory); Assert.AreEqual(client.Replace('\\', '/') + "/buildx", (await File.ReadAllTextAsync(Path.Combine(world, "buildx-config"), TestContext.CancellationToken)).Trim(), "the builders of the run are still found"); Assert.IsTrue(File.Exists(Path.Combine(world, "plugins")), "the plugins of the client (buildx) are still there"); using (var used = JsonDocument.Parse(await File.ReadAllTextAsync(Path.Combine(world, "config.json"), TestContext.CancellationToken))) { var auths = used.RootElement.GetProperty("auths"); Assert.AreEqual(1, auths.EnumerateObject().Count(), "only the registry of Febe"); Assert.AreEqual(Convert.ToBase64String(Encoding.UTF8.GetBytes("Alby96:" + RegistryToken)), auths.GetProperty("registro.invalid:3000").GetProperty("auth").GetString()); Assert.AreEqual("casa", used.RootElement.GetProperty("currentContext").GetString()); } // After it: gone, and the runner's configuration untouched. Assert.IsFalse(Directory.Exists(Path.Combine(temp, "febe-docker-7"))); Assert.AreEqual(original, await File.ReadAllTextAsync(Path.Combine(client, "config.json"), TestContext.CancellationToken)); // A failed push leaves nothing behind either; without the token nothing is attempted. var failed = await PublishAsync(RegistryToken, exit: "1"); Assert.AreNotEqual(0, failed.Code); Assert.IsFalse(Directory.Exists(Path.Combine(temp, "febe-docker-7"))); var refused = await PublishAsync(token: null); Assert.AreEqual(2, refused.Code, refused.Output); Assert.IsFalse(File.Exists(Path.Combine(world, "calls"))); Assert.AreEqual(original, await File.ReadAllTextAsync(Path.Combine(client, "config.json"), TestContext.CancellationToken)); // The steps leave the credentials to the script, and the cleanup that always runs removes its folder. foreach (var (name, job, step) in new[] { ("verifica.yml", "immagine", "Pubblicazione come :main e :sha-"), ("rilascio.yml", "immagine", "Pubblicazione sul registro di Gitea") }) { var text = Job(Workflow(name), job); var publish = Step(text, step); StringAssert.Contains(publish, "REGISTRO_TOKEN: ${{ secrets.REGISTRY_TOKEN }}", name); Assert.DoesNotContain("config.json", Code(publish), $"{name}: the runner's client configuration is never edited"); StringAssert.Contains(Step(text, "Pulizia (sempre)"), "rm -rf \"${RUNNER_TEMP:-/tmp}/febe-docker-$ESECUZIONE\"", name); } } [GeneratedRegex(@"\bjq\b")] private static partial Regex JqWord(); }