Files
Febe/tests/Febe.Tests/Web/LoginSecurityTests.cs
T
2026-10-14 00:59:18 +00:00

220 lines
10 KiB
C#

using System.Diagnostics;
using System.Net;
using System.Text.Json;
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]
public void 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");
var node = FindOnPath("node");
if (node is null)
{
Assert.Inconclusive("Node non è installato: la regola della pagina di accesso si prova solo dove c'è (CI, sviluppo).");
}
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"),
];
using var temp = new TempFolder("accesso-js");
var script = temp.Combine("prova.mjs");
var module = new Uri(Repository.PathOf("src", "Febe.Web", "wwwroot", "js", "core", "return-path.js")).AbsoluteUri;
File.WriteAllText(script, $$"""
import { returnAddress } from '{{module}}';
const cases = JSON.parse(process.argv[2]);
console.log(JSON.stringify(cases.map(v => returnAddress(v, '{{origin}}'))));
""");
var start = new ProcessStartInfo(node) { RedirectStandardOutput = true, RedirectStandardError = true };
start.ArgumentList.Add(script);
start.ArgumentList.Add(JsonSerializer.Serialize(cases.Select(c => c.Value)));
using var process = Process.Start(start)!;
var output = process.StandardOutput.ReadToEnd();
var errors = process.StandardError.ReadToEnd();
process.WaitForExit();
Assert.AreEqual(0, process.ExitCode, errors);
var results = JsonSerializer.Deserialize<string[]>(output)!;
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));
private static string? FindOnPath(string name)
{
foreach (var folder in (Environment.GetEnvironmentVariable("PATH") ?? string.Empty).Split(Path.PathSeparator, StringSplitOptions.RemoveEmptyEntries))
{
foreach (var candidate in new[] { name, name + ".exe" })
{
var path = Path.Combine(folder, candidate);
if (File.Exists(path))
{
return path;
}
}
}
return null;
}
}