Files
Febe/tests/Febe.Tests/Desktop/SavedSessionConnectionTests.cs
T
Alby96andClaude Opus 5.5 c87768766c
verifica / controlli (push) Successful in 22s
verifica / prove (push) Successful in 16m46s
verifica / installatore (push) Successful in 4m43s
verifica / immagine (push) Successful in 21m2s
Sessione salvata cifrata, copiata a «Ho finito» (#36, S4)
Il client del sito ha bisogno della sessione del browser di Febe: ora la copia
c'è, cifrata e dietro un interruttore, senza cambiare nulla di predefinito.

- Opzione «raccolta» (pagine predefinita, richieste): solo con «richieste» e
  almeno un'operazione configurata si costruiscono sessione salvata, client del
  sito e copia. Con Instagram nulla cambia: le dieci operazioni restano non
  configurate (mancano __spin_*, __req, __s, __dyn, __csr e altri).
- Cookie con dominio, percorso, solo-host, Secure, HttpOnly e scadenza, mandati
  solo dove il browser li manderebbe (RFC 6265).
- Sezione «page» del catalogo: dove la pagina tiene ogni valore; nuovi campi rev,
  hs, hsi, dpr, ccg, comet_req, entry_nonce. Il caricatore rifiuta
  un'operazione configurata con un valore di sessione senza fonte nella pagina.
- Dati/sessione/sessione.json: DPAPI su Windows, AES-256-GCM in Docker (chiave
  da FEBE_CHIAVE_SESSIONE o chiave.bin), scrittura atomica, file illeggibile =
  nessuna sessione. «Scollega» la cancella; chiave.bin resta.
- Copia a «Ho finito» con Network.getCookies e una sola Runtime.evaluate in sola
  lettura, solo da una pagina del sito e finché dura il permesso di guida.
- FEBE_PASSWORD e FEBE_CHIAVE_SESSIONE non passano a Chromium, Xvfb, ffmpeg.
- Sito di prova: csrftoken, cookie limitato a /api/, registro di moduli suo.
- Revisione su tre lenti: 11 punti confermati, tutti corretti.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 16:43:43 +01:00

314 lines
15 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 ALateHoFinitoAfterTheLeaseEndedDoesNotCopy()
{
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;
// He closes the window without «Ho finito»: the lease ends by itself, the page is the engine's again.
await browser.HideFromUserAsync(ct);
await DesktopTestBed.WaitUntilAsync(() => !browser.UserIsDriving, TimeSpan.FromSeconds(10), "la fine della guida");
browser.FakeCdp.Navigated(Site + "/");
var finish = await bed.JsonAsync(HttpMethod.Post, "/api/connection/finish");
Assert.IsTrue(finish.GetProperty("connected").GetBoolean());
StringAssert.Contains(finish.GetProperty("message").GetString(), "non è stata copiata");
Assert.AreEqual(0, browser.FakeCdp.CaptureReads, "nothing is read from a page that is not his");
Assert.IsNull(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()!;
}
}