Fase 10 — Nuova rotta: solo Docker (#184)
ADR 0021-0026 for the new course of 2 December 2026, roadmap of phases 10-24. The desktop application is gone: Docker is the only form, and outside a container the server runs only for development and tests with --data-dir, on this computer only. Lighter image (829 MB to 410 MB), rotating logs, backtest and learning as one-shot commands. refs #113 #114 #115 #78 #80 #81 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
This commit was merged in pull request #184.
This commit is contained in:
1 parent
3c57b3e84c
commit
1bc7e067fd
96 files changed
+1433
-1606
No files matched your search
@@ -15,5 +15,6 @@
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\src\Anubis\Anubis.csproj" />
|
||||
<ProjectReference Include="..\..\src\Anubis.Server\Anubis.Server.csproj" />
|
||||
<ProjectReference Include="..\..\src\Anubis.Guard\Anubis.Guard.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -121,6 +121,9 @@ public sealed partial class DeliveryTests
|
||||
Assert.AreEqual("/mnt/user/appdata/anubis", fields["/data"].Value);
|
||||
var extra = template.Element("ExtraParams")!.Value;
|
||||
StringAssert.Contains(extra, "--memory=4g");
|
||||
StringAssert.Contains(extra, "--log-opt max-size=10m --log-opt max-file=3", "Docker's own log files rotate (ADR 0022).");
|
||||
StringAssert.Contains(Text("docs/MANUALE.md"), "--log-opt max-size=10m --log-opt max-file=3");
|
||||
StringAssert.Contains(Text("docker-compose.yml"), "max-size: 10m");
|
||||
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));
|
||||
@@ -223,15 +226,34 @@ public sealed partial class DeliveryTests
|
||||
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)));
|
||||
Assert.IsTrue(publish.All(l => l.EndsWith(" -o /app ${ANUBIS_COMMIT:+-p:SourceRevisionId=$ANUBIS_COMMIT}", StringComparison.Ordinal)),
|
||||
"Into /app, with the commit as a separate argument: without the space the output folder would swallow it.");
|
||||
StringAssert.Contains(docker, "COPY global.json Directory.Build.props Directory.Build.targets Directory.Packages.props ./");
|
||||
Assert.Contains("grep -qiE '^onnxruntime", docker, "The build stops if the Windows libraries of ONNX Runtime come back into /app.");
|
||||
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.");
|
||||
|
||||
// Only what Linux x64 needs (ADR 0022): the native libraries of the other 23 platforms stay out of the image.
|
||||
var restore = docker.Split('\n').Where(l => l.Contains("dotnet restore", StringComparison.Ordinal)).ToList();
|
||||
Assert.HasCount(2, restore);
|
||||
Assert.IsTrue(restore.Concat(publish).All(l => l.Contains(" -r linux-x64 ", StringComparison.Ordinal)), string.Join("\n", restore.Concat(publish)));
|
||||
Assert.IsTrue(publish.All(l => l.Contains("--self-contained false", StringComparison.Ordinal)));
|
||||
Assert.DoesNotContain("ANUBIS_PLATFORM", docker, "The guard and the server recognise the container by themselves.");
|
||||
|
||||
var entry = Text("deploy/docker/entrypoint.sh");
|
||||
StringAssert.Contains(entry, "PUID=0");
|
||||
StringAssert.Contains(entry, "--no-new-privs");
|
||||
|
||||
// Every one-shot command of the server runs outside the guard, which would restart it when it ends.
|
||||
var oneShot = OneShot().Match(entry);
|
||||
Assert.IsTrue(oneShot.Success, "The entrypoint routes the one-shot commands.");
|
||||
var routed = oneShot.Groups[1].Value.Split('|');
|
||||
var commands = CommandOfTheServer().Matches(Text("src/Anubis.Server/Program.cs")).Select(m => m.Groups[1].Value).ToList();
|
||||
Assert.IsNotEmpty(commands);
|
||||
CollectionAssert.AreEquivalent(commands, routed);
|
||||
}
|
||||
|
||||
// ---- the workflow ----
|
||||
@@ -574,6 +596,12 @@ public sealed partial class DeliveryTests
|
||||
[GeneratedRegex(@"--stop-timeout (\d+)")]
|
||||
private static partial Regex StopTimeout();
|
||||
|
||||
[GeneratedRegex(@"\r?\n\s*([a-z|]+)\)\r?\n\s*app=""/app/Anubis\.Server\.dll""")]
|
||||
private static partial Regex OneShot();
|
||||
|
||||
[GeneratedRegex(@"args\[0\] == ""([a-z]+)""")]
|
||||
private static partial Regex CommandOfTheServer();
|
||||
|
||||
[GeneratedRegex(@"publish\.sh|docker (push|login)")]
|
||||
private static partial Regex PublishCommand();
|
||||
}
|
||||
@@ -7,12 +7,10 @@ namespace Anubis.Tests;
|
||||
[TestClass]
|
||||
public sealed class DependencyPolicyTests
|
||||
{
|
||||
/// <summary>The list of ADR 0004 as precised by ADR 0006. Changing it needs the user's permission and a new ADR.</summary>
|
||||
/// <summary>The list of ADR 0004 as precised by ADR 0006 and shortened by ADR 0022. Changing it needs the user's permission and a new ADR.</summary>
|
||||
private static readonly HashSet<string> _authorised = new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
"Microsoft.Data.Sqlite",
|
||||
"System.Security.Cryptography.ProtectedData",
|
||||
"Microsoft.Web.WebView2",
|
||||
"MSTest.TestFramework",
|
||||
"MSTest.TestAdapter",
|
||||
"Microsoft.NET.Test.Sdk",
|
||||
|
||||
@@ -129,14 +129,14 @@ public sealed class DiagnosticsTests
|
||||
var text = await DiagnosticsReporter.BuildAsync(test.Db, new DiagnosticsRequest(Start.AddMinutes(1), Start.AddHours(12), Zones.Rome)
|
||||
{
|
||||
LogsFolder = logs,
|
||||
Setup = [new("Piattaforma", "desktop")],
|
||||
Setup = [new("Dove gira", "container")],
|
||||
GeneratedAt = Start.AddHours(12),
|
||||
}).ConfigureAwait(false);
|
||||
|
||||
Assert.IsLessThanOrEqualTo(DiagnosticsReporter.MaxBytes, Encoding.UTF8.GetByteCount(text));
|
||||
Assert.DoesNotContain(Hidden, text);
|
||||
Assert.Contains("# Anubis · dati per l'analisi", text);
|
||||
Assert.Contains("- Piattaforma: desktop", text);
|
||||
Assert.Contains("- Dove gira: container", text);
|
||||
Assert.Contains("Il bot è ripartito 1 volte nel periodo.", text);
|
||||
Assert.Contains("Spento 1 volte", text);
|
||||
Assert.Contains("Silenzi a processo acceso: 1", text);
|
||||
@@ -179,9 +179,11 @@ public sealed class DiagnosticsTests
|
||||
Assert.AreEqual("text/markdown", report.Content.Headers.ContentType?.MediaType);
|
||||
var text = await report.Content.ReadAsStringAsync();
|
||||
Assert.Contains("# Anubis · dati per l'analisi", text);
|
||||
Assert.Contains("- Piattaforma: docker", text);
|
||||
Assert.Contains("- Dove gira: fuori dal container, per sviluppo e prove", text);
|
||||
Assert.Contains("| " + AnubisInfo.Version + " |", text, "The start sample of the running process is in the report.");
|
||||
Assert.Contains("Scarica i dati per l'analisi", await server.TextAsync("/diario"));
|
||||
var diary = await server.TextAsync("/diario");
|
||||
Assert.Contains("Scarica i dati per l'analisi", diary);
|
||||
Assert.Contains(" fuori dal container (sviluppo), acceso ", diary, "The diary says where it runs, as Settings does.");
|
||||
}
|
||||
|
||||
private static ProcessSample Sample(DateTimeOffset at, DateTimeOffset process, double megabytes, int i) => new()
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
using Anubis.Demo;
|
||||
using Anubis.Platform;
|
||||
|
||||
namespace Anubis.Tests;
|
||||
|
||||
/// <summary>Startup configuration in Docker and on desktop (issue #7, SPEC 15.1, 15.6).</summary>
|
||||
/// <summary>Startup configuration of the container, and what is left outside it (issue #7, SPEC 15.1, ADR 0022).</summary>
|
||||
[TestClass]
|
||||
public sealed class PlatformTests
|
||||
{
|
||||
@@ -94,60 +95,39 @@ public sealed class PlatformTests
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void TomlSubsetParsesAndRejectsWithLineNumbers()
|
||||
public void TheContainerFindsItsDataAndOutsideItTheFolderIsGivenByHand()
|
||||
{
|
||||
var values = Toml.Parse("""
|
||||
# comment
|
||||
allow_live = false
|
||||
port = 8_787 # trailing comment
|
||||
name = "a \"quoted\" # not a comment"
|
||||
// The rule of the server and of the guard alike (ADR 0022): no ANUBIS_PLATFORM, no user folder.
|
||||
var container = new Dictionary<string, string?> { ["DOTNET_RUNNING_IN_CONTAINER"] = "true" };
|
||||
Assert.AreEqual("/data", DataDirectory.Locate(null, container));
|
||||
Assert.AreEqual(Path.GetFullPath("dati-di-prova"), DataDirectory.Locate("dati-di-prova", container));
|
||||
Assert.AreEqual(Path.GetFullPath("dati-di-prova"), DataDirectory.Locate("dati-di-prova", new Dictionary<string, string?>()));
|
||||
|
||||
[database]
|
||||
engine = "postgres"
|
||||
""");
|
||||
Assert.IsFalse((bool)values["allow_live"]);
|
||||
Assert.AreEqual(8787L, values["port"]);
|
||||
Assert.AreEqual("a \"quoted\" # not a comment", values["name"]);
|
||||
Assert.AreEqual("postgres", values["database.engine"]);
|
||||
|
||||
var error = Assert.Throws<FormatException>(() => Toml.Parse("a = 1\nb = [1, 2]\n"));
|
||||
Assert.Contains("Riga 2", error.Message);
|
||||
Assert.Throws<FormatException>(() => Toml.Parse("a = 1\na = 2"));
|
||||
Assert.Throws<FormatException>(() => Toml.Parse("a = \"open"));
|
||||
var outside = new Dictionary<string, string?> { ["ANUBIS_PLATFORM"] = "docker" };
|
||||
var refused = Assert.Throws<StartupRefusedException>(() => DataDirectory.Locate(null, outside));
|
||||
Assert.Contains("--data-dir", refused.Message);
|
||||
Assert.Contains("Fuori da un container", refused.Message);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public void DesktopStartsFromAnEmptyFolderAndKeepsSecretsOutOfConfigToml()
|
||||
public void TheDemoStartsFromAnEmptyFolderAndCreatesItsOwnKey()
|
||||
{
|
||||
var folder = TempFolder.Create("desktop");
|
||||
var folder = TempFolder.Create("demo-key");
|
||||
try
|
||||
{
|
||||
var data = new DataDirectory(folder);
|
||||
var store = ProtectedSecretKey.DefaultStore(data);
|
||||
var first = DesktopPlatform.Load(data, store);
|
||||
Assert.IsTrue(first.NeedsFirstRun);
|
||||
Assert.IsFalse(first.IsComplete);
|
||||
var first = DemoMode.Config(data);
|
||||
Assert.IsTrue(first.IsComplete, string.Join("; ", first.Problems.Select(p => p.What)));
|
||||
Assert.AreEqual(data.SqliteFile, first.Db!.SqlitePath);
|
||||
Assert.IsFalse(first.AllowLive);
|
||||
Assert.IsFalse(first.SecretKey.HasKey, "An empty folder has no key yet.");
|
||||
|
||||
var key = first.SecretKey.GetOrCreateKey();
|
||||
DesktopPlatform.WriteConfig(data, store, new DbSettings { Engine = DbEngine.Postgres, Host = "localhost", Password = "fake-pg-pass-1" });
|
||||
|
||||
var text = File.ReadAllText(data.ConfigFile);
|
||||
Assert.Contains("allow_live = false", text);
|
||||
Assert.IsFalse(text.Contains("fake-pg-pass-1", StringComparison.Ordinal), "la password del database non va in config.toml");
|
||||
Assert.IsFalse(text.Contains(Convert.ToBase64String(key), StringComparison.Ordinal), "la chiave dei segreti non va in config.toml");
|
||||
Assert.IsFalse(text.Contains("secret", StringComparison.OrdinalIgnoreCase) && text.Contains("key =", StringComparison.Ordinal));
|
||||
|
||||
var second = DesktopPlatform.Load(data, store);
|
||||
Assert.IsTrue(second.IsComplete, string.Join("; ", second.Problems.Select(p => p.What)));
|
||||
Assert.AreEqual("fake-pg-pass-1", second.Db!.Password);
|
||||
CollectionAssert.AreEqual(key, second.SecretKey.GetOrCreateKey(), "la chiave resta la stessa tra un avvio e l'altro");
|
||||
Assert.IsFalse(second.AllowLive);
|
||||
Assert.IsFalse(second.AllowNetwork);
|
||||
|
||||
DesktopPlatform.WriteConfig(data, store, new DbSettings { Engine = DbEngine.Sqlite });
|
||||
var sqlite = DesktopPlatform.Load(data, store);
|
||||
Assert.AreEqual(data.SqliteFile, sqlite.Db!.SqlitePath);
|
||||
Assert.HasCount(32, key);
|
||||
Assert.IsNotEmpty(Directory.EnumerateFiles(Path.Combine(folder, "keys")).ToList(), "The key lives in a file of the demo folder.");
|
||||
CollectionAssert.AreEqual(key, DemoMode.Config(data).SecretKey.GetOrCreateKey(), "The same key at the next start.");
|
||||
Assert.DoesNotContain("Windows", first.SecretKey.Description);
|
||||
}
|
||||
finally
|
||||
{
|
||||
@@ -157,22 +137,34 @@ public sealed class PlatformTests
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void BrokenConfigTomlIsAProblemNotAGuess()
|
||||
public void NothingOfTheDesktopIsLeftInTheProduct()
|
||||
{
|
||||
var folder = TempFolder.Create("desktop-bad");
|
||||
try
|
||||
// ADR 0022: the desktop application, its configuration file and its guided first run are gone.
|
||||
string[] words = ["config.toml", "primo-avvio", "PlatformKind", "ANUBIS_PLATFORM", "DesktopPlatform", "ProtectedData"];
|
||||
var found = Repo.Files()
|
||||
.Where(file => Repo.Relative(file) is var path && (path.StartsWith("src/", StringComparison.Ordinal) ||
|
||||
path.StartsWith("tools/", StringComparison.Ordinal) || path.StartsWith("deploy/", StringComparison.Ordinal)))
|
||||
.Where(file => file.Extension is not (".png" or ".ico" or ".ttf" or ".onnx"))
|
||||
.SelectMany(file => words.Where(word => File.ReadAllText(file.FullName).Contains(word, StringComparison.Ordinal))
|
||||
.Select(word => Repo.Relative(file) + ": " + word))
|
||||
.ToList();
|
||||
Assert.IsEmpty(found, string.Join("; ", found));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void TheSolutionHasFiveProjects()
|
||||
{
|
||||
var solution = System.Xml.Linq.XDocument.Load(Path.Combine(Repo.Root.FullName, "Anubis.slnx"));
|
||||
var projects = solution.Descendants("Project").Select(p => (string)p.Attribute("Path")!).Order(StringComparer.Ordinal).ToList();
|
||||
CollectionAssert.AreEqual(new[]
|
||||
{
|
||||
var data = new DataDirectory(folder);
|
||||
File.WriteAllText(data.ConfigFile, "[database]\nengine = sqlite\n");
|
||||
var config = DesktopPlatform.Load(data, ProtectedSecretKey.DefaultStore(data));
|
||||
Assert.IsNull(config.Db);
|
||||
Assert.IsFalse(config.IsComplete);
|
||||
Assert.Contains("Riga 2", config.Problems[0].What);
|
||||
}
|
||||
finally
|
||||
{
|
||||
TempFolder.Delete(folder);
|
||||
}
|
||||
"src/Anubis.Guard/Anubis.Guard.csproj",
|
||||
"src/Anubis.Server/Anubis.Server.csproj",
|
||||
"src/Anubis/Anubis.csproj",
|
||||
"tests/Anubis.Tests/Anubis.Tests.csproj",
|
||||
"tools/Anubis.Tasks/Anubis.Tasks.csproj",
|
||||
}, projects);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
|
||||
@@ -28,8 +28,7 @@ public sealed partial class SecurityTests
|
||||
{
|
||||
private static readonly string[] _open =
|
||||
[
|
||||
"/health", "/brand/{file}", "/assets/{file}", "/favicon.ico", "/accesso", "/primo-avvio", "/servizio", "/azioni/accesso", "/azioni/primo-avvio", "/azioni/primo-avvio/prova",
|
||||
"/azioni/servizio/{choice}",
|
||||
"/health", "/brand/{file}", "/assets/{file}", "/favicon.ico", "/accesso", "/servizio", "/azioni/accesso", "/azioni/servizio/{choice}",
|
||||
];
|
||||
|
||||
[TestMethod]
|
||||
@@ -71,8 +70,8 @@ public sealed partial class SecurityTests
|
||||
var address = Parameter().Replace(form, m => m.Value.Contains("guid", StringComparison.Ordinal) ? Guid.Empty.ToString("D") : "x");
|
||||
using var content = new FormUrlEncodedContent([new("password", "x")]);
|
||||
using var answer = await server.Http.PostAsync(new Uri(address, UriKind.Relative), content);
|
||||
Assert.IsTrue(answer.StatusCode == HttpStatusCode.BadRequest || (answer.StatusCode == HttpStatusCode.ServiceUnavailable && open.Contains(form)) ||
|
||||
(answer.StatusCode == HttpStatusCode.Redirect && form.StartsWith("/azioni/primo-avvio", StringComparison.Ordinal)), form + ": " + answer.StatusCode);
|
||||
Assert.IsTrue(answer.StatusCode == HttpStatusCode.BadRequest || (answer.StatusCode == HttpStatusCode.ServiceUnavailable && open.Contains(form)),
|
||||
form + ": " + answer.StatusCode);
|
||||
}
|
||||
|
||||
using var unknown = await server.GetAsync("/qualcosa-che-non-esiste");
|
||||
|
||||
@@ -165,6 +165,13 @@ public sealed class ServerTests
|
||||
}
|
||||
|
||||
TempFolder.Delete(demoRoot);
|
||||
|
||||
// A development run outside a container: the same refusal, even when bound to every address (ADR 0022).
|
||||
await using var dev = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite());
|
||||
using var rebinding = new HttpRequestMessage(HttpMethod.Get, new Uri("/health", UriKind.Relative));
|
||||
rebinding.Headers.Host = "evil.example:" + dev.BaseAddress.Port.ToString(System.Globalization.CultureInfo.InvariantCulture);
|
||||
using var refused = await dev.Http.SendAsync(rebinding);
|
||||
Assert.AreEqual(HttpStatusCode.Forbidden, refused.StatusCode);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
@@ -332,36 +339,93 @@ public sealed class ServerTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task DesktopStartsFromAnEmptyFolderAndKeepsTheKeyOutOfConfig()
|
||||
public void TheDesktopIsGoneAndOutsideAContainerTheFolderIsGivenByHand()
|
||||
{
|
||||
await using var server = await ServerHarness.StartAsync("desktop", new Dictionary<string, string?>(), waitReady: false);
|
||||
await server.WaitForAsync(HostMode.FirstRun);
|
||||
var env = ServerHarness.DockerSqlite();
|
||||
var desktop = Assert.Throws<StartupRefusedException>(() => ServerOptions.Parse(["--platform", "desktop"], env));
|
||||
Assert.Contains("solo in un container Docker", desktop.Message);
|
||||
|
||||
using (var redirect = await server.GetAsync("/"))
|
||||
// "--platform docker" still works, for the commands already written in the manuals.
|
||||
var outside = ServerOptions.Parse(["--platform", "docker"], env);
|
||||
Assert.IsFalse(outside.InContainer);
|
||||
Assert.IsTrue(outside.LocalOnly);
|
||||
var refused = Assert.Throws<StartupRefusedException>(() => outside.LoadConfig(env));
|
||||
Assert.Contains("--data-dir", refused.Message);
|
||||
|
||||
var inside = new Dictionary<string, string?>(env, StringComparer.Ordinal) { ["DOTNET_RUNNING_IN_CONTAINER"] = "true" };
|
||||
var container = ServerOptions.Parse([], inside);
|
||||
Assert.IsTrue(container.InContainer);
|
||||
Assert.IsFalse(container.LocalOnly);
|
||||
Assert.AreEqual("/data", container.LoadConfig(inside).Data.Root);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow(false, "http://127.0.0.1:")]
|
||||
[DataRow(true, "http://0.0.0.0:")]
|
||||
public async Task OutsideAContainerTheServerListensOnlyOnThisComputer(bool inContainer, string address)
|
||||
{
|
||||
var folder = TempFolder.Create("listen");
|
||||
try
|
||||
{
|
||||
Assert.AreEqual("/primo-avvio", ServerHarness.Location(redirect));
|
||||
var env = ServerHarness.DockerSqlite();
|
||||
env["PORT"] = "18787";
|
||||
if (inContainer)
|
||||
{
|
||||
env["DOTNET_RUNNING_IN_CONTAINER"] = "true";
|
||||
}
|
||||
|
||||
await using (var app = ServerApp.Build(["--data-dir", folder], new ServerOverrides { Environment = env, PasswordIterations = 1000 }))
|
||||
{
|
||||
Assert.AreEqual(address + "18787", app.Configuration["urls"]);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
TempFolder.Delete(folder);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow("Anubis.Server.dll", "--platform desktop", "solo in un container Docker")]
|
||||
[DataRow("Anubis.Server.dll", "", "--data-dir")]
|
||||
[DataRow("Anubis.Guard.dll", "--platform desktop", "solo in un container Docker")]
|
||||
[DataRow("Anubis.Guard.dll", "--platform desktop --data-dir .", "solo in un container Docker")]
|
||||
[DataRow("Anubis.Guard.dll", "", "--data-dir")]
|
||||
public async Task TheServerSaysInItalianWhyItDoesNotStart(string program, string arguments, string message)
|
||||
{
|
||||
var info = new System.Diagnostics.ProcessStartInfo(Anubis.Supervision.GuardLaunch.Dotnet())
|
||||
{
|
||||
RedirectStandardError = true,
|
||||
RedirectStandardOutput = true,
|
||||
UseShellExecute = false,
|
||||
};
|
||||
// The guard too: a refused start ends with the message, not with an engine restarted again and again.
|
||||
info.ArgumentList.Add(Path.Combine(AppContext.BaseDirectory, program));
|
||||
foreach (var argument in arguments.Split(' ', StringSplitOptions.RemoveEmptyEntries))
|
||||
{
|
||||
info.ArgumentList.Add(argument);
|
||||
}
|
||||
|
||||
const string password = "fake-desktop-pass-3";
|
||||
using (var done = await server.PostFormAsync("/primo-avvio", "/azioni/primo-avvio", ("motore", "sqlite"), ("password", password), ("conferma", password)))
|
||||
// Outside a container, even when the suite runs in one (the CI).
|
||||
info.Environment.Remove("DOTNET_RUNNING_IN_CONTAINER");
|
||||
using var process = System.Diagnostics.Process.Start(info)!;
|
||||
var errors = process.StandardError.ReadToEndAsync();
|
||||
_ = process.StandardOutput.ReadToEndAsync();
|
||||
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(60));
|
||||
try
|
||||
{
|
||||
Assert.AreEqual("/", ServerHarness.Location(done));
|
||||
await process.WaitForExitAsync(timeout.Token);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
// A guard that does not refuse would restart the engine for ever: it goes, with what it started.
|
||||
process.Kill(entireProcessTree: true);
|
||||
Assert.Fail(program + " did not end within a minute.");
|
||||
}
|
||||
|
||||
Assert.AreEqual(HostMode.Ready, server.Host.Status.Mode);
|
||||
using (var home = await server.GetAsync("/"))
|
||||
{
|
||||
Assert.AreEqual(HttpStatusCode.OK, home.StatusCode, "Signed in by the wizard.");
|
||||
}
|
||||
|
||||
var data = new DataDirectory(server.DataDir);
|
||||
Assert.IsTrue(File.Exists(data.SqliteFile));
|
||||
var config = await File.ReadAllTextAsync(data.ConfigFile);
|
||||
StringAssert.Contains(config, "engine = \"sqlite\"");
|
||||
StringAssert.Contains(config, "allow_live = false");
|
||||
Assert.IsFalse(System.Text.RegularExpressions.Regex.IsMatch(config, @"^\s*\w*(secret|key|password)\w*\s*=", System.Text.RegularExpressions.RegexOptions.Multiline),
|
||||
"Neither the secret key nor a password goes into config.toml.");
|
||||
Assert.IsNotEmpty(Directory.EnumerateFiles(Path.Combine(data.Root, "keys")).ToList());
|
||||
Assert.AreEqual(2, process.ExitCode);
|
||||
Assert.Contains(message, await errors);
|
||||
Assert.DoesNotContain(" at ", await errors, "A message, not a stack trace.");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
@@ -403,6 +467,13 @@ public sealed class ServerTests
|
||||
StringAssert.Contains(message, "\"bot\":\"active\"");
|
||||
await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, null, CancellationToken.None);
|
||||
|
||||
// The demo has no startup password and answers only this computer: the error-page choices go through without one.
|
||||
using (var choice = await server.PostFormAsync("/", "/azioni/servizio/riprova"))
|
||||
{
|
||||
Assert.AreEqual(HttpStatusCode.Redirect, choice.StatusCode);
|
||||
Assert.DoesNotContain("errore", ServerHarness.Location(choice));
|
||||
}
|
||||
|
||||
var after = Snapshot(configured);
|
||||
CollectionAssert.AreEquivalent(before.Keys.ToList(), after.Keys.ToList(), "No file added or removed in the configured data folder.");
|
||||
foreach (var (name, hash) in before)
|
||||
|
||||
@@ -158,22 +158,8 @@ public sealed class TradingRulesTests
|
||||
env["ANUBIS_ALLOW_LIVE"] = "0";
|
||||
Assert.ThrowsExactly<LiveTradingRefusedException>(() => LiveGuard.Ensure(TradingEnvironments.Live, TradingConsent.From(DockerPlatform.Load(env))));
|
||||
|
||||
// Desktop: the config.toml the wizard writes keeps real money off.
|
||||
var root = TempFolder.Create("live");
|
||||
try
|
||||
{
|
||||
var data = new DataDirectory(root);
|
||||
var store = new RestrictedFileStore(Path.Combine(root, "keys"));
|
||||
DesktopPlatform.WriteConfig(data, store, new DbSettings { Engine = DbEngine.Sqlite });
|
||||
var desktop = TradingConsent.From(DesktopPlatform.Load(data, store));
|
||||
Assert.IsFalse(desktop.AllowLive);
|
||||
var refused = Assert.ThrowsExactly<LiveTradingRefusedException>(() => LiveGuard.Ensure(TradingEnvironments.Live, desktop));
|
||||
Assert.Contains("config.toml", refused.Message);
|
||||
}
|
||||
finally
|
||||
{
|
||||
TempFolder.Delete(root);
|
||||
}
|
||||
var refused = Assert.ThrowsExactly<LiveTradingRefusedException>(() => LiveGuard.Ensure(TradingEnvironments.Live, docker));
|
||||
Assert.Contains("ANUBIS_ALLOW_LIVE", refused.Message, "The only switch for real money is the variable of the container (ADR 0022).");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
|
||||
@@ -164,14 +164,19 @@
|
||||
"Microsoft.Data.Sqlite": "[10.0.14, )",
|
||||
"Microsoft.ML.OnnxRuntime": "[1.31.1, )",
|
||||
"Microsoft.ML.Tokenizers": "[2.0.1, )",
|
||||
"Npgsql": "[10.0.3, )",
|
||||
"System.Security.Cryptography.ProtectedData": "[10.0.14, )"
|
||||
"Npgsql": "[10.0.3, )"
|
||||
}
|
||||
},
|
||||
"anubis.guard": {
|
||||
"type": "Project",
|
||||
"dependencies": {
|
||||
"Anubis": "[0.9.0, )"
|
||||
}
|
||||
},
|
||||
"anubis.server": {
|
||||
"type": "Project",
|
||||
"dependencies": {
|
||||
"Anubis": "[0.7.0, )"
|
||||
"Anubis": "[0.9.0, )"
|
||||
}
|
||||
},
|
||||
"Microsoft.Data.Sqlite": {
|
||||
@@ -211,12 +216,6 @@
|
||||
"dependencies": {
|
||||
"Microsoft.Extensions.Logging.Abstractions": "10.0.0"
|
||||
}
|
||||
},
|
||||
"System.Security.Cryptography.ProtectedData": {
|
||||
"type": "CentralTransitive",
|
||||
"requested": "[10.0.14, )",
|
||||
"resolved": "10.0.14",
|
||||
"contentHash": "UuaBUHgmtc9h6CMxaQqFDDJxkS5JVy7XEB+DbtCvD68GFcVM9/AccuNwFpARx8nwCnvjaxzoOBjG3gPz32P1Eg=="
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user