using System.Buffers.Binary; using System.Collections; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Text.RegularExpressions; using System.Xml.Linq; using Anubis.Platform; using Anubis.Server; using Anubis.Supervision; namespace Anubis.Tests; /// What is delivered: the Unraid template, the image and how it is published (issues #70 and #71, SPEC 15.2, 15.3, 15.5). [TestClass] public sealed partial class DeliveryTests { private const string Image = "gitea.encke-hake.ts.net/balbosoft/anubis"; private static string Text(string path) => File.ReadAllText(Path.Combine(Repo.Root.FullName, path.Replace('/', Path.DirectorySeparatorChar))).ReplaceLineEndings("\n"); private static string Section(string from, string to) { var spec = Text("docs/SPEC.md"); var start = spec.IndexOf("\n" + from, StringComparison.Ordinal); Assert.IsGreaterThan(0, start, from); var end = spec.IndexOf("\n" + to, start + 1, StringComparison.Ordinal); return end < 0 ? spec[start..] : spec[start..end]; } private static XElement Template() => XDocument.Parse(Text("deploy/unraid/anubis.xml")).Root!; private static Dictionary Fields(XElement template) { var fields = new Dictionary(StringComparer.Ordinal); foreach (var config in template.Elements("Config")) { Assert.IsTrue(fields.TryAdd(config.Attribute("Target")!.Value, config), "Twice: " + config); } return fields; } private static HashSet VariablesOf151() => VariableName().Matches(string.Join('\n', Section("### 15.1", "### 15.2").Split('\n').Where(l => l.StartsWith("| `", StringComparison.Ordinal)).Select(l => l.Split('|')[1]))) .Select(m => m.Groups[1].Value).ToHashSet(StringComparer.Ordinal); // ---- the Unraid template ---- [TestMethod] [TestCategory(Category.Unit)] public void TheTemplateHasTheFieldsOfAppendixE() { var template = Template(); Assert.AreEqual("Container", template.Name.LocalName); Assert.AreEqual("2", template.Attribute("version")!.Value); var appendix = Section("## Appendice E", "## Appendice F"); var draft = appendix[(appendix.IndexOf("```xml\n", StringComparison.Ordinal) + 7)..]; var expected = Fields(XDocument.Parse(draft[..draft.IndexOf("\n```", StringComparison.Ordinal)]).Root!); var actual = Fields(template); CollectionAssert.AreEquivalent(expected.Keys.ToList(), actual.Keys.ToList()); foreach (var (target, field) in expected) { foreach (var name in new[] { "Type", "Mode", "Display", "Required", "Default", "Mask" }) { // The address of the heartbeat is a secret of its service: masked, unlike the draft (ADR 0020). var want = (target, name) == ("ANUBIS_HEARTBEAT_URL", "Mask") ? "true" : field.Attribute(name)!.Value; Assert.AreEqual(want, actual[target].Attribute(name)!.Value, target + " " + name); } Assert.AreEqual(field.Value, actual[target].Value, target); Assert.IsFalse(string.IsNullOrWhiteSpace(actual[target].Attribute("Description")!.Value), target); } } [TestMethod] [TestCategory(Category.Unit)] public void EveryVariableOfTheTemplateIsIn151AndTheAccountKeysAreNot() { var known = VariablesOf151(); Assert.IsGreaterThan(20, known.Count); var targets = Fields(Template()).Where(f => f.Value.Attribute("Type")!.Value == "Variable").Select(f => f.Key).ToList(); Assert.HasCount(16, targets); CollectionAssert.IsSubsetOf(targets, known.ToList()); Assert.IsEmpty(targets.Where(t => t.StartsWith("ALPACA", StringComparison.Ordinal) || t.StartsWith("OKX", StringComparison.Ordinal) || t.EndsWith("_API_KEY", StringComparison.Ordinal))); } [TestMethod] [TestCategory(Category.Unit)] public void TheTemplateMasksSecretsAndHidesRareFields() { var fields = Fields(Template()); foreach (var secret in new[] { "ANUBIS_DB_PASSWORD", "ANUBIS_SECRET_KEY", "ANUBIS_ADMIN_PASSWORD", "TELEGRAM_BOT_TOKEN", "ANUBIS_DB_URL", "ANUBIS_HEARTBEAT_URL" }) { Assert.AreEqual("true", fields[secret].Attribute("Mask")!.Value, secret); Assert.AreEqual("", fields[secret].Value, secret); } foreach (var rare in new[] { "ANUBIS_ALLOW_LIVE", "TELEGRAM_BOT_TOKEN", "TELEGRAM_CHAT_ID", "ANUBIS_HEARTBEAT_URL", "PUID", "PGID", "ANUBIS_DB_URL" }) { Assert.AreEqual("advanced", fields[rare].Attribute("Display")!.Value, rare); } Assert.AreEqual("0", fields["ANUBIS_ALLOW_LIVE"].Value); Assert.AreEqual("postgres|sqlite", fields["ANUBIS_DB_ENGINE"].Attribute("Default")!.Value); } [TestMethod] [TestCategory(Category.Unit)] public void TheTemplatePointsToTheRealImage() { var template = Template(); var text = Text("deploy/unraid/anubis.xml"); Assert.DoesNotContain("example", text); Assert.DoesNotContain("UTENTE", text); Assert.DoesNotContain("bozza", text); Assert.AreEqual(Image + ":latest", template.Element("Repository")!.Value); StringAssert.Contains(Text("tools/Anubis.Tasks/Program.cs"), Image + ":"); StringAssert.Contains(Text("deploy/docker/publish.sh"), "$REGISTRY/balbosoft/anubis"); var fields = Fields(template); Assert.AreEqual("8787", fields["8787"].Value); Assert.AreEqual("/mnt/user/appdata/anubis", fields["/data"].Value); var extra = template.Element("ExtraParams")!.Value; StringAssert.Contains(extra, "--memory=4g"); var stop = int.Parse(StopTimeout().Match(extra).Groups[1].Value, System.Globalization.CultureInfo.InvariantCulture); Assert.AreEqual(60, stop); Assert.IsGreaterThan(new GuardOptions().GracefulStop, TimeSpan.FromSeconds(stop)); } [TestMethod] [TestCategory(Category.Unit)] public void TheIconIsASquarePngWithTransparency() { var url = Template().Element("Icon")!.Value; StringAssert.EndsWith(url, "/deploy/unraid/anubis-icon.png"); var png = File.ReadAllBytes(Path.Combine(Repo.Root.FullName, "deploy", "unraid", "anubis-icon.png")); CollectionAssert.AreEqual(new byte[] { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A }, png[..8]); var width = BinaryPrimitives.ReadInt32BigEndian(png.AsSpan(16)); Assert.AreEqual(width, BinaryPrimitives.ReadInt32BigEndian(png.AsSpan(20))); Assert.IsGreaterThanOrEqualTo(128, width); Assert.AreEqual(6, (int)png[25], "Colour type 6: red, green, blue and transparency."); } // ---- what the loader reads ---- [TestMethod] [TestCategory(Category.Unit)] public void TheLoaderReadsEveryVariableOf151AndNoOther() { var read = new HashSet(StringComparer.Ordinal); Dictionary Base(string engine) => new() { ["ANUBIS_DB_ENGINE"] = engine, ["ANUBIS_SECRET_KEY"] = new string('k', 40), ["ANUBIS_ADMIN_PASSWORD"] = "initial-pass-1" }; var withUrl = Base("postgres"); withUrl["ANUBIS_DB_URL"] = "postgresql://anubis:a-database-pass@db.example:5432/anubis"; var withHost = Base("postgres"); (withHost["ANUBIS_DB_HOST"], withHost["ANUBIS_DB_PASSWORD"]) = ("db.example", "a-database-pass"); foreach (var env in new[] { withHost, Base("sqlite"), withUrl }) { DockerPlatform.Load(new Recorded(env, read), Path.GetTempPath()); } var expected = VariablesOf151(); foreach (var key in DockerPlatform.OptionalKeys) { Assert.Contains(key, expected); expected.Add(key + "_DEMO"); } CollectionAssert.AreEquivalent(expected.Order(StringComparer.Ordinal).ToList(), read.Order(StringComparer.Ordinal).ToList()); } [TestMethod] [TestCategory(Category.Unit)] public void AFieldLeftBlankInTheTemplateIsAsIfItWereNotThere() { var env = Fields(Template()).Where(f => f.Value.Attribute("Type")!.Value == "Variable").ToDictionary(f => f.Key, f => (string?)f.Value.Value, StringComparer.Ordinal); var blank = DockerPlatform.Load(env, Path.GetTempPath()); CollectionAssert.AreEquivalent(new[] { "ANUBIS_DB_HOST", "ANUBIS_DB_PASSWORD", "ANUBIS_SECRET_KEY", "ANUBIS_ADMIN_PASSWORD" }, blank.Problems.Select(p => p.Setting).ToList()); env["ANUBIS_DB_ENGINE"] = "sqlite"; env["ANUBIS_SECRET_KEY"] = new string('k', 40); env["ANUBIS_ADMIN_PASSWORD"] = "initial-pass-1"; var filled = DockerPlatform.Load(env, Path.GetTempPath()); Assert.IsEmpty(filled.Problems); Assert.IsFalse(filled.AllowLive); Assert.IsNull(filled.HeartbeatUrl); env["PUID"] = "0"; Assert.AreEqual("PUID", DockerPlatform.Load(env, Path.GetTempPath()).Problems.Single().Setting); } // ---- the health of the container (SPEC 15.2) ---- [TestMethod] [TestCategory(Category.Unit)] public void HealthCoversTheLoopAndThePrices() { var now = new DateTimeOffset(2026, 12, 1, 9, 0, 0, TimeSpan.Zero); DateTimeOffset? Ago(double minutes) => now.AddMinutes(-minutes); Assert.IsTrue(HealthRules.Loop(now, false, Ago(60)).Ok, "Not started, as on the error page or without keys."); Assert.IsTrue(HealthRules.Loop(now, true, null).Ok); Assert.IsTrue(HealthRules.Loop(now, true, Ago(1.9)).Ok); Assert.AreEqual(("fermo", false), HealthRules.Loop(now, true, Ago(2.1))); Assert.AreEqual(new GuardOptions().Silence, HealthRules.LoopLimit); Assert.IsTrue(HealthRules.Feed(now, null, null).Ok, "No instrument to follow yet."); Assert.IsTrue(HealthRules.Feed(now, Ago(4), null).Ok); Assert.IsFalse(HealthRules.Feed(now, Ago(6), null).Ok, "Open and silent from the start."); Assert.IsTrue(HealthRules.Feed(now, Ago(600), Ago(4)).Ok); Assert.AreEqual(("fermi", false), HealthRules.Feed(now, Ago(600), Ago(6))); } // ---- the image ---- [TestMethod] [TestCategory(Category.Unit)] public void TheImageSaysWhatItIs() { var docker = Text("deploy/docker/Dockerfile"); var project = Template().Element("Project")!.Value; StringAssert.Contains(docker, $"org.opencontainers.image.source=\"{project}\""); StringAssert.Contains(docker, "org.opencontainers.image.version=\"$ANUBIS_VERSION\""); StringAssert.Contains(docker, "org.opencontainers.image.revision=\"$ANUBIS_COMMIT\""); var publish = docker.Split('\n').Where(l => l.StartsWith("RUN dotnet publish", StringComparison.Ordinal)).ToList(); Assert.HasCount(2, publish); Assert.IsTrue(publish.All(l => l.EndsWith("${ANUBIS_COMMIT:+-p:SourceRevisionId=$ANUBIS_COMMIT}", StringComparison.Ordinal))); CollectionAssert.AreEquivalent(new[] { "mcr.microsoft.com/dotnet/sdk:10.0", "mcr.microsoft.com/dotnet/aspnet:10.0" }, docker.Split('\n').Where(l => l.StartsWith("FROM ", StringComparison.Ordinal)).Select(l => l.Split(' ')[1]).ToList()); StringAssert.Contains(docker, "${PORT:-8787}"); StringAssert.Contains(docker, "EXPOSE 8787\n"); StringAssert.Contains(docker, "--timeout=10s", "Longer than the 5 seconds the page waits for the database, so its answer arrives."); var entry = Text("deploy/docker/entrypoint.sh"); StringAssert.Contains(entry, "PUID=0"); StringAssert.Contains(entry, "--no-new-privs"); } // ---- the workflow ---- private static Dictionary Workflow() => MiniYaml.Read(Text(".gitea/workflows/ci.yml")); private static Dictionary At(object map, string key) => (Dictionary)((Dictionary)map)[key]; private static List> Steps(string job) => ((List)At(At(Workflow(), "jobs"), job)["steps"]).Cast>().ToList(); [TestMethod] [TestCategory(Category.Unit)] public void TheWorkflowUsesNoExternalAction() { foreach (var job in At(Workflow(), "jobs").Keys) { Assert.IsNotEmpty(Steps(job)); foreach (var step in Steps(job)) { Assert.IsTrue(step.ContainsKey("run"), $"{job}: {step["name"]}"); Assert.IsFalse(step.ContainsKey("uses"), $"{job}: {step["name"]}"); } } } [TestMethod] [TestCategory(Category.Unit)] public void TheImageIsPublishedOnlyOnVersionTagsAndAfterTheTests() { var workflow = Workflow(); CollectionAssert.AreEqual(new[] { "**" }, ((List)At(At(workflow, "on"), "push")["branches"]).Cast().ToList()); CollectionAssert.AreEqual(new[] { "v*" }, ((List)At(At(workflow, "on"), "push")["tags"]).Cast().ToList()); Assert.AreEqual("test", At(At(workflow, "jobs"), "image")["needs"]); var matrix = (List)At(At(At(At(workflow, "jobs"), "test"), "strategy"), "matrix")["db"]; CollectionAssert.AreEquivalent(new[] { "sqlite", "postgres" }, matrix.Cast().ToList()); var steps = Steps("image"); var publishing = Enumerable.Range(0, steps.Count).Where(i => PublishCommand().IsMatch((string)steps[i]["run"])).ToList(); Assert.HasCount(1, publishing); Assert.AreEqual("github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v')", steps[publishing[0]]["if"]); Assert.IsGreaterThan(steps.FindIndex(s => ((string)s["run"]).Contains(" drill", StringComparison.Ordinal)), publishing[0]); Assert.IsEmpty(Steps("test").Where(s => PublishCommand().IsMatch((string)s["run"]))); } [TestMethod] [TestCategory(Category.Unit)] public void TheTokensStayInTheStepsThatNeedThem() { var text = Text(".gitea/workflows/ci.yml"); Assert.AreEqual(1, Regex.Count(text, @"secrets\.")); Assert.DoesNotContain("set -x", text); foreach (var job in At(Workflow(), "jobs").Keys) { var definition = At(At(Workflow(), "jobs"), job); if (definition.TryGetValue("env", out var env)) { Assert.IsEmpty(((Dictionary)env).Values.OfType().Where(v => v.Contains("token", StringComparison.OrdinalIgnoreCase) || v.Contains("secrets.", StringComparison.Ordinal))); } foreach (var step in Steps(job)) { var run = (string)step["run"]; Assert.DoesNotContain("github.token", run); Assert.DoesNotContain("secrets.", run); Assert.DoesNotContain("github.ref", run, "A name chosen by who pushes reaches the shell only as a variable."); } } var publish = Steps("image").Single(s => PublishCommand().IsMatch((string)s["run"])); Assert.AreEqual("${{ secrets.REGISTRY_TOKEN }}", At(publish, "env")["REGISTRY_TOKEN"]); } [TestMethod] [TestCategory(Category.Unit)] public void WhatIsPublishedIsTheImageThatWasTried() { var name = (string)At(At(At(Workflow(), "jobs"), "image"), "env")["IMAGE"]; StringAssert.Contains(name, "github.run_id"); var docker = Steps("image").Select(s => (string)s["run"]).Where(r => r.Contains("docker", StringComparison.Ordinal)).ToList(); Assert.HasCount(4, docker, "Build, drill, publish, remove."); Assert.IsTrue(docker.All(r => r.Contains("\"$IMAGE\"", StringComparison.Ordinal))); } [TestMethod] [TestCategory(Category.Unit)] public void TheYamlReaderRefusesWhatItDoesNotKnow() { var read = MiniYaml.Read("# c\na: 1 # c\nb:\n - x\n - k: 'v: w'\n run: |\n one\n two\n\n three\nlist: [\"**\", z]\nfold: >-\n p\n q\n"); Assert.AreEqual("1", read["a"]); Assert.AreEqual("x", ((List)read["b"])[0]); Assert.AreEqual("v: w", ((Dictionary)((List)read["b"])[1])["k"]); Assert.AreEqual("one\n two\nthree", ((Dictionary)((List)read["b"])[1])["run"]); CollectionAssert.AreEqual(new[] { "**", "z" }, ((List)read["list"]).Cast().ToList()); Assert.AreEqual("p q", read["fold"]); foreach (var wrong in new[] { "a: 1\n\tb: 2", "a: 1\na: 2", "a: &x 1", "a: *x", "a:\n b: 1\n c: 2", "a: 1\n b: 2", "just text", "a: {b: 1}", "a: [1" }) { StringAssert.Contains(Assert.ThrowsExactly(() => MiniYaml.Read(wrong), wrong).Message, "line "); } } // ---- the script that publishes, with a docker and a git that only take note ---- [TestMethod] [TestCategory(Category.Integration)] [OSCondition(OperatingSystems.Linux)] [DataRow("v0.9.0", "v0.7.0", 0, "0.9.0,latest")] [DataRow("v0.9.0", "", 0, "0.9.0,latest")] [DataRow("v0.9.0-rc.1", "v0.7.0", 0, "0.9.0-rc.1")] [DataRow("v0.9.0", "v0.10.0", 0, "0.9.0")] [DataRow("v0.9.0", "v0.10.0-rc.1", 0, "0.9.0,latest")] [DataRow("v0.9.1", "v0.7.0", 1, "")] [DataRow("fase-9", "v0.7.0", 1, "")] [DataRow("v9", "v0.7.0", 1, "")] [DataRow("v0.9.0;id", "v0.7.0", 1, "")] public async Task TheScriptPublishesTheVersionAndMovesLatestOnlyForward(string tag, string others, int exit, string pushed) { using var run = new PublishRun(others); var (code, output) = await run.RunAsync(tag, PublishRun.Token); Assert.AreEqual(exit, code, output); CollectionAssert.AreEqual(pushed.Split(',', StringSplitOptions.RemoveEmptyEntries), run.Pushed(), output); if (exit != 0) { StringAssert.Contains(output, "Pubblicazione non riuscita"); } } [TestMethod] [TestCategory(Category.Integration)] [OSCondition(OperatingSystems.Linux)] public async Task TheScriptGivesTheTokenToDockerOnlyOnItsInputAndLeavesNothing() { using var run = new PublishRun("v0.7.0"); var (code, output) = await run.RunAsync("v0.9.0", PublishRun.Token); Assert.AreEqual(0, code, output); Assert.DoesNotContain(PublishRun.Token, output); Assert.DoesNotContain(PublishRun.Token, run.Calls); Assert.AreEqual(PublishRun.Token, run.Input); var config = run.Config; Assert.IsNotEmpty(config); Assert.IsFalse(Directory.Exists(config), "The folder with the credentials is gone."); using var without = new PublishRun("v0.7.0"); (code, output) = await without.RunAsync("v0.9.0", ""); Assert.AreEqual(1, code); StringAssert.Contains(output, "REGISTRY_TOKEN"); Assert.AreEqual("", without.Calls); using var offline = new PublishRun("v0.7.0", gitFails: true); (code, output) = await offline.RunAsync("v0.9.0", PublishRun.Token); Assert.AreEqual(1, code, output); Assert.IsEmpty(offline.Pushed()); } private sealed class PublishRun : IDisposable { public const string Token = "a-token-only-for-the-test"; private readonly string _root = Path.Combine(Path.GetTempPath(), "anubis-publish-" + Guid.NewGuid().ToString("N")); public PublishRun(string others, bool gitFails = false) { Directory.CreateDirectory(Path.Combine(_root, "deploy", "docker")); Directory.CreateDirectory(Path.Combine(_root, "bin")); File.WriteAllText(Path.Combine(_root, "deploy", "docker", "publish.sh"), Text("deploy/docker/publish.sh")); File.WriteAllText(Path.Combine(_root, "Directory.Build.props"), "\n 0.9.0\n\n"); Tool("docker", "printf '%s\\n' \"$*\" >> \"$RECORD/calls\"\nif [ \"$1\" = login ]; then cat > \"$RECORD/input\"; printf '%s' \"$DOCKER_CONFIG\" > \"$RECORD/config\"; fi\n"); Tool("git", gitFails ? "exit 128\n" : string.Concat(others.Split(',', StringSplitOptions.RemoveEmptyEntries).Select(o => $"printf 'abc\\trefs/tags/{o}\\n'\n"))); } public string Calls => Recorded("calls"); public string Input => Recorded("input"); public string Config => Recorded("config"); public List Pushed() => Calls.Split('\n').Where(l => l.StartsWith("push registry.test/balbosoft/anubis:", StringComparison.Ordinal)).Select(l => l[(l.LastIndexOf(':') + 1)..]).ToList(); public async Task<(int Code, string Output)> RunAsync(string tag, string token) { var info = new ProcessStartInfo("sh") { RedirectStandardError = true, RedirectStandardOutput = true, UseShellExecute = false }; info.ArgumentList.Add(Path.Combine(_root, "deploy", "docker", "publish.sh")); info.ArgumentList.Add("anubis:ci-1-1"); info.ArgumentList.Add(tag); info.Environment["PATH"] = Path.Combine(_root, "bin") + ":" + Environment.GetEnvironmentVariable("PATH"); info.Environment["RECORD"] = _root; info.Environment["REGISTRY"] = "registry.test"; info.Environment["REGISTRY_USER"] = "someone"; info.Environment["REGISTRY_TOKEN"] = token; using var process = Process.Start(info)!; var output = process.StandardOutput.ReadToEndAsync(); var error = process.StandardError.ReadToEndAsync(); await process.WaitForExitAsync(); return (process.ExitCode, await output + await error); } public void Dispose() => Directory.Delete(_root, recursive: true); private string Recorded(string name) => File.Exists(Path.Combine(_root, name)) ? File.ReadAllText(Path.Combine(_root, name)) : ""; private void Tool(string name, string body) { var path = Path.Combine(_root, "bin", name); File.WriteAllText(path, "#!/bin/sh\n" + body); if (!OperatingSystem.IsWindows()) { File.SetUnixFileMode(path, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute); } } } /// An environment that takes note of the names asked for. private sealed class Recorded(Dictionary values, HashSet read) : IReadOnlyDictionary { public IEnumerable Keys => values.Keys; public IEnumerable Values => values.Values; public int Count => values.Count; public string? this[string key] => TryGetValue(key, out var value) ? value : throw new KeyNotFoundException(key); public bool ContainsKey(string key) { read.Add(key); return values.ContainsKey(key); } public bool TryGetValue(string key, [MaybeNullWhen(false)] out string? value) { read.Add(key); return values.TryGetValue(key, out value); } public IEnumerator> GetEnumerator() => values.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } [GeneratedRegex("`([A-Z][A-Z0-9_]+)`")] private static partial Regex VariableName(); [GeneratedRegex(@"--stop-timeout (\d+)")] private static partial Regex StopTimeout(); [GeneratedRegex(@"publish\.sh|docker (push|login)")] private static partial Regex PublishCommand(); }