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; /// /// 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 Secure whenever the browser talked /// HTTPS, also through the trusted proxy of FEBE_PROXY_FIDATO (websec-3). /// [TestClass] public sealed class LoginSecurityTests { private const string Password = "una password lunga"; /// Values of «torna» a crafted link could carry, each of which a browser resolves to another site. 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", "", ]; /// Paths of the interface, which must still work. 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( $"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 StartAsync(bool trustProxy) => WebTestServer.StartAsync(new FebeWebOptions { Access = AccessMode.Password, Password = Password, TrustForwardedHost = trustProxy, Lockout = new LockoutOptions { AttemptsPerClient = 50, AttemptsOverall = 50 }, }); private async Task 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)); }