Richiesta di Alberto (#59): decidere cosa scaricare prima, una Dashboard compatta come pagina iniziale da guardare mentre il motore lavora, e le miniature di ciò che è arrivato. - Dashboard (§7.9, §10.2): /dashboard è la pagina iniziale e la prima voce della barra; /, /attivita, «Ho finito» del browser, il riquadro di stato e il ritorno dopo l'accesso portano lì. In alto l'anteprima del browser sempre visibile, chiesta ogni secondo mentre il motore lavora (LiveBrowserPreview cattura al più un fotogramma al secondo), accanto cosa sta facendo e i quattro tetti; poi la striscia più bassa, la cronologia con le miniature e la coda ridotta alle prime righe con «Mostra tutta». Sotto i 1000 px una colonna sola. - Miniature della cronologia: /api/activity/arrived dà gli elementi che una ricetta ha salvato (account, inizio e fine della ricetta), chiesti solo quando la riga entra in vista, al più otto con «+N». Un clic apre un'anteprima leggera con foto o video senza audio, frecce fra i file della riga, Esc, «Apri nella Libreria» e «Apri l'account». - «Cosa scaricare prima» (§7.2, §6.5): ordine generale dei tipi in Impostazioni → Limiti e comportamento (trascinare, «Su» e «Giù», nota sulle storie che scadono), predefinito storie, evidenza, post, reel, taggati. Dopo il giro, il lavoro dovuto si estrae con il peso dell'account per il peso del tipo (16, 8, 4, 2, 1): pesa, non rende fisso. La coda dei file segue lo stesso ordine. - Prove: DownloadOrderTests (ordine, pesi, coda, motore con seme fisso: il primo tipo viene più spesso ma non sempre, il giro resta primo, un tipo senza lavoro non si visita), DashboardApiTests, una prova dell'interfaccia per / e /attivita. Non ancora fatto: ordine per account e segno del reel (serve una migrazione da concordare con E1), «Raggruppa i post» / «Tutte le foto», confronto con i mockup, revisione del resto della guida che nomina ancora Attività. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
193 lines
9.4 KiB
C#
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 + "/dashboard")),
|
|
(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));
|
|
}
|