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; /// /// 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 /api/ 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 richieste.prova.json with it. The copy writes nothing into the browser. Runs where Chromium and /// Xvfb are (the CI). /// [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); } /// The cookies of the site in the browser (names, values, paths), to compare before and after the copy. private static async Task 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)); } }