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

122 lines
6.0 KiB
C#

using Febe.Core.Abstractions;
using Febe.Core.Collection;
using Febe.Core.Collection.Requests;
using Febe.SitoDiProva;
using Febe.Tests.Support;
using VirtualClock = Febe.Tests.Browser.TestSupport.VirtualClock;
namespace Febe.Tests.Collection;
/// <summary>
/// What the test site gives its pages for the copy at «Ho finito» (issue #36, S4, spec §14.2): the cookies a real site
/// sets (the session, <c>csrftoken</c>, one limited to <c>/api/</c>), a module registry of its own whose names are the
/// <c>page</c> section of <c>richieste.prova.json</c> (never Instagram's), and a <c>/api/graphql</c> that refuses a
/// wrong or missing value of the page as it refuses a wrong token. No browser.
/// </summary>
[TestClass]
[TestCategory(SyntheticSite.Category)]
public sealed class TestSiteSessionTests
{
public TestContext TestContext { get; set; } = null!;
[TestMethod]
public async Task AVisitSetsTheSessionCsrftokenAndTheApiPathCookie()
{
await using var site = await SyntheticSite.StartAsync();
using var client = new HttpClient(new SocketsHttpHandler { UseProxy = false, UseCookies = false, AllowAutoRedirect = false });
using var response = await client.GetAsync(new Uri(site.Url("/")), TestContext.CancellationToken);
var lines = response.Headers.GetValues("Set-Cookie").ToList();
string Line(string name) => lines.Single(l => l.StartsWith(name + "=", StringComparison.Ordinal));
StringAssert.Contains(Line(TestSite.SessionCookie), "path=/;");
StringAssert.Contains(Line(TestSite.SessionCookie).ToLowerInvariant(), "httponly");
var csrf = Line(TestSite.CsrfCookie);
StringAssert.Contains(csrf, "path=/;");
Assert.DoesNotContain("httponly", csrf.ToLowerInvariant(), "the page reads it to send it back in x-csrftoken");
StringAssert.Contains(Line(TestSite.ApiPathCookie), "path=/api/");
// A second visit with the session and the token keeps them: no new cookie.
var session = Line(TestSite.SessionCookie).Split(';')[0];
var token = csrf.Split(';')[0];
using var again = new HttpRequestMessage(HttpMethod.Get, new Uri(site.Url("/")));
again.Headers.TryAddWithoutValidation("Cookie", $"{session}; {token}");
using var second = await client.SendAsync(again, TestContext.CancellationToken);
Assert.IsFalse(second.Headers.Contains("Set-Cookie"));
}
[TestMethod]
public async Task ThePageModulesAreThoseOfTheCatalogsPageSectionWithTheValuesTheSiteChecks()
{
var catalog = RequestCatalog.LoadTestSite();
var page = catalog.Page!;
var modules = TestSite.PageModules("1234");
var expected = HttpSiteRequesterTests.PageValues();
foreach (var field in page.Order)
{
var source = page.Values[field];
Assert.IsTrue(modules.TryGetValue(source.Module, out var module), $"{field}: module {source.Module}");
Assert.IsTrue(module.TryGetValue(source.Property, out var value), $"{field}: {source}");
Assert.AreEqual(field == "account_id" ? "1234" : expected[field], value, field);
}
foreach (var operation in catalog.Operations.Where(o => o.Kind == OperationKind.GraphQl))
{
var module = page.DocIdModuleFor(operation.Name)!;
Assert.AreEqual(operation.Name + TestSite.DocIdModuleSuffix, module);
Assert.AreEqual(TestSite.DocIds[operation.Name], modules[module][string.Empty]);
}
// Never Instagram's names in the test site.
foreach (var name in modules.Keys)
{
Assert.DoesNotContain("instagram", name.ToLowerInvariant());
Assert.IsFalse(RequestCatalog.LoadInstagram().Page!.Values.Values.Any(s => s.Module == name), name);
}
// Every page of the site carries the registry first in its head.
await using var site = await SyntheticSite.StartAsync();
using var client = new HttpClient(new SocketsHttpHandler { UseProxy = false, UseCookies = false, AllowAutoRedirect = false });
foreach (var path in new[] { "/", "/benvenuto", "/profilo/marta.prova/" })
{
var html = await client.GetStringAsync(new Uri(site.Url(path)), TestContext.CancellationToken);
StringAssert.Contains(html, "<head><script>(function () {", path);
StringAssert.Contains(html, "__d(\"GettoniProva\"", path);
StringAssert.Contains(html, "__d(\"ProvaProfiloQuery_operazioneProva\"", path);
}
}
[TestMethod]
public async Task TheGraphQlQueryRefusesAWrongOrMissingValueOfThePage()
{
await using var site = await SyntheticSite.StartAsync();
var catalog = RequestCatalog.LoadTestSite();
var values = HttpSiteRequesterTests.Values();
async Task<int> StatusWith(string field, string? value, bool header = false)
{
var fields = values.Fields.ToDictionary(StringComparer.Ordinal);
if (value is null)
{
// A value the page did not give: the client cannot send the request at all.
fields.Remove(field);
}
else
{
fields[field] = value;
}
using var requester = new HttpSiteRequester(catalog, new InMemorySiteSession(new SiteSessionValues(values.Cookies, values.UserAgent, fields, values.DocIds)), HttpSiteRequesterOptions.TestSite(new Uri(site.SiteUrl + "/")), new VirtualClock());
var answer = await requester.SendAsync(HttpSiteRequesterTests.Graph(), Permit.Grant(ActionKind.ProfileOpen, null), CancellationToken.None);
return answer.Status;
}
Assert.AreEqual(200, await StatusWith("rev", TestSite.Revision), "the right values pass");
foreach (var field in new[] { "rev", "hs", "hsi", "ccg", "dpr", "comet_req", "entry_nonce" })
{
Assert.AreEqual(400, await StatusWith(field, "altro-valore"), field);
}
await Assert.ThrowsExactlyAsync<SiteSessionMissingException>(() => StatusWith("hsi", null));
}
}