Files
Febe/tests/Febe.Tests/Collection/SessionCaptureIntegrationTests.cs
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

138 lines
6.3 KiB
C#

using System.Security.Cryptography;
using System.Text.Json;
using System.Text.Json.Nodes;
using Febe.Browser.Cdp;
using Febe.Browser.Recipes;
using Febe.Browser.Session;
using Febe.Core.Abstractions;
using Febe.Core.Collection;
using Febe.Core.Collection.Requests;
using Febe.Core.Security;
using Febe.SitoDiProva;
using Febe.Tests.Collection.Support;
using Febe.Tests.Support;
using VirtualClock = Febe.Tests.Browser.TestSupport.VirtualClock;
namespace Febe.Tests.Collection;
/// <summary>
/// The copy at «Ho finito» with a real Chromium on the local test site (issue #36, S4, spec §6.0, §14.2), never
/// Instagram: the cookies the pages set (the one limited to <c>/api/</c> with its path), the user agent and the modules
/// of the page are copied into an encrypted saved session, and the site client then gets an answer to every configured
/// operation of <c>richieste.prova.json</c> with it. The copy writes nothing into the browser. Runs where Chromium and
/// Xvfb are (the CI).
/// </summary>
[TestClass]
[TestCategory(SyntheticSite.Category)]
[DoNotParallelize]
public sealed class SessionCaptureIntegrationTests
{
private static SharedChromium? s_chromium;
private static string? s_unavailable;
public TestContext TestContext { get; set; } = null!;
[ClassInitialize]
public static async Task StartAsync(TestContext context)
{
s_unavailable = SharedChromium.UnavailableReason();
if (s_unavailable is null)
{
s_chromium = await SharedChromium.StartAsync();
}
}
[ClassCleanup]
public static async Task StopAsync()
{
if (s_chromium is not null)
{
await s_chromium.DisposeAsync();
s_chromium = null;
}
}
[TestMethod]
[Timeout(180_000, CooperativeCancellation = true)]
public async Task ALoginOnTheTestSiteCopiedAtHoFinitoServesTheSiteClient()
{
if (s_unavailable is not null)
{
Assert.Inconclusive(s_unavailable);
}
var ct = TestContext.CancellationToken;
await using var site = await SyntheticSite.StartAsync();
var cdp = s_chromium!.Cdp;
// Alberto's login on the test site: a visit opens the session.
var navigation = await cdp.NavigateAsync(site.Url("/benvenuto"), ct);
Assert.IsTrue(navigation.Succeeded, navigation.ErrorText);
Assert.IsTrue(await cdp.WaitForLoadAsync(new SystemClock(), TimeSpan.FromSeconds(60), ct), "La pagina non ha finito di caricare.");
var plan = SessionCapturePlan.For(CollectionSite.TestSite(site.SiteHost, site.CdnHost), RequestCatalog.LoadTestSite(), SignalRules.LoadTestSite());
var before = await CookiesAsync(cdp, plan, ct);
var result = await SessionCapture.CaptureAsync(cdp, plan, new VirtualClock(), ct);
var after = await CookiesAsync(cdp, plan, ct);
Assert.IsNotNull(result.Values, result.ToString());
Assert.IsEmpty(result.MissingValues, string.Join(", ", result.MissingValues));
Assert.IsEmpty(result.MissingDocIds, string.Join(", ", result.MissingDocIds));
Assert.AreEqual(0, result.DroppedCookies);
Assert.AreEqual(before, after, "the copy writes no cookie into the browser");
Assert.IsFalse((await cdp.EvaluateAsync("navigator.webdriver === true", ct)).GetBoolean(), "the browser as it is");
var values = result.Values;
Assert.AreEqual((await cdp.EvaluateAsync("navigator.userAgent", ct)).GetString(), values.UserAgent);
CollectionAssert.IsSubsetOf(new[] { TestSite.SessionCookie, TestSite.CsrfCookie, TestSite.ApiPathCookie }, values.Cookies.Select(c => c.Name).ToArray());
var apiCookie = values.Cookies.Single(c => c.Name == TestSite.ApiPathCookie);
Assert.AreEqual(TestSite.ApiPath, apiCookie.Path, "the cookie limited to /api/ keeps its path");
Assert.AreEqual("127.0.0.1", apiCookie.Domain);
Assert.IsTrue(apiCookie.HostOnly);
Assert.AreEqual(TestSite.Lsd, values.Fields["lsd"]);
Assert.AreEqual(TestSite.Dpr, values.Fields["dpr"], "a number of the page as text");
Assert.AreEqual(TestSite.DocIds[TestSite.ProfileQuery], values.DocIds[TestSite.ProfileQuery]);
lock (site.World.Gate)
{
Assert.AreEqual(site.World.Viewer.Id, values.Fields["account_id"]);
}
// Into the encrypted file, read back by a new store as at the next start, then the site client.
using var temp = new TempFolder("sessione-copiata");
var protector = new AesGcmSessionProtector(RandomNumberGenerator.GetBytes(SessionKey.Length));
var file = temp.Combine("sessione", "sessione.json");
Assert.IsTrue(await new FileSiteSession(file, protector).ReplaceAsync(values, ct));
var restored = new FileSiteSession(file, protector);
Assert.AreEqual(SavedSessionState.Present, restored.State);
var catalog = RequestCatalog.LoadTestSite();
using var requester = new HttpSiteRequester(catalog, restored, HttpSiteRequesterOptions.TestSite(new Uri(site.SiteUrl + "/")), new VirtualClock());
var cases = HttpSiteRequesterTests.Cases(site);
foreach (var operation in catalog.Configured)
{
var answer = await requester.SendAsync(new SiteRequest(operation.Name, cases[operation.Name].Values), Permit.Grant(operation.Category, null), ct);
Assert.AreEqual(200, answer.Status, operation.Name);
Assert.IsTrue(answer.RootFieldsPresent, operation.Name);
}
Assert.AreEqual(catalog.Configured.Count(), site.Control.DirectRequests.Count);
}
/// <summary>The cookies of the site in the browser (names, values, paths), to compare before and after the copy.</summary>
private static async Task<string> CookiesAsync(ICdpSession cdp, SessionCapturePlan plan, CancellationToken ct)
{
var urls = new JsonArray();
foreach (var url in plan.CookieUrls)
{
urls.Add(url.AbsoluteUri);
}
var answer = await cdp.SendAsync("Network.getCookies", new JsonObject { ["urls"] = urls }, ct);
return string.Join(
"; ",
answer.GetProperty("cookies").EnumerateArray()
.Select(c => $"{c.GetProperty("name").GetString()}={c.GetProperty("value").GetString()}@{c.GetProperty("domain").GetString()}{c.GetProperty("path").GetString()}")
.Order(StringComparer.Ordinal));
}
}