Files
Febe/tests/Febe.Tests/Web/LoginSecurityTests.cs
T
Alby96andClaude Opus 5.5 a4ad8a8bc4 CI senza azioni e senza Node, solo comandi scritti in casa (C6, 3/4)
Per la decisione di Alberto del 18 novembre 2026 (niente componenti esterni) i flussi
di verifica, rilascio e pulizia non usano più azioni JavaScript, che vogliono Node:

- sorgenti con git init/fetch e il gettone del lavoro, passato a git solo
  nell'ambiente del passo, mai scritto nella configurazione;
- SDK .NET con .gitea/scripts/dotnet.sh, dai metadati di Microsoft e verificato
  con lo SHA-512 prima di installarlo nella cache degli strumenti del runner;
- builder buildx creato da costruisci-immagine.sh builder;
- artefatti nel pacchetto generico febe-ci del registro di Gitea (artefatti.sh,
  con REGISTRY_TOKEN), tolti dalla pulizia del lunedì dopo 14 giorni; la release
  ricostruisce installatore e zip invece di riceverli da un altro lavoro;
- JSON letto con un lettore in awk POSIX (json.awk) per i controlli e per la
  scelta delle versioni del registro, al posto di versioni-registro.js;
- contenitore delle prove debian:trixie al posto di node:24-trixie;
- la prova della pagina di accesso gira in Chromium invece che in Node.

controlli.sh rifiuta ora un flusso con uses:, tabulazioni o rientri dispari, e le
prove nuove controllano l'assenza di Node, il passo dei sorgenti uguale in ogni
lavoro, l'SDK prima di ogni dotnet, la scelta dell'SDK, il caricamento degli
artefatti con un curl finto e la scadenza dei vecchi. Nessuna esecuzione vera di
Gitea Actions: ciò che resta da vedere è in docs/processo.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 14:41:49 +01:00

193 lines
9.4 KiB
C#

using System.Net;
using System.Text.Json;
using System.Text.Json.Nodes;
using Febe.Tests.Desktop.Support;
using Febe.Tests.Support;
using Febe.Tests.Web.Support;
using Febe.Web;
using Febe.Web.Security;
namespace Febe.Tests.Web;
/// <summary>
/// The login page of the Docker interface (spec §13.1): after the password it goes back only to a page of the interface
/// («torna»), never to another site (websec-2, web-8); the session cookie is <c>Secure</c> whenever the browser talked
/// HTTPS, also through the trusted proxy of <c>FEBE_PROXY_FIDATO</c> (websec-3).
/// </summary>
[TestClass]
public sealed class LoginSecurityTests
{
private const string Password = "una password lunga";
/// <summary>Values of «torna» a crafted link could carry, each of which a browser resolves to another site.</summary>
private static readonly string[] Foreign =
[
"//evil.example",
"/\\evil.example",
"/\\/evil.example",
"/\t/evil.example",
"/\n/evil.example",
"/\r/evil.example",
"\\\\evil.example",
"/./\\evil.example",
"http://evil.example/",
"https:evil.example",
"javascript:alert(1)",
" /libreria",
"/libreria\u0000",
"libreria",
"",
];
/// <summary>Paths of the interface, which must still work.</summary>
private static readonly string[] Own = ["/libreria", "/account/12", "/impostazioni/collegamento", "/libreria?tipo=foto#x", "/%5Cnon-un-sito", "/.//dentro"];
public TestContext TestContext { get; set; } = null!;
[TestMethod]
public void TheServerAcceptsOnlyPathsOfTheInterface()
{
foreach (var value in Foreign)
{
Assert.IsFalse(LoginReturn.IsSafe(value), JsonSerializer.Serialize(value));
Assert.AreEqual("/accesso", LoginReturn.LoginAddress(value));
}
Assert.IsFalse(LoginReturn.IsSafe(null));
Assert.IsFalse(LoginReturn.IsSafe("/" + new string('a', LoginReturn.MaxLength)));
foreach (var value in Own)
{
Assert.IsTrue(LoginReturn.IsSafe(value), value);
}
Assert.AreEqual("/accesso?torna=%2Faccount%2F12", LoginReturn.LoginAddress("/account/12"));
}
[TestMethod]
public async Task ACraftedLinkToTheLoginPageLosesItsReturnBeforeThePageShows()
{
await using var server = await StartAsync(trustProxy: false);
foreach (var page in new[] { "/accesso", "/accesso.html" })
{
foreach (var value in new[] { "/\\evil.example", "//evil.example", "/\t/evil.example", "http://evil.example/" })
{
using var response = await server.Client.GetAsync($"{page}?torna={Uri.EscapeDataString(value)}", TestContext.CancellationToken);
Assert.AreEqual(HttpStatusCode.Redirect, response.StatusCode, $"{page} {JsonSerializer.Serialize(value)}");
Assert.AreEqual("/accesso", response.Headers.Location?.OriginalString);
}
}
using (var own = await server.Client.GetAsync("/accesso?torna=%2Faccount%2F12", TestContext.CancellationToken))
{
Assert.AreEqual(HttpStatusCode.OK, own.StatusCode, "a page of the interface stays");
}
// A page asked through an address that a browser would read as another site: the login page, without «torna».
using (var crafted = await server.Client.GetAsync("/%5Cevil.example", TestContext.CancellationToken))
{
Assert.AreEqual(HttpStatusCode.Redirect, crafted.StatusCode);
Assert.AreEqual("/accesso", crafted.Headers.Location?.OriginalString);
}
using (var normal = await server.Client.GetAsync("/account/12", TestContext.CancellationToken))
{
Assert.AreEqual("/accesso?torna=%2Faccount%2F12", normal.Headers.Location?.OriginalString);
}
}
[TestMethod]
[Timeout(300_000, CooperativeCancellation = true)]
public async Task TheLoginPageGoesBackOnlyToAPageOfTheInterface()
{
var accesso = File.ReadAllText(Repository.PathOf("src", "Febe.Web", "wwwroot", "js", "accesso.js"));
StringAssert.Contains(accesso, "import { returnAddress } from './core/return-path.js';");
StringAssert.Contains(accesso, "location.href = returnAddress(");
Assert.DoesNotContain("startsWith('//')", accesso, "the old check let «/\\host» through");
const string origin = "http://tower:8480";
List<(string? Value, string Expected)> cases =
[
.. Foreign.Select(v => ((string?)v, origin + "/libreria")),
(null, origin + "/libreria"),
("/account/12", origin + "/account/12"),
("/libreria?tipo=foto#x", origin + "/libreria?tipo=foto#x"),
("/%5Cnon-un-sito", origin + "/%5Cnon-un-sito"),
// The path is normalised to «//dentro», but the page goes to the absolute address: still this site.
("/.//dentro", origin + "//dentro"),
];
// The rule runs where it runs for real: in Chromium, in the module the login page imports, served by Febe to a
// browser that has not logged in yet. No other JavaScript engine: the CI has no Node.
await using var ui = await UiBrowser.StartAsync();
await using var server = await StartAsync(trustProxy: false);
var page = new Uri(server.Address, "/accesso");
var navigation = await ui.SendAsync("Page.navigate", new JsonObject { ["url"] = page.AbsoluteUri });
Assert.IsFalse(navigation.TryGetProperty("errorText", out var error) && error.GetString() is { Length: > 0 }, $"apertura di {page}: {error}");
await ui.WaitAsync("location.pathname === '/accesso' && document.readyState === 'complete'", "pagina di accesso");
var values = JsonSerializer.Serialize(cases.Select(c => c.Value));
var results = await ui.EvalAsync<string[]>(
$"import('/js/core/return-path.js').then((m) => {values}.map((v) => m.returnAddress(v, {JsonSerializer.Serialize(origin)})))");
Assert.HasCount(cases.Count, results, ui.Report());
for (var i = 0; i < cases.Count; i++)
{
Assert.AreEqual(cases[i].Expected, results[i], JsonSerializer.Serialize(cases[i].Value));
Assert.AreEqual("tower:8480", new Uri(results[i]).Authority, "never another site");
}
}
[TestMethod]
public async Task TheSessionCookieIsSecureBehindTheTrustedProxyWithHttps()
{
// Plain HTTP on the network of home: no Secure, or the browser would drop the cookie.
await using (var plain = await StartAsync(trustProxy: false))
{
Assert.IsFalse(IsSecure(await LoginAsync(plain, origin: null, forwardedHost: null, forwardedProto: null)));
// Without FEBE_PROXY_FIDATO the header is anybody's: it changes nothing.
Assert.IsFalse(IsSecure(await LoginAsync(plain, origin: null, forwardedHost: null, forwardedProto: "https")));
}
await using var proxied = await StartAsync(trustProxy: true);
Assert.IsTrue(IsSecure(await LoginAsync(proxied, origin: "https://febe.example.org", forwardedHost: "febe.example.org", forwardedProto: "https")));
Assert.IsTrue(IsSecure(await LoginAsync(proxied, origin: null, forwardedHost: null, forwardedProto: "https, http")), "the value the proxy next to the browser wrote");
Assert.IsFalse(IsSecure(await LoginAsync(proxied, origin: null, forwardedHost: null, forwardedProto: "http")), "the proxy says the browser used HTTP");
var session = await LoginAsync(proxied, origin: null, forwardedHost: null, forwardedProto: null);
Assert.IsFalse(IsSecure(session), "LAN access next to the proxy");
using var logout = proxied.Request(HttpMethod.Post, "/api/uscita");
logout.Headers.TryAddWithoutValidation("Cookie", session.Split(';')[0]);
logout.Headers.TryAddWithoutValidation("X-Forwarded-Proto", "https");
using var response = await proxied.Client.SendAsync(logout, TestContext.CancellationToken);
Assert.IsTrue(IsSecure(response.Headers.GetValues("Set-Cookie").Single()), "the logout clears the same cookie");
}
private static Task<WebTestServer> StartAsync(bool trustProxy) => WebTestServer.StartAsync(new FebeWebOptions
{
Access = AccessMode.Password,
Password = Password,
TrustForwardedHost = trustProxy,
Lockout = new LockoutOptions { AttemptsPerClient = 50, AttemptsOverall = 50 },
});
private async Task<string> LoginAsync(WebTestServer server, string? origin, string? forwardedHost, string? forwardedProto)
{
using var request = server.Request(HttpMethod.Post, "/api/accesso", new { password = Password }, origin ?? string.Empty);
if (forwardedHost is not null)
{
request.Headers.TryAddWithoutValidation("X-Forwarded-Host", forwardedHost);
}
if (forwardedProto is not null)
{
request.Headers.TryAddWithoutValidation("X-Forwarded-Proto", forwardedProto);
}
using var response = await server.Client.SendAsync(request, TestContext.CancellationToken);
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, await response.Content.ReadAsStringAsync(TestContext.CancellationToken));
return response.Headers.GetValues("Set-Cookie").Single();
}
private static bool IsSecure(string setCookie) =>
setCookie.Split(';').Any(part => string.Equals(part.Trim(), "secure", StringComparison.OrdinalIgnoreCase));
}