Files
Anubis/tests/Anubis.Tests/SecurityTests.cs
Alby96andClaude Opus 5.5 1bc7e067fd
ci / test (postgres) (push) Successful in 4m50s
ci / test (sqlite) (push) Failing after 4m21s
ci / image (push) Skipped
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>
2026-12-03 19:59:00 +01:00

412 lines
21 KiB
C#

using System.Net;
using System.Net.Http.Json;
using System.Net.WebSockets;
using System.Text;
using System.Text.RegularExpressions;
using Anubis.Access;
using Anubis.Brokers;
using Anubis.Core;
using Anubis.Data;
using Anubis.Db;
using Anubis.News;
using Anubis.Platform;
using Anubis.Server;
using Anubis.Trading;
using Microsoft.AspNetCore.Antiforgery;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.DependencyInjection;
namespace Anubis.Tests;
/// <summary>The security review of Phase 9 as tests (issue #68, SPEC 15.4, 12.4, 9.1).</summary>
[TestClass]
public sealed partial class SecurityTests
{
private static readonly string[] _open =
[
"/health", "/brand/{file}", "/assets/{file}", "/favicon.ico", "/accesso", "/servizio", "/azioni/accesso", "/azioni/servizio/{choice}",
];
[TestMethod]
[TestCategory(Category.Integration)]
public async Task EveryRouteAsksForASessionAndEveryFormForItsToken()
{
await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite());
var endpoints = server.Services.GetRequiredService<EndpointDataSource>().Endpoints.OfType<RouteEndpoint>().ToList();
Assert.IsGreaterThan(60, endpoints.Count);
var open = new HashSet<string>(StringComparer.Ordinal);
var forms = new List<string>();
foreach (var e in endpoints)
{
var path = "/" + e.RoutePattern.RawText!.TrimStart('/');
if (e.Metadata.GetMetadata<IAllowAnonymous>() is not null)
{
open.Add(path);
}
else if (!path.StartsWith("/_", StringComparison.Ordinal))
{
Assert.IsNotNull(e.Metadata.GetMetadata<IAuthorizeData>(), path + " does not ask for a session.");
}
var writes = (e.Metadata.GetMetadata<IHttpMethodMetadata>()?.HttpMethods ?? []).Any(m => m is not ("GET" or "HEAD" or "OPTIONS"));
if (writes && path.StartsWith("/azioni", StringComparison.Ordinal))
{
Assert.IsTrue(e.Metadata.GetMetadata<IAntiforgeryMetadata>()?.RequiresValidation, path + " accepts a form without its token.");
forms.Add(path);
}
}
CollectionAssert.AreEquivalent(_open, open.ToList());
Assert.IsGreaterThan(30, forms.Count);
// And really: signed in, without the token, every form is refused.
await server.SignInFirstTimeAsync();
foreach (var form in forms)
{
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)),
form + ": " + answer.StatusCode);
}
using var unknown = await server.GetAsync("/qualcosa-che-non-esiste");
Assert.AreEqual(HttpStatusCode.NotFound, unknown.StatusCode);
server.Forget();
using var stranger = await server.GetAsync("/api/registri.zip");
Assert.AreEqual(HttpStatusCode.Unauthorized, stranger.StatusCode);
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task PagesAreNotKeptAndLargeBodiesAreRefused()
{
await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite());
await server.SignInFirstTimeAsync();
foreach (var path in new[] { "/", "/impostazioni", "/api/status", "/api/conti/posizioni.csv" })
{
using var page = await server.GetAsync(path);
StringAssert.Contains(page.Headers.CacheControl?.ToString(), "no-store", path);
Assert.AreEqual("", page.Headers.Server.ToString());
Assert.AreEqual("same-origin", page.Headers.GetValues("Cross-Origin-Opener-Policy").Single());
}
using (var style = await server.GetAsync("/assets/anubis.css"))
{
Assert.IsNull(style.Headers.CacheControl);
}
using (var content = new ByteArrayContent(new byte[(1024 * 1024) + 1]) { Headers = { { "Content-Type", "application/x-www-form-urlencoded" } } })
using (var large = await server.Http.PostAsync(new Uri("/azioni/accesso", UriKind.Relative), content))
{
Assert.IsTrue(large.StatusCode is HttpStatusCode.RequestEntityTooLarge or HttpStatusCode.BadRequest, large.StatusCode.ToString());
}
using var odd = await server.GetAsync("/api/diagnostica.md?ore=NaN");
Assert.AreEqual(HttpStatusCode.OK, odd.StatusCode);
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task TheLiveStatusEndsWithTheSession()
{
await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite());
await server.SignInFirstTimeAsync();
var address = new UriBuilder(server.BaseAddress) { Scheme = "ws", Path = "/ws" }.Uri;
using (var foreign = new ClientWebSocket())
{
foreign.Options.Cookies = server.Cookies;
foreign.Options.SetRequestHeader("Origin", "http://other.example");
await Assert.ThrowsAsync<WebSocketException>(() => foreign.ConnectAsync(address, CancellationToken.None));
}
using var socket = new ClientWebSocket();
socket.Options.Cookies = new CookieContainer();
socket.Options.Cookies.Add(server.Cookies.GetCookies(server.BaseAddress));
await socket.ConnectAsync(address, CancellationToken.None);
var buffer = new byte[8192];
Assert.AreEqual(WebSocketMessageType.Text, (await socket.ReceiveAsync(buffer, CancellationToken.None)).MessageType);
using (var bye = await server.PostFormAsync("/impostazioni", "/azioni/esci"))
{
Assert.AreEqual("/accesso", ServerHarness.Location(bye));
}
using var limit = new CancellationTokenSource(TimeSpan.FromSeconds(30));
while ((await socket.ReceiveAsync(buffer, limit.Token)).MessageType != WebSocketMessageType.Close)
{
}
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task WhereTheKeyOfTheModelGoesIsDecidedWithThePassword()
{
await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite());
var password = await server.SignInFirstTimeAsync();
var settings = server.Host.Services!.Settings;
await server.Host.Services.Secrets.SetAsync(NewsModelSettings.KeySecret, "chiave-del-modello-1", "test");
const string action = "/azioni/impostazioni/";
async Task<string> Save(string key, string value, string? with)
{
using var answer = await server.PostFormAsync("/impostazioni", action + key, ("ritorno", "/impostazioni"), ("valore", value), ("password", with ?? ""));
return ServerHarness.Location(answer);
}
StringAssert.Contains(await Save(NewsModelSettings.Address.Key, "https://collector.example/", null), "errore=password-rischio");
StringAssert.Contains(await Save(NewsModelSettings.Provider.Key, NewsModelProviders.OpenAi, "wrong-password-1"), "errore=password-rischio");
Assert.AreEqual("", (await settings.GetAsync(NewsModelSettings.Address.Key)).Value);
Assert.AreEqual(NewsModelProviders.Anthropic, (await settings.GetAsync(NewsModelSettings.Provider.Key)).Value);
Assert.AreEqual("/impostazioni", await Save(NewsModelSettings.Address.Key, "https://models.example/", password));
Assert.AreEqual("https://models.example/", (await settings.GetAsync(NewsModelSettings.Address.Key)).Value);
var csrf = await server.Http.GetFromJsonAsync<Dictionary<string, string>>(new Uri("/api/antiforgery", UriKind.Relative));
foreach (var key in NewsModelSettings.All.Concat(NewsRuleSettings.All).Select(d => d.Key))
{
using var request = new HttpRequestMessage(HttpMethod.Put, new Uri("/api/settings/" + key, UriKind.Relative)) { Content = JsonContent.Create(new { value = "off" }) };
request.Headers.Add(csrf!["header"], csrf["token"]);
using var put = await server.Http.SendAsync(request);
Assert.AreEqual(HttpStatusCode.BadRequest, put.StatusCode, key);
StringAssert.Contains(await put.Content.ReadAsStringAsync(), "usa_le_impostazioni");
}
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task WithRealMoneyARuleGoesOffOnlyWithThePhraseAndThePassword()
{
await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), trading: true);
var password = await server.SignInFirstTimeAsync();
var services = server.Host.Services!;
async Task<string> Switch(SettingDefinition rule, string value, params (string, string)[] more)
{
using var answer = await server.PostFormAsync("/impostazioni", "/azioni/impostazioni/" + rule.Key, [("ritorno", "/impostazioni"), ("valore", value), .. more]);
return ServerHarness.Location(answer);
}
Assert.AreEqual("/impostazioni", await Switch(NewsRuleSettings.Macro, "off"), "Without real money a switch is a switch.");
await services.Db.WriteAsync(s => s.ExecuteAsync("UPDATE strategy_state SET stage = 'reduced' WHERE strategy = 'crypto_trend'"));
Assert.IsTrue(await new StageBook(services.Db, server.Host.Clock, TradingConsent.None, (_, _, _) => Task.FromResult(false)).AnyLiveAsync(null, CancellationToken.None));
StringAssert.Contains(await server.TextAsync("/impostazioni"), "per spegnere la regola servono la frase e la password");
StringAssert.Contains(await Switch(NewsRuleSettings.Severe, "off"), "errore=frase-rischio");
StringAssert.Contains(await Switch(NewsRuleSettings.Severe, "off", ("frase", StageBook.RaisePhrase), ("password", "wrong-password-1")), "errore=password-rischio");
Assert.AreEqual("on", (await services.Settings.GetAsync(NewsRuleSettings.Severe.Key)).Value);
Assert.AreEqual("/impostazioni", await Switch(NewsRuleSettings.Severe, "off", ("frase", StageBook.RaisePhrase), ("password", password)));
Assert.AreEqual("/impostazioni", await Switch(NewsRuleSettings.Severe, "on"), "Back on is always free.");
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task NoPageAndNoDownloadShowsASecret()
{
const string heartbeat = "http://192.168.0.9/ping/segreto-del-segnale-1";
var env = ServerHarness.DockerSqlite();
env["FRED_API_KEY"] = "segreto-fred-ambiente-1";
env["ANUBIS_HEARTBEAT_URL"] = heartbeat;
await using var server = await ServerHarness.StartAsync("docker", env, trading: true);
var password = await server.SignInFirstTimeAsync();
var services = server.Host.Services!;
var values = new List<string> { "segreto-fred-ambiente-1", heartbeat, ServerHarness.SecretKey, ServerHarness.AdminPassword, password };
foreach (var (name, i) in TradingService.KeyFields(Venues.Okx).Concat(TradingService.KeyFields(Venues.Alpaca)).Select(k => k.Name)
.Concat([NewsModelSettings.KeySecret, "FINNHUB_API_KEY", "TELEGRAM_BOT_TOKEN"]).Select((n, i) => (n, i)))
{
values.Add("segreto-salvato-" + i);
await services.Secrets.SetAsync(name, "segreto-salvato-" + i, "test");
}
var hash = await services.Db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT password_hash FROM users", r => r.Text("password_hash")));
values.Add(hash!);
var paths = server.Services.GetRequiredService<EndpointDataSource>().Endpoints.OfType<RouteEndpoint>()
.Where(e => e.Metadata.GetMetadata<IHttpMethodMetadata>()?.HttpMethods.Contains("GET") != false)
.Select(e => "/" + e.RoutePattern.RawText!.TrimStart('/'))
.Where(p => !p.Contains('{', StringComparison.Ordinal) && !p.StartsWith("/_", StringComparison.Ordinal) && p != "/ws")
.Concat(["/api/secrets/OKX_API_KEY_DEMO", "/api/secrets/FRED_API_KEY", "/operazioni?pagina=1", "/api/data/quality?format=md&days=30"])
.Distinct().ToList();
Assert.IsGreaterThan(25, paths.Count);
foreach (var path in paths)
{
using var answer = await server.GetAsync(path);
var text = path.EndsWith(".zip", StringComparison.Ordinal) ? await UnzipAsync(answer) : WebUtility.HtmlDecode(await answer.Content.ReadAsStringAsync());
foreach (var value in values)
{
Assert.IsFalse(text.Contains(value, StringComparison.Ordinal), path + " shows " + value);
}
}
// The archive carries the keys encrypted, and nobody's session.
var folder = TempFolder.Create("archive-secrets");
var archive = Path.Combine(folder, "a");
await Archive.ExportAsync(services.Db, archive, server.Host.Clock);
foreach (var file in Directory.EnumerateFiles(archive))
{
var text = await File.ReadAllTextAsync(file);
foreach (var value in values.Where(v => v != hash))
{
Assert.IsFalse(text.Contains(value, StringComparison.Ordinal), file);
}
}
Assert.AreEqual(0L, new FileInfo(Path.Combine(archive, "sessions.jsonl")).Length);
TempFolder.Delete(folder);
}
private static async Task<string> UnzipAsync(HttpResponseMessage answer)
{
using var zip = new System.IO.Compression.ZipArchive(await answer.Content.ReadAsStreamAsync());
var text = new StringBuilder();
foreach (var entry in zip.Entries)
{
using var reader = new StreamReader(await entry.OpenAsync());
text.Append(await reader.ReadToEndAsync());
}
return text.ToString();
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task AKeyNeverFollowsARedirect()
{
var reached = 0;
await using var other = await FallbackAsync(_ => Results.Ok(Interlocked.Increment(ref reached)));
await using var broker = await FallbackAsync(c => Results.Redirect(other.Urls.Single() + c.Request.Path, permanent: false, preserveMethod: true));
var address = new Uri(broker.Urls.Single());
using var http = Outgoing.KeyedClient();
var trading = new TradingHttp(http, SystemClock.Instance, "prova", (_, _) => true);
Dictionary<string, string> headers = new() { ["APCA-API-SECRET-KEY"] = "segreto", ["OK-ACCESS-KEY"] = "chiave" };
var answer = await trading.SendAsync(HttpMethod.Post, new Uri(address, "/v2/orders"), "{}", _ => headers, null, retry: false, CancellationToken.None);
Assert.IsFalse(answer.Ok);
await Assert.ThrowsAsync<MarketDataException>(() => new ApiHttp(http, SystemClock.Instance, "prova").GetBytesAsync(new Uri(address, "/v2/bars"), null, headers, CancellationToken.None));
var reply = await new LanguageModel(http, new NewsModelConfig(NewsModelProviders.Anthropic, "m", address, 0m, 0m, 0m), "segreto")
.AskAsync(new ModelRequest("i", "m", [], 10), CancellationToken.None);
Assert.IsNull(reply.Text);
Assert.AreEqual(0, reached, "The other host must never be reached.");
}
private static async Task<WebApplication> FallbackAsync(Func<HttpContext, IResult> answer)
{
var builder = WebApplication.CreateSlimBuilder();
builder.WebHost.UseUrls("http://127.0.0.1:0");
var app = builder.Build();
app.MapFallback(answer);
await app.StartAsync();
return app;
}
/// <summary>The contact for the SEC is the user's own e-mail (ADR 0020): another host must never see it, on the client the service really uses.</summary>
[TestMethod]
[TestCategory(Category.Integration)]
public async Task TheContactOfTheSecNeverFollowsARedirect()
{
var reached = 0;
await using var other = await FallbackAsync(_ => Results.Ok(Interlocked.Increment(ref reached)));
await using var sec = await FallbackAsync(c => Results.Redirect(other.Urls.Single() + c.Request.Path));
await using var test = await DatabaseTests.MigratedAsync();
var bus = new EventBus();
using var market = new MarketDataService(test.Db, SystemClock.Instance, bus, new SettingsStore(test.Db, SystemClock.Instance, bus), new SecretStore(test.Db, SystemClock.Instance, new byte[32]), null);
var agent = new Dictionary<string, string> { ["User-Agent"] = Edgar.UserAgent("prova@esempio.it")! };
await Assert.ThrowsAsync<MarketDataException>(() => market.Sec.GetBytesAsync(new Uri(sec.Urls.Single() + "/files/company_tickers"), null, agent, CancellationToken.None));
Assert.AreEqual(0, reached);
}
[TestMethod]
[TestCategory(Category.Unit)]
[DataRow("POST", "/api/v5/asset/with" + "drawal")]
[DataRow("POST", "/api/v5/asset/trans" + "fer")]
[DataRow("POST", "/api/v5/account/set-" + "leverage")]
[DataRow("POST", "/api/v5/trade/amend-order")]
[DataRow("GET", "/api/v5/asset/balances")]
[DataRow("POST", "/v2/wal" + "lets/transfers")]
[DataRow("POST", "/v1/journals")]
[DataRow("DELETE", "/v2/positions")]
[DataRow("DELETE", "/v2/orders")]
[DataRow("DELETE", "/v2/orders/")]
[DataRow("DELETE", "/v2/orders/a/../../positions")]
[DataRow("PATCH", "/v2/account/configurations")]
public async Task WhatIsNotInTheListIsNeverSent(string method, string path)
{
var verb = new HttpMethod(method);
Assert.IsFalse(BrokerRequests.Okx(verb, path));
Assert.IsFalse(BrokerRequests.Alpaca(verb, path));
using var http = new FakeHttp();
var trading = new TradingHttp(http.Client(), SystemClock.Instance, "prova", BrokerRequests.Alpaca);
await Assert.ThrowsAsync<InvalidOperationException>(() => trading.SendAsync(verb, new Uri("https://example.test" + path), null, _ => new Dictionary<string, string>(), null,
retry: false, CancellationToken.None));
Assert.IsEmpty(http.Requests);
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheAccountsAreOpenedInTwoPlacesOnlyAndBothAskForTheConsent()
{
var code = Repo.Files().Where(f => f.Extension == ".cs" && Repo.Relative(f).StartsWith("src", StringComparison.Ordinal)).ToList();
var openers = code.Where(f => Opener().IsMatch(File.ReadAllText(f.FullName))).Select(f => f.Name).ToList();
CollectionAssert.AreEquivalent(new[] { "TradingService.cs", "GuardBrokers.cs" }, openers);
foreach (var name in new[] { "OkxTrading.cs", "AlpacaTrading.cs" })
{
StringAssert.Contains(File.ReadAllText(code.Single(f => f.Name == name).FullName), "LiveGuard.Ensure(options.Environment, consent);");
}
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheContainerIsHardened()
{
var entry = File.ReadAllText(Path.Combine(Repo.Root.FullName, "deploy", "docker", "entrypoint.sh"));
StringAssert.Contains(entry, "umask 077");
StringAssert.Contains(entry, "--no-new-privs");
StringAssert.Contains(entry, "PUID=0");
var template = File.ReadAllText(Path.Combine(Repo.Root.FullName, "deploy", "unraid", "anubis.xml"));
foreach (var name in new[] { "ANUBIS_DB_PASSWORD", "ANUBIS_SECRET_KEY", "ANUBIS_ADMIN_PASSWORD", "TELEGRAM_BOT_TOKEN", "ANUBIS_HEARTBEAT_URL", "ANUBIS_DB_URL" })
{
StringAssert.Matches(template, new Regex("Target=\"" + name + "\"[^>]*Mask=\"true\""), name);
}
}
[TestMethod]
[TestCategory(Category.Unit)]
public void AShortFirstPasswordIsAProblemOfTheConfiguration()
{
var env = ServerHarness.DockerSqlite();
env["ANUBIS_ADMIN_PASSWORD"] = "corta-1";
var config = DockerPlatform.Load(env);
Assert.AreEqual("ANUBIS_ADMIN_PASSWORD", config.Problems.Single().Setting);
}
[TestMethod]
[TestCategory(Category.Unit)]
public void ThePasswordInsideTheAddressIsMasked()
{
Assert.AreEqual("se:gre/to", new DbSettings { Engine = DbEngine.Postgres, Url = "postgres://anubis:se%3Agre%2Fto@db:5432/anubis" }.UrlPassword);
Assert.IsNull(new DbSettings { Engine = DbEngine.Postgres, Url = "postgres://anubis@db/anubis" }.UrlPassword);
}
[TestMethod]
[TestCategory(Category.Unit)]
public void ACellOfACsvIsNeverAFormula()
{
Assert.AreEqual("'=1+1", Format.CsvText("=1+1"));
Assert.AreEqual("'+cmd", Format.CsvText("+cmd"));
Assert.AreEqual("'-x", Format.CsvText("-x"));
Assert.AreEqual("'@y", Format.CsvText("@y"));
Assert.AreEqual("'\tz", Format.CsvText("\tz"));
Assert.AreEqual("\"a;b\"", Format.CsvText("a;b"));
Assert.AreEqual("\"a \"\"b\"\"\"", Format.CsvText("a \"b\""));
Assert.AreEqual("\"'\rx\"", Format.CsvText("\rx"));
Assert.AreEqual("-", Format.CsvText("-"));
Assert.AreEqual("", Format.CsvText(null));
var csv = Encoding.UTF8.GetString(Format.Csv(["a", "b"], [["=1", -5.3m]]));
StringAssert.Contains(csv, "'=1;-5,3");
}
[GeneratedRegex(@"\{[^}]*\}")]
private static partial Regex Parameter();
[GeneratedRegex(@"new (OkxTrading|AlpacaTrading)\(")]
private static partial Regex Opener();
}