Files
Febe/tests/Febe.Tests/Desktop/SavedSessionConnectionTests.cs
T
Alby96andClaude Opus 5.5 c69755db23 Sessione salvata: correzioni della revisione di S4b (#36)
Un errore imprevisto durante la copia senza «Ho finito» (database, disco) non trattiene più per sempre il permesso di guida: la copia scrive solo il tipo d'errore e la guida finisce lo stesso, così il motore non resta in «Stai usando il browser». Un «Ho finito» tardivo dopo una copia fatta lasciando il browser dice che la sessione era già stata copiata invece di chiedere un nuovo accesso. Il registro distingue la finestra chiusa da quella ridotta a icona troppo a lungo. /api/engine e gli eventi prendono «Serve «Ho finito»» dall'istantanea del motore (EngineSnapshot.SessionCopyMissing) senza chiedere al browser a ogni evento. La prova di WebView2 aspetta la riga del registro, non solo la sessione in memoria. Documenti: nove operazioni GraphQL con __spin_*, H23 descritta in prove-dal-vivo (parte E), guida aggiornata.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 12:13:25 +01:00

335 lines
17 KiB
C#

using System.Net;
using Febe.App;
using Febe.Core.Collection.Requests;
using Febe.Tests.Desktop.Support;
using Febe.Tests.Support;
namespace Febe.Tests.Desktop;
/// <summary>
/// The saved session in the shared composition (issue #36, S4, spec §6.0, §13.2, rule 7), with a fake browser: it
/// exists only with «raccolta» on «richieste» and configured operations (never with Instagram in S4, never by
/// default), «Ho finito» copies it only while Alberto's lease holds and only from a page of the site, «Annulla» copies
/// nothing, «Scollega» deletes it, and the test site's automatic login copies it too. Never Instagram.
/// </summary>
[TestClass]
public sealed class SavedSessionConnectionTests
{
private const string Site = "http://127.0.0.1:8481";
public TestContext TestContext { get; set; } = null!;
[TestMethod]
[Timeout(90_000, CooperativeCancellation = true)]
public async Task TheGateBuildsNothingWithInstagramNorByDefaultAndTheClientWithTheTestSiteAndRichieste()
{
var ct = TestContext.CancellationToken;
// Instagram with «richieste»: no operation is configured in S4, so nothing is built and nothing is read.
await using (var bed = await DesktopTestBed.StartAsync(["--raccolta", "richieste"]))
{
await bed.App.Running.WaitAsync(TimeSpan.FromSeconds(20), ct);
Assert.IsNull(bed.App.SavedSession);
Assert.IsNull(bed.App.SiteRequester);
var finish = await LoginAsync(bed);
Assert.DoesNotContain("Sessione copiata", finish);
Assert.AreEqual(0, bed.Browser!.FakeCdp.CaptureReads, "no module of Instagram's page is read");
Assert.IsFalse(Directory.Exists(bed.App.Data!.Session), "nothing in Dati/sessione");
}
// The test site by default («pagine»): the browser path, as before S4.
await using (var bed = await DesktopTestBed.StartAsync(["--sito-di-prova", Site]))
{
await bed.App.Running.WaitAsync(TimeSpan.FromSeconds(20), ct);
Assert.AreEqual(CollectionRoute.Pages, bed.App.Options.Collection);
Assert.IsNull(bed.App.SavedSession);
Assert.IsNull(bed.App.SiteRequester);
await LoginAsync(bed);
Assert.AreEqual(0, bed.Browser!.FakeCdp.CaptureReads);
Assert.IsFalse(Directory.Exists(bed.App.Data!.Session));
}
// The test site with «richieste»: the saved session, its copy and the site client.
await using (var bed = await DesktopTestBed.StartAsync(["--sito-di-prova", Site, "--raccolta", "richieste"]))
{
await bed.App.Running.WaitAsync(TimeSpan.FromSeconds(20), ct);
Assert.IsNotNull(bed.App.SavedSession);
Assert.IsNotNull(bed.App.SiteRequester);
Assert.AreEqual(SavedSessionState.None, bed.App.SavedSession.State);
}
}
[TestMethod]
[Timeout(90_000, CooperativeCancellation = true)]
public async Task HoFinitoSavesTheSessionAnnullaDoesNotAndScollegaDeletesIt()
{
var ct = TestContext.CancellationToken;
await using var bed = await StartAsync();
var app = bed.App;
var browser = bed.Browser!;
// «Annulla» after a login: nothing copied.
await BeginAsync(bed);
browser.FakeCdp.LoggedIn = true;
using (var cancel = await bed.SendAsync(HttpMethod.Post, "/api/connection/cancel"))
{
Assert.AreEqual(HttpStatusCode.NoContent, cancel.StatusCode);
}
Assert.AreEqual(0, browser.FakeCdp.CaptureReads);
Assert.IsNull(app.SavedSession!.Read());
// «Ho finito» on a page of the site: copied, encrypted on disk, before the page goes to rest.
var message = await LoginAsync(bed);
StringAssert.Contains(message, "Sessione copiata per le richieste di Febe.");
Assert.AreEqual(1, browser.FakeCdp.CaptureReads);
var saved = app.SavedSession.Read()!;
Assert.AreEqual("sessione-di-prova", saved.Cookie("sessione_prova"));
Assert.AreEqual("/api/", saved.Cookies.Single(c => c.Name == "percorso_api").Path);
Assert.IsNull(saved.Cookie("sessionid"), "another site's cookie is not copied");
Assert.AreEqual(Febe.SitoDiProva.TestSite.EntryNonce, saved.Fields["entry_nonce"]);
Assert.AreEqual("about:blank", browser.FakeCdp.Url, "then the page rests, as before");
var file = app.Data!.SessionFile;
Assert.IsTrue(File.Exists(file));
var bytes = File.ReadAllBytes(file);
CollectionAssert.AreEqual("FEBS"u8.ToArray(), bytes[..4], "the header of an encrypted session");
Assert.AreEqual(-1, System.Text.Encoding.ASCII.GetString(bytes).IndexOf("sessione-di-prova", StringComparison.Ordinal), "no value in clear");
Assert.IsFalse(browser.UserIsDriving, "«Ho finito» ends the lease after the copy");
// «Scollega»: the saved session goes with the profile, from memory and from disk.
using (var disconnect = await bed.SendAsync(HttpMethod.Post, "/api/connection/disconnect"))
{
Assert.AreEqual(HttpStatusCode.NoContent, disconnect.StatusCode);
}
Assert.IsNull(app.SavedSession.Read());
Assert.IsFalse(File.Exists(file));
Assert.AreEqual(1, browser.EmptiedProfiles);
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task ALateHoFinitoAfterTheLeaseEndedReadsNothingAndSaysTheSessionWasAlreadyCopied()
{
var ct = TestContext.CancellationToken;
await using var bed = await StartAsync();
var browser = bed.Browser!;
bed.App.Connection!.DrivingGrace = TimeSpan.FromMilliseconds(300);
await BeginAsync(bed);
browser.FakeCdp.LoggedIn = true;
browser.FakeCdp.Navigated(Site + "/");
// He puts the window away without «Ho finito»: the lease ends by itself, after the copy of S4b (its page is still
// his until then), and the page is the engine's again.
await browser.HideFromUserAsync(ct);
await DesktopTestBed.WaitUntilAsync(() => !browser.UserIsDriving, TimeSpan.FromSeconds(10), "la fine della guida");
Assert.AreEqual(1, browser.FakeCdp.CaptureReads, "copied once, before the lease ended");
var copied = bed.App.SavedSession!.Read();
Assert.IsNotNull(copied);
// «Ho finito» pressed late: nothing is read from a page that is not his, and he is not asked to log in again
// for a session copied a moment before.
var finish = await bed.JsonAsync(HttpMethod.Post, "/api/connection/finish");
Assert.IsTrue(finish.GetProperty("connected").GetBoolean());
var message = finish.GetProperty("message").GetString()!;
StringAssert.Contains(message, "era già stata copiata quando il browser è tornato al motore");
StringAssert.Contains(message, "Non serve rifare l'accesso");
Assert.DoesNotContain("non è stata copiata", message);
Assert.DoesNotContain("Rifai l'accesso", message);
Assert.AreEqual(1, browser.FakeCdp.CaptureReads, "nothing is read from a page that is not his");
Assert.AreSame(copied, bed.App.SavedSession.Read());
// A new use of the browser whose end copies nothing (the login page): a late «Ho finito» now says that this time
// the session was not copied, even if an earlier use had copied it.
await BeginAsync(bed, openLogin: false);
browser.FakeCdp.Navigated(Site + "/accesso/");
await browser.HideFromUserAsync(ct);
await DesktopTestBed.WaitUntilAsync(() => !browser.UserIsDriving, TimeSpan.FromSeconds(10), "la fine della guida sulla pagina di accesso");
finish = await bed.JsonAsync(HttpMethod.Post, "/api/connection/finish");
StringAssert.Contains(finish.GetProperty("message").GetString(), "non è stata copiata");
Assert.AreEqual(1, browser.FakeCdp.CaptureReads);
Assert.AreSame(copied, bed.App.SavedSession.Read());
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task HoFinitoOnAPageThatIsNotTheSiteKeepsTheOldSessionAndSaysSo()
{
await using var bed = await StartAsync();
var browser = bed.Browser!;
await LoginAsync(bed);
var first = bed.App.SavedSession!.Read()!;
// «Usa il browser», then «Ho finito» from another site's page.
await BeginAsync(bed, openLogin: false);
browser.FakeCdp.Navigated("https://altro.example.invalid/pagina");
var finish = await bed.JsonAsync(HttpMethod.Post, "/api/connection/finish");
var message = finish.GetProperty("message").GetString()!;
StringAssert.Contains(message, "non era su una pagina del sito");
StringAssert.Contains(message, "premi di nuovo «Ho finito»");
Assert.AreSame(first, bed.App.SavedSession.Read(), "a refused copy leaves the saved session as it was");
// And from the site's page again: a new copy replaces it.
await BeginAsync(bed, openLogin: false);
browser.FakeCdp.Navigated(Site + "/");
await bed.JsonAsync(HttpMethod.Post, "/api/connection/finish");
Assert.AreNotEqual(first.Capture, bed.App.SavedSession.Read()!.Capture);
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task AFailedDeleteOfTheSavedSessionMakesScollegaReportAPartialFailure()
{
await using var bed = await StartAsync();
await LoginAsync(bed);
var file = bed.App.Data!.SessionFile;
// Something the file system will not delete as a file stands where the session is.
File.Delete(file);
Directory.CreateDirectory(file);
using (var disconnect = await bed.SendAsync(HttpMethod.Post, "/api/connection/disconnect"))
{
Assert.AreEqual(HttpStatusCode.BadRequest, disconnect.StatusCode);
var text = await disconnect.Content.ReadAsStringAsync();
StringAssert.Contains(text, "sessione salvata");
}
Assert.IsNull(bed.App.SavedSession!.Read(), "not used any more, whatever the disk did");
Assert.AreEqual(1, bed.Browser!.EmptiedProfiles, "the profile is deleted all the same");
Directory.Delete(file);
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task WithPagineScollegaStillDeletesASessionLeftByARichiesteStartButKeepsTheKey()
{
var ct = TestContext.CancellationToken;
await using var bed = await DesktopTestBed.StartAsync(["--sito-di-prova", Site]);
await bed.App.Running.WaitAsync(TimeSpan.FromSeconds(20), ct);
Assert.IsNull(bed.App.SavedSession, "«pagine»: no saved session in this start");
StringAssert.Contains(ReadLog(bed), "Raccolta «pagine»", "the log says which route Febe took (§6.0)");
// What an earlier start with «richieste» left: the encrypted session, a broken write, the key.
var data = bed.App.Data!;
Directory.CreateDirectory(data.Session);
File.WriteAllText(data.SessionFile, "copia-di-prova");
var part = data.SessionFile + ".1234abcd" + Febe.Core.Security.OwnerOnlyFiles.PartSuffix;
File.WriteAllText(part, "resto");
var key = new byte[Febe.Core.Security.SessionKey.Length];
File.WriteAllBytes(data.SessionKeyFile, key);
using (var disconnect = await bed.SendAsync(HttpMethod.Post, "/api/connection/disconnect"))
{
Assert.AreEqual(HttpStatusCode.NoContent, disconnect.StatusCode);
}
Assert.IsFalse(File.Exists(data.SessionFile), "a session of the disconnected account never comes back at the next «richieste» start");
Assert.IsFalse(File.Exists(part));
Assert.IsTrue(File.Exists(data.SessionKeyFile), "chiave.bin stays, for the copy of the next login");
Assert.AreEqual(1, bed.Browser!.EmptiedProfiles);
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task HoFinitoOnAPageMissingAValueTheRequestsNeedSaysTheyStopAsADisconnection()
{
await using var bed = await StartAsync();
var browser = bed.Browser!;
// The page lacks one module (the nonce of AvvioProva) and the doc_id module.
var page = FakeCdp.DefaultPageCapture();
((System.Text.Json.Nodes.JsonObject)page["values"]!).Remove("entry_nonce");
((System.Text.Json.Nodes.JsonObject)page["docIds"]!).Remove(Febe.SitoDiProva.TestSite.ProfileQuery);
browser.FakeCdp.PageCapture = page;
var message = await LoginAsync(bed);
StringAssert.Contains(message, "mancavano 2 valori");
StringAssert.Contains(message, "non partono");
StringAssert.Contains(message, "disconnessione");
StringAssert.Contains(message, "«Usa il browser»");
Assert.DoesNotContain("restano al browser", message, "nothing sends those requests back to the browser");
var saved = bed.App.SavedSession!.Read()!;
Assert.IsFalse(saved.Fields.ContainsKey("entry_nonce"), "missing, never guessed");
}
[TestMethod]
public void EveryCopyMessageSaysWhatTheCodeDoesNext()
{
static string For(SessionCopyStatus status, Febe.Browser.Session.CaptureRefusal? refusal = null, int missing = 0, int docIds = 0) =>
BrowserConnectionService.CopyMessage(new SessionCopyOutcome(status, refusal, 3, missing, docIds));
Assert.AreEqual("Sessione copiata per le richieste di Febe.", For(SessionCopyStatus.Saved));
foreach (var partial in new[] { For(SessionCopyStatus.Saved, missing: 1, docIds: 1), For(SessionCopyStatus.SavedInMemoryOnly, missing: 2) })
{
StringAssert.Contains(partial, "mancavano 2 valori");
StringAssert.Contains(partial, "ha comunque sostituito quella salvata");
StringAssert.Contains(partial, "si ferma come disconnessione");
Assert.DoesNotContain("restano al browser", partial);
}
// «Ho finito» always ends the lease: after a refusal the advice is to open the browser again, never «Ho finito» alone.
foreach (var refusal in Enum.GetValues<Febe.Browser.Session.CaptureRefusal>())
{
var refused = For(SessionCopyStatus.Refused, refusal);
StringAssert.Contains(refused, "Riapri il browser dalla pagina Collegamento");
StringAssert.Contains(refused, "resta com'era");
Assert.DoesNotContain("Riprova più tardi con «Ho finito»", refused);
}
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task TheTestSitesAutomaticLoginCopiesTheSessionWhenTheGateIsOn()
{
var ct = TestContext.CancellationToken;
var shell = new FakeDesktopShell { OnCreated = b => b.FakeCdp.LogsInOnVisit = Site };
await using var bed = await DesktopTestBed.StartAsync(["--sito-di-prova", Site, "--accesso-di-prova", "--raccolta", "richieste"], shell);
await bed.App.Running.WaitAsync(TimeSpan.FromSeconds(20), ct);
Assert.IsTrue(bed.App.Connection!.IsConnected);
Assert.AreEqual(Febe.SitoDiProva.TestSite.Lsd, bed.App.SavedSession!.Read()!.Fields["lsd"]);
Assert.IsTrue(File.Exists(bed.App.Data!.SessionFile));
Assert.AreEqual("about:blank", bed.Browser!.FakeCdp.Url, "back to rest after the copy");
Assert.IsFalse(bed.Browser.UserIsDriving);
}
private async Task<DesktopTestBed> StartAsync()
{
var bed = await DesktopTestBed.StartAsync(["--sito-di-prova", Site, "--raccolta", "richieste"]);
await bed.App.Running.WaitAsync(TimeSpan.FromSeconds(20), TestContext.CancellationToken);
return bed;
}
/// <summary>The log files of this start, read while Febe still writes them.</summary>
private static string ReadLog(DesktopTestBed bed)
{
var folder = bed.App.Log.Folder;
Assert.IsNotNull(folder, "the log has a folder");
var text = new System.Text.StringBuilder();
foreach (var file in Directory.GetFiles(folder))
{
using var stream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
using var reader = new StreamReader(stream);
text.Append(reader.ReadToEnd());
}
return text.ToString();
}
private static async Task BeginAsync(DesktopTestBed bed, bool openLogin = true)
{
using var begin = await bed.SendAsync(HttpMethod.Post, "/api/connection/begin", openLogin ? """{"openLogin":true}""" : """{"openLogin":false}""");
Assert.AreEqual(HttpStatusCode.NoContent, begin.StatusCode);
}
/// <summary>«Accedi», Alberto logs in on the site's page, «Ho finito». Returns the message.</summary>
private static async Task<string> LoginAsync(DesktopTestBed bed)
{
await BeginAsync(bed);
bed.Browser!.FakeCdp.LoggedIn = true;
var finish = await bed.JsonAsync(HttpMethod.Post, "/api/connection/finish");
Assert.IsTrue(finish.GetProperty("connected").GetBoolean(), finish.GetProperty("message").GetString());
return finish.GetProperty("message").GetString()!;
}
}