La prova di accesso aspettava ancora /libreria per un «torna» mancante, mentre dal cambio a /dashboard il modulo return-path.js torna alla Dashboard: nella CI, con Chromium, sarebbe caduta. Ora la pagina attesa si legge e si controlla dal modulo prima di aprire il browser, così non può più divergere nemmeno dove Chromium manca. La specifica dava per decisi i 5 secondi di grazia in Docker prima che lasciare la pagina del browser copi la sessione e il posto su otto della coda dei file al file che aspetta da più tempo: sono scelte di chi ha costruito, non risposte di Alberto. Diventano proposte con le domande 20 e 21 di §16, come già diceva docs/stato.md; la guida dice lo stesso del posto su otto. §4.6 cita la conferma di «Elimina» com'è costruita da it.json, dice che in «In evidenza» l'interruttore «Raggruppa i post» / «Tutte le foto» manca e che «Tutte le foto» mostra solo i file presenti in libreria. Il messaggio d'esempio di §0 costruisce una schermata che esiste, la riga del mockup 06 rimanda a «Schermate della tappa D1», e due righe di prove-dal-vivo.md dicono Dashboard invece di Attività. docs/stato.md scrive i risultati dei controlli invece di rimandare al resoconto. Prove nuove in SpecificationConsistencyTests per ciascun punto, più una che ricostruisce la conferma da it.json e una sui risultati in stato.md. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
199 lines
9.9 KiB
C#
199 lines
9.9 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");
|
|
|
|
// Every missing or unsafe value goes to the page the module names, the Dashboard since stage D1. Read here, before
|
|
// the browser, so that the expected cases cannot drift from the module even where Chromium is missing.
|
|
const string home = "/dashboard";
|
|
var module = File.ReadAllText(Repository.PathOf("src", "Febe.Web", "wwwroot", "js", "core", "return-path.js"));
|
|
StringAssert.Contains(module, $"export const DEFAULT_PAGE = '{home}';", "the page after the login when «torna» is missing or unsafe");
|
|
|
|
const string origin = "http://tower:8480";
|
|
List<(string? Value, string Expected)> cases =
|
|
[
|
|
.. Foreign.Select(v => ((string?)v, origin + home)),
|
|
(null, origin + home),
|
|
("/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));
|
|
}
|