Files
Febe/tests/Febe.Tests/Packaging/ImageContentsTests.cs
T
Alby96andClaude Opus 5.5 525d7dfdaa Immagine Docker con solo Chromium, Xvfb e ciò che serve a .NET; Febe processo 1 senza tini (C6, 4/4)
Decisione di Alberto del 18 novembre 2026: nell'immagine solo Chromium con i
pacchetti di Debian che gli servono, Xvfb e ciò che serve al runtime .NET.

- Ogni pacchetto della lista ha il suo motivo accanto nel Dockerfile e nella
  tabella nuova di docs/docker.md. Controllato sulle librerie native di .NET 10:
  zlib non serve più a .NET ma resta perché la chiede chromium; i caratteri
  restano perché senza Chromium non scrive (DejaVu per fontconfig, Liberation
  per le misure di Arial e Helvetica, Noto per le emoji).
- Tolti tini, util-linux e passwd dalla lista: setpriv, groupadd, useradd e
  getent sono già nell'immagine di base, e la costruzione si ferma se uno manca.
- Il processo 1 è Febe: l'avvio cede il posto con exec, e il runtime .NET da
  processo 1 raccoglie i processi orfani. La prova dell'immagine controlla che
  il processo 1 sia febe e che non restino zombie suoi figli.
- La riga di ffmpeg resta com'era: la toglie il ramo funzione/decoder-h264.
- Nuova ImageContentsTests: rifiuta un pacchetto fuori elenco o senza motivo,
  il ritorno di tini e una consegna senza exec nell'avvio.

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

221 lines
10 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.Text.RegularExpressions;
using Febe.Tests.Desktop.Support;
namespace Febe.Tests.Packaging;
/// <summary>
/// What the Docker image installs (spec §11, Alberto's decision of 18 November 2026): only Chromium with the Debian
/// packages it needs, Xvfb and what the .NET runtime needs, each with its reason next to the list and in docs/docker.md;
/// Febe itself is process 1, without tini.
/// </summary>
[TestClass]
public sealed partial class ImageContentsTests
{
/// <summary>Every package the runtime stage may name, and why (the same reasons the Dockerfile gives).</summary>
private static readonly Dictionary<string, string> Allowed = new(StringComparer.Ordinal)
{
["chromium"] = "the browser",
["chromium-l10n"] = "Chromium's languages: with LANG=it_IT.UTF-8 menus and Accept-Language are Italian",
["xvfb"] = "the virtual display: Chromium is never headless",
["libicu76"] = ".NET globalization (InvariantGlobalization is false)",
["libssl3t64"] = ".NET TLS and AES-GCM",
["libstdc++6"] = "loaded by libcoreclr, libclrjit and libhostfxr",
["libgcc-s1"] = ".NET and Chromium",
["zlib1g"] = "a direct dependency of Chromium",
["fonts-dejavu-core"] = "the first font fontconfig asks for",
["fonts-liberation"] = "Arial, Helvetica and Times with the same metrics",
["fonts-noto-color-emoji"] = "emoji in the remote view",
["ca-certificates"] = "certificate authorities for .NET TLS",
["tzdata"] = "time zones for the engine and Chromium",
["locales"] = "generates it_IT.UTF-8 for the C library Chromium runs with",
};
/// <summary>
/// Still installed on this line of work and removed by stages C2–C3 (branch funzione/decoder-h264), which also
/// remove its lines from the Dockerfile. Tolerated, never required: drop it from here once that branch is merged.
/// </summary>
private static readonly HashSet<string> PendingRemoval = ["ffmpeg"];
/// <summary>Without these the image does not work: the browser, its display, and what .NET loads.</summary>
private static readonly string[] Required = ["chromium", "chromium-l10n", "xvfb", "libicu76", "libssl3t64", "ca-certificates", "tzdata", "locales"];
/// <summary>Programs that must not come back: an init of others, privilege tools, downloaders, other runtimes.</summary>
private static readonly string[] Forbidden = ["tini", "dumb-init", "gosu", "su-exec", "sudo", "curl", "wget", "nodejs", "npm", "python3"];
[TestMethod]
public void TheImageInstallsOnlyChromiumWhatItNeedsXvfbAndWhatTheDotNetRuntimeNeeds()
{
var installed = InstalledPackages(RuntimeStage());
Assert.HasCount(installed.Distinct(StringComparer.Ordinal).Count(), installed, "every package once");
foreach (var package in installed)
{
Assert.IsTrue(Allowed.ContainsKey(package) || PendingRemoval.Contains(package), $"pacchetto fuori dall'elenco ammesso: {package}");
}
foreach (var package in Required)
{
CollectionAssert.Contains(installed, package);
}
foreach (var package in Forbidden)
{
CollectionAssert.DoesNotContain(installed, package);
}
// Only the runtime stage installs anything with apt: the build stages use the SDK image as it is.
var dockerfile = Dockerfile();
Assert.AreEqual(1, Regex.Matches(Code(dockerfile), @"apt-get install").Count, "a single apt-get install, in the runtime stage");
}
[TestMethod]
public void EveryInstalledPackageHasItsReasonNextToTheList()
{
var stage = RuntimeStage();
var installed = InstalledPackages(stage).Where(p => !PendingRemoval.Contains(p)).ToHashSet(StringComparer.Ordinal);
var reasons = new HashSet<string>(StringComparer.Ordinal);
foreach (Match match in ReasonLine().Matches(stage))
{
foreach (var name in match.Groups["names"].Value.Split(' ', StringSplitOptions.RemoveEmptyEntries))
{
Assert.IsTrue(reasons.Add(name), $"motivo ripetuto per {name}");
}
}
foreach (var package in installed)
{
Assert.Contains(package, reasons, $"manca il motivo di {package} accanto alla lista");
}
foreach (var name in reasons)
{
Assert.Contains(name, installed, $"motivo di un pacchetto che non si installa: {name}");
}
}
[TestMethod]
public void TheGuideGivesTheSameReasonsForTheSamePackages()
{
var path = Repository.PathOf("docs", "docker.md");
if (!File.Exists(path))
{
Assert.Inconclusive("Questa copia del repository non ha docs/ (costruzione dell'immagine Docker).");
}
var guide = File.ReadAllText(path).Replace("\r\n", "\n", StringComparison.Ordinal);
var start = guide.IndexOf("### Perché c'è ogni pacchetto", StringComparison.Ordinal);
Assert.IsGreaterThanOrEqualTo(0, start, "docs/docker.md has the table of the packages");
var end = guide.IndexOf("\n## ", start, StringComparison.Ordinal);
var section = end < 0 ? guide[start..] : guide[start..end];
var listed = new HashSet<string>(StringComparer.Ordinal);
foreach (Match row in GuideRow().Matches(section))
{
foreach (Match name in BacktickedName().Matches(row.Groups["names"].Value))
{
Assert.IsTrue(listed.Add(name.Groups["name"].Value), name.Value);
}
}
var installed = InstalledPackages(RuntimeStage()).Where(p => !PendingRemoval.Contains(p)).ToHashSet(StringComparer.Ordinal);
Assert.IsTrue(installed.SetEquals(listed), $"Dockerfile: {string.Join(' ', installed.Order())}; guida: {string.Join(' ', listed.Order())}");
}
[TestMethod]
public void FebeIsProcessOneWithoutTini()
{
var dockerfile = Dockerfile();
var code = Code(dockerfile);
StringAssert.Contains(code, "ENTRYPOINT [\"/usr/local/bin/febe-avvio\"]");
StringAssert.Contains(code, "CMD [\"/app/febe\"]");
StringAssert.Contains(code, "STOPSIGNAL SIGTERM");
foreach (var program in Forbidden)
{
Assert.IsFalse(Regex.IsMatch(code, $@"(?<![\w.-]){Regex.Escape(program)}(?![\w.-])"), $"{program} nel Dockerfile");
}
// Process 1 stays Febe only if the start hands over with exec every time, never as a child.
var entrypoint = Code(File.ReadAllText(Repository.PathOf("docker", "entrypoint.sh")));
var handovers = entrypoint.Split('\n').Where(line => line.Contains("\"$@\"", StringComparison.Ordinal)).Select(line => line.Trim()).ToList();
CollectionAssert.AreEqual(
new[] { "exec \"$@\"", "exec setpriv --reuid=\"${PUID}\" --regid=\"${PGID}\" --init-groups \"$@\"" },
handovers);
}
[TestMethod]
public void TheToolsTheStartUsesComeWithTheBaseImageAndTheBuildChecksThem()
{
var code = Code(Dockerfile());
StringAssert.Contains(code, "for comando in setpriv groupadd useradd getent; do");
var entrypoint = Code(File.ReadAllText(Repository.PathOf("docker", "entrypoint.sh")));
foreach (var tool in new[] { "setpriv", "groupadd", "useradd", "getent" })
{
StringAssert.Contains(entrypoint, tool + " ");
}
}
[TestMethod]
public void TheReasonsOfThePackagesStillHold()
{
// ICU: the server keeps the culture-aware globalization (dates and sorting in Italian).
var server = File.ReadAllText(Repository.PathOf("src", "Febe.Server", "Febe.Server.csproj"));
StringAssert.Contains(server, "<InvariantGlobalization>false</InvariantGlobalization>");
// chromium-l10n and locales: the browser takes its language from LANG, never from a command-line switch.
var code = Code(Dockerfile());
StringAssert.Contains(code, "LANG=it_IT.UTF-8");
StringAssert.Contains(code, "it_IT.UTF-8 UTF-8");
StringAssert.Contains(code, "FEBE_CHROMIUM=/usr/bin/chromium");
}
private static string Dockerfile() =>
File.ReadAllText(Repository.PathOf("docker", "Dockerfile")).Replace("\r\n", "\n", StringComparison.Ordinal);
/// <summary>From the FROM of the runtime stage to the end.</summary>
private static string RuntimeStage()
{
var dockerfile = Dockerfile();
var start = dockerfile.IndexOf("\nFROM debian:", StringComparison.Ordinal);
Assert.IsGreaterThanOrEqualTo(0, start, "the runtime stage starts from Debian");
StringAssert.Contains(dockerfile[start..dockerfile.IndexOf('\n', start + 1)], " AS runtime");
return dockerfile[start..];
}
/// <summary>The packages of the apt-get install of <paramref name="stage"/>, in order, without options and comments.</summary>
private static List<string> InstalledPackages(string stage)
{
var start = stage.IndexOf("apt-get install", StringComparison.Ordinal);
Assert.IsGreaterThanOrEqualTo(0, start, "the runtime stage installs with apt-get install");
var end = stage.IndexOf("&&", start, StringComparison.Ordinal);
Assert.IsGreaterThan(start, end);
var packages = new List<string>();
foreach (var line in Code(stage[start..end]).Split('\n'))
{
foreach (var word in line.Replace('\\', ' ').Split(' ', StringSplitOptions.RemoveEmptyEntries))
{
if (word is not ("apt-get" or "install") && !word.StartsWith('-'))
{
packages.Add(word);
}
}
}
Assert.IsNotEmpty(packages);
return packages;
}
/// <summary>The text without comment lines (a Dockerfile drops them even inside a continued RUN).</summary>
private static string Code(string text) =>
string.Join('\n', text.Split('\n').Where(line => !line.TrimStart().StartsWith('#')));
/// <summary>«# name [name] reason»: a line of the list of reasons (continuation lines start further right).</summary>
[GeneratedRegex(@"^# (?<names>[a-z0-9][a-z0-9.+-]*(?: [a-z0-9][a-z0-9.+-]*)*) {2,}\S", RegexOptions.Multiline)]
private static partial Regex ReasonLine();
/// <summary>A row of the table in docs/docker.md: «| `name`, `name` | reason |».</summary>
[GeneratedRegex(@"^\| (?<names>`[^|]+) \| [^|]+\|$", RegexOptions.Multiline)]
private static partial Regex GuideRow();
[GeneratedRegex(@"`(?<name>[^`]+)`")]
private static partial Regex BacktickedName();
}