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>
This commit is contained in:
1 parent
3046b2da47
commit
c87768766c
69 files changed
+5936
-415
No files matched your search
@@ -0,0 +1,410 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
using Febe.App;
|
||||
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.Tests.Browser.TestSupport;
|
||||
|
||||
namespace Febe.Tests.Browser;
|
||||
|
||||
/// <summary>
|
||||
/// The copy of the browser's session at «Ho finito» (issue #36, S4, spec §6.0, §6.1 «Copiare la sessione»), against a
|
||||
/// fake page: only <c>Page.getFrameTree</c>, <c>Network.getCookies</c> and one read-only <c>Runtime.evaluate</c>; the
|
||||
/// cookies with their domains and paths, the modules the catalog names and nothing else, a missing value left out and
|
||||
/// never guessed (rule 9), and no value in any text (rule 10). Never Instagram, never a browser.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class SessionCaptureTests
|
||||
{
|
||||
private const string SiteHost = "127.0.0.1:8481";
|
||||
private const string UserAgent = "Mozilla/5.0 (X11; Linux x86_64) Agente di prova";
|
||||
|
||||
private static readonly CollectionSite Site = CollectionSite.TestSite(SiteHost, "127.0.0.2:8482");
|
||||
private static readonly SessionCapturePlan Plan = SessionCapturePlan.For(Site, RequestCatalog.LoadTestSite(), SignalRules.LoadTestSite());
|
||||
|
||||
/// <summary>The secrets of the fake page: none may appear in a text, a message or a log line.</summary>
|
||||
private static readonly string[] Secrets = ["valore-sessione-segreto", "valore-csrf-segreto", "valore-api-segreto", "lsd-segreto", "nonce-segreto", "9000000000000009"];
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheCopySendsOnlyGetCookiesAndOneEvaluateThatPassesTheGuard()
|
||||
{
|
||||
var cdp = Page($"http://{SiteHost}/profilo/marta.prova/");
|
||||
var result = await SessionCapture.CaptureAsync(cdp, Plan, new VirtualClock(), CancellationToken.None);
|
||||
|
||||
Assert.IsNotNull(result.Values, result.ToString());
|
||||
CollectionAssert.AreEqual(new[] { "Page.getFrameTree", "Network.getCookies", "Runtime.evaluate" }, cdp.Sent.Select(c => c.Method).ToArray());
|
||||
Assert.IsTrue(cdp.Sent.All(c => CdpCommandPolicy.IsAllowed(c.Method)), "only commands of §6.1");
|
||||
var evaluation = cdp.Sent.Single(c => c.Method == "Runtime.evaluate").Parameters!;
|
||||
ReadOnlyScriptGuard.EnsureReadOnly(evaluation["expression"]!.GetValue<string>());
|
||||
Assert.IsTrue(evaluation["returnByValue"]!.GetValue<bool>());
|
||||
Assert.IsFalse(evaluation["awaitPromise"]!.GetValue<bool>(), "nothing asynchronous in the page");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void GetCookiesAsksTheSiteRootAndEveryCatalogPathPrefix()
|
||||
{
|
||||
var urls = Plan.CookieUrls.Select(u => u.AbsoluteUri).ToList();
|
||||
Assert.AreEqual($"http://{SiteHost}/", urls[0], "the root first");
|
||||
CollectionAssert.Contains(urls, $"http://{SiteHost}/api/graphql");
|
||||
Assert.IsTrue(urls.All(u => u.StartsWith($"http://{SiteHost}/", StringComparison.Ordinal)), "only the site");
|
||||
Assert.IsFalse(urls.Any(u => u.Contains('{', StringComparison.Ordinal) || u.Contains("%7B", StringComparison.OrdinalIgnoreCase)), "a path is cut before its first value");
|
||||
Assert.IsTrue(urls.Any(u => u.StartsWith($"http://{SiteHost}/api/dati/", StringComparison.Ordinal)), "the addresses of the plain operations too");
|
||||
Assert.AreEqual(urls.Count, urls.Distinct().Count());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task CookiesKeepValueDomainPathSecureAndExpiryAndOthersAreLeftOut()
|
||||
{
|
||||
var expiry = new DateTimeOffset(2027, 1, 1, 0, 0, 0, TimeSpan.Zero);
|
||||
var cdp = Page($"http://{SiteHost}/", cookies: new JsonArray(
|
||||
Cookie("sessione_prova", "valore-sessione-segreto", "127.0.0.1", expires: expiry.ToUnixTimeSeconds()),
|
||||
Cookie("csrftoken", "valore-csrf-segreto", "127.0.0.1"),
|
||||
Cookie("percorso_api", "valore-api-segreto", "127.0.0.1", "/api/", secure: true),
|
||||
Cookie("altrove", "valore", "esempio.invalid"),
|
||||
Cookie("diviso", "valore", "127.0.0.1", partitioned: true),
|
||||
Cookie("strano", "valore;con-separatore", "127.0.0.1"),
|
||||
Cookie("accentato", "caffè", "127.0.0.1")));
|
||||
|
||||
var result = await SessionCapture.CaptureAsync(cdp, Plan, new VirtualClock(), CancellationToken.None);
|
||||
var values = result.Values!;
|
||||
CollectionAssert.AreEqual(new[] { "sessione_prova", "csrftoken", "percorso_api" }, values.Cookies.Select(c => c.Name).ToArray(), "another host's cookie is not the site's");
|
||||
Assert.AreEqual(3, result.DroppedCookies, "partitioned, «;» and non-ASCII values are left out and counted");
|
||||
|
||||
var session = values.Cookies[0];
|
||||
Assert.AreEqual("valore-sessione-segreto", session.Value);
|
||||
Assert.AreEqual("127.0.0.1", session.Domain);
|
||||
Assert.IsTrue(session.HostOnly);
|
||||
Assert.AreEqual("/", session.Path);
|
||||
Assert.IsTrue(session.HttpOnly);
|
||||
Assert.AreEqual(expiry, session.Expires);
|
||||
Assert.IsNull(values.Cookies[1].Expires, "a session cookie has no expiry");
|
||||
|
||||
var api = values.Cookies[2];
|
||||
Assert.AreEqual("/api/", api.Path, "a cookie limited to a path keeps it");
|
||||
Assert.IsTrue(api.Secure);
|
||||
Assert.IsNull(values.CookieFor("percorso_api", new Uri($"http://{SiteHost}/"), new VirtualClock().Now), "never sent outside its path");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ADomainCookieOfInstagramIsKeptAsADomainCookie()
|
||||
{
|
||||
var plan = SessionCapturePlan.For(CollectionSite.Instagram, RequestCatalog.LoadInstagram(), SignalRules.LoadDefault());
|
||||
var cdp = Page("https://www.instagram.com/", cookies: new JsonArray(
|
||||
Cookie("sessionid", "valore-sessione-segreto", ".instagram.com", secure: true),
|
||||
Cookie("altro", "valore", ".example.invalid")));
|
||||
|
||||
var result = await SessionCapture.CaptureAsync(cdp, plan, new VirtualClock(), CancellationToken.None);
|
||||
var cookie = result.Values!.Cookies.Single();
|
||||
Assert.AreEqual("instagram.com", cookie.Domain);
|
||||
Assert.IsFalse(cookie.HostOnly, "a leading dot is a domain cookie");
|
||||
Assert.IsTrue(cookie.Secure);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheUserAgentIsNavigatorUserAgentAsItIsAndThePageValuesComeFromTheCatalogModulesOnly()
|
||||
{
|
||||
var cdp = Page($"http://{SiteHost}/");
|
||||
var result = await SessionCapture.CaptureAsync(cdp, Plan, new VirtualClock(), CancellationToken.None);
|
||||
var values = result.Values!;
|
||||
Assert.AreEqual(UserAgent, values.UserAgent);
|
||||
Assert.AreEqual("lsd-segreto", values.Fields["lsd"]);
|
||||
Assert.AreEqual("1", values.Fields["dpr"], "a number of the page as text");
|
||||
Assert.AreEqual("9000000000000009", values.DocIds["ProvaProfiloQuery"]);
|
||||
Assert.IsFalse(values.Fields.ContainsKey("estraneo"), "a value the plan did not ask is ignored");
|
||||
Assert.IsFalse(values.DocIds.ContainsKey("AltraQuery"));
|
||||
|
||||
// The expression names exactly the modules of the catalog's page section, and the GraphQL operations of the catalog.
|
||||
var expression = SessionCaptureScript.Build(Plan);
|
||||
var catalog = RequestCatalog.LoadTestSite();
|
||||
foreach (var source in catalog.Page!.Values.Values)
|
||||
{
|
||||
StringAssert.Contains(expression, $"read(\"{source.Module}\", \"{source.Property}\")");
|
||||
}
|
||||
|
||||
StringAssert.Contains(expression, "read(\"ProvaProfiloQuery_operazioneProva\", null)");
|
||||
Assert.AreEqual(catalog.Page.Values.Count + 1, CountOf(expression, "const v = read("), "one read per value and doc_id, nothing else");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheExpressionPassesTheGuardForBothShippedCatalogs()
|
||||
{
|
||||
foreach (var (site, catalog, rules) in new[]
|
||||
{
|
||||
(Site, RequestCatalog.LoadTestSite(), SignalRules.LoadTestSite()),
|
||||
(CollectionSite.Instagram, RequestCatalog.LoadInstagram(), SignalRules.LoadDefault()),
|
||||
})
|
||||
{
|
||||
var expression = SessionCaptureScript.Build(SessionCapturePlan.For(site, catalog, rules));
|
||||
Assert.IsTrue(ReadOnlyScriptGuard.IsReadOnly(expression), site.Name);
|
||||
Assert.DoesNotContain("document.cookie", expression);
|
||||
Assert.DoesNotContain("Storage", expression);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task AMissingModuleOrANonStringOrAControlCharacterValueIsMissingNotGuessed()
|
||||
{
|
||||
var page = PageValues();
|
||||
var values = (JsonObject)page["values"]!;
|
||||
values.Remove("hsi");
|
||||
values["hs"] = new JsonObject { ["oggetto"] = true };
|
||||
values["rev"] = "con\naccapo";
|
||||
values["ccg"] = new string('x', SessionCapture.MaxValueLength + 1);
|
||||
((JsonObject)page["docIds"]!).Remove("ProvaProfiloQuery");
|
||||
var cdp = Page($"http://{SiteHost}/", page: page);
|
||||
|
||||
var result = await SessionCapture.CaptureAsync(cdp, Plan, new VirtualClock(), CancellationToken.None);
|
||||
CollectionAssert.AreEquivalent(new[] { "hsi", "hs", "rev", "ccg" }, result.MissingValues.ToArray());
|
||||
CollectionAssert.AreEqual(new[] { "ProvaProfiloQuery" }, result.MissingDocIds.ToArray());
|
||||
foreach (var name in result.MissingValues)
|
||||
{
|
||||
Assert.IsFalse(result.Values!.Fields.ContainsKey(name), name);
|
||||
}
|
||||
|
||||
Assert.IsEmpty(result.Values!.DocIds);
|
||||
Assert.AreEqual("lsd-segreto", result.Values.Fields["lsd"], "the others are copied");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task NotOnTheSiteOrOnItsLoginOrVerificationPageNothingIsRead()
|
||||
{
|
||||
foreach (var (url, refusal) in new[]
|
||||
{
|
||||
("about:blank", CaptureRefusal.NotOnSite),
|
||||
("http://127.0.0.2:8482/file.jpg", CaptureRefusal.NotOnSite),
|
||||
("https://altro.example.invalid/", CaptureRefusal.NotOnSite),
|
||||
($"http://{SiteHost}/verifica?motivo=prova", CaptureRefusal.CheckpointPage),
|
||||
($"http://{SiteHost}/accesso/", CaptureRefusal.CheckpointPage),
|
||||
($"http://{SiteHost}/sessione-scaduta", CaptureRefusal.CheckpointPage),
|
||||
})
|
||||
{
|
||||
var cdp = Page(url);
|
||||
var result = await SessionCapture.CaptureAsync(cdp, Plan, new VirtualClock(), CancellationToken.None);
|
||||
Assert.IsNull(result.Values, url);
|
||||
Assert.AreEqual(refusal, result.Refusal, url);
|
||||
CollectionAssert.AreEqual(new[] { "Page.getFrameTree" }, cdp.Sent.Select(c => c.Method).ToArray(), url);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ABrowserErrorOrNoUserAgentRefusesWithoutThePageText()
|
||||
{
|
||||
var failing = Page($"http://{SiteHost}/");
|
||||
failing.Responder = (method, parameters) => method switch
|
||||
{
|
||||
"Page.getFrameTree" => Frame($"http://{SiteHost}/"),
|
||||
"Runtime.evaluate" => new JsonObject { ["exceptionDetails"] = new JsonObject { ["text"] = "lsd-segreto è nella pagina" } },
|
||||
_ => Cookies(),
|
||||
};
|
||||
var error = await SessionCapture.CaptureAsync(failing, Plan, new VirtualClock(), CancellationToken.None);
|
||||
Assert.AreEqual(CaptureRefusal.BrowserError, error.Refusal);
|
||||
AssertNoSecret(error.ToString());
|
||||
|
||||
var page = PageValues();
|
||||
page["ua"] = null;
|
||||
var noAgent = await SessionCapture.CaptureAsync(Page($"http://{SiteHost}/", page: page), Plan, new VirtualClock(), CancellationToken.None);
|
||||
Assert.AreEqual(CaptureRefusal.NoUserAgent, noAgent.Refusal);
|
||||
|
||||
var thrower = new ThrowingCdp();
|
||||
var gone = await SessionCapture.CaptureAsync(thrower, Plan, new VirtualClock(), CancellationToken.None);
|
||||
Assert.AreEqual(CaptureRefusal.BrowserError, gone.Refusal);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheCopierSavesReplacesOrThrowsAwayAndItsLogAndTextsHoldNoValue()
|
||||
{
|
||||
var log = new List<string>();
|
||||
var store = new InMemorySiteSession(null);
|
||||
var copier = new BrowserSessionCopier(Page($"http://{SiteHost}/"), Plan, store, new VirtualClock(), log.Add);
|
||||
|
||||
var first = await copier.CopyAsync(() => true, CancellationToken.None);
|
||||
Assert.AreEqual(SessionCopyStatus.Saved, first.Status);
|
||||
var saved = store.Read()!;
|
||||
Assert.AreEqual("valore-sessione-segreto", saved.Cookie("sessione_prova"));
|
||||
|
||||
// A second copy replaces the session with a new capture; one the page stopped being Alberto's meanwhile is thrown away.
|
||||
var second = await copier.CopyAsync(() => true, CancellationToken.None);
|
||||
Assert.AreEqual(SessionCopyStatus.Saved, second.Status);
|
||||
Assert.AreNotEqual(saved.Capture, store.Read()!.Capture, "a new login replaces the session (§6.0)");
|
||||
var kept = store.Read();
|
||||
var late = await copier.CopyAsync(() => false, CancellationToken.None);
|
||||
Assert.AreEqual(SessionCopyStatus.Discarded, late.Status);
|
||||
Assert.AreSame(kept, store.Read(), "a copy thrown away touches nothing");
|
||||
|
||||
// Not on the site: refused, the saved session stays.
|
||||
var away = new BrowserSessionCopier(Page("about:blank"), Plan, store, new VirtualClock(), log.Add);
|
||||
Assert.AreEqual(CaptureRefusal.NotOnSite, (await away.CopyAsync(() => true, CancellationToken.None)).Refusal);
|
||||
Assert.AreSame(kept, store.Read());
|
||||
|
||||
Assert.HasCount(4, log);
|
||||
foreach (var text in log.Append(saved.ToString()).Append(first.ToString()).Append(Plan.ToString()).Append(saved.Cookies[0].ToString()))
|
||||
{
|
||||
AssertNoSecret(text);
|
||||
}
|
||||
|
||||
StringAssert.Contains(log[0], "Sessione copiata: 3 cookie");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheCopierCountsAsMissingOnlyWhatAConfiguredOperationSends()
|
||||
{
|
||||
// The test site's catalog with its GraphQL query not configured: only the plain operations remain, which send
|
||||
// app_id and the user agent; rev, hsi and the query's doc_id are read but no configured request waits for them.
|
||||
var file = JsonNode.Parse(SiteMap.ReadEmbeddedText("richieste.prova.json"))!.AsObject();
|
||||
var query = file["operations"]!.AsArray().Select(o => o!.AsObject()).Single(o => o["name"]!.GetValue<string>() == "ProvaProfiloQuery");
|
||||
query["configured"] = false;
|
||||
query["reason"] = "Non configurata per la prova.";
|
||||
var plan = SessionCapturePlan.For(Site, RequestCatalog.Parse(file.ToJsonString(), "richieste.prova.json (prova)"), SignalRules.LoadTestSite());
|
||||
CollectionAssert.AreEquivalent(new[] { "app_id" }, plan.NeededValues.ToArray());
|
||||
Assert.IsEmpty(plan.NeededDocIds);
|
||||
CollectionAssert.Contains(Plan.NeededDocIds.ToArray(), "ProvaProfiloQuery", "configured in the shipped test catalog");
|
||||
|
||||
var page = PageValues();
|
||||
((JsonObject)page["values"]!).Remove("hsi");
|
||||
((JsonObject)page["values"]!).Remove("rev");
|
||||
((JsonObject)page["docIds"]!).Remove("ProvaProfiloQuery");
|
||||
var log = new List<string>();
|
||||
var unused = await new BrowserSessionCopier(Page($"http://{SiteHost}/", page: page), plan, new InMemorySiteSession(null), new VirtualClock(), log.Add)
|
||||
.CopyAsync(() => true, CancellationToken.None);
|
||||
Assert.AreEqual(SessionCopyStatus.Saved, unused.Status);
|
||||
Assert.AreEqual(0, unused.MissingValues + unused.MissingDocIds, "nothing a configured request sends is missing");
|
||||
StringAssert.Contains(log[^1], "che nessuna operazione configurata usa");
|
||||
|
||||
((JsonObject)page["values"]!).Remove("app_id");
|
||||
var needed = await new BrowserSessionCopier(Page($"http://{SiteHost}/", page: page), plan, new InMemorySiteSession(null), new VirtualClock(), log.Add)
|
||||
.CopyAsync(() => true, CancellationToken.None);
|
||||
Assert.AreEqual(1, needed.MissingValues);
|
||||
Assert.AreEqual(0, needed.MissingDocIds);
|
||||
StringAssert.Contains(log[^1], "mancano app_id, che servono alle operazioni configurate");
|
||||
|
||||
// With the shipped catalog the query is configured: its doc_id counts.
|
||||
var shipped = await new BrowserSessionCopier(Page($"http://{SiteHost}/", page: page), Plan, new InMemorySiteSession(null), new VirtualClock(), log.Add)
|
||||
.CopyAsync(() => true, CancellationToken.None);
|
||||
Assert.AreEqual(3, shipped.MissingValues, "app_id, hsi and rev");
|
||||
Assert.AreEqual(1, shipped.MissingDocIds);
|
||||
AssertNoSecret(string.Join("\n", log));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(20_000, CooperativeCancellation = true)]
|
||||
public async Task ABrowserThatDoesNotAnswerIsABrowserErrorAfterTheTimeout()
|
||||
{
|
||||
var store = new InMemorySiteSession(null);
|
||||
var copier = new BrowserSessionCopier(new HangingCdp(), Plan, store, new VirtualClock(), _ => { }) { Timeout = TimeSpan.FromMilliseconds(200) };
|
||||
var outcome = await copier.CopyAsync(() => true, CancellationToken.None);
|
||||
Assert.AreEqual(SessionCopyStatus.Refused, outcome.Status);
|
||||
Assert.AreEqual(CaptureRefusal.BrowserError, outcome.Refusal);
|
||||
Assert.IsNull(store.Read());
|
||||
}
|
||||
|
||||
private static int CountOf(string text, string part)
|
||||
{
|
||||
var count = 0;
|
||||
for (var at = text.IndexOf(part, StringComparison.Ordinal); at >= 0; at = text.IndexOf(part, at + part.Length, StringComparison.Ordinal))
|
||||
{
|
||||
count++;
|
||||
}
|
||||
|
||||
return count;
|
||||
}
|
||||
|
||||
private static void AssertNoSecret(string text)
|
||||
{
|
||||
foreach (var secret in Secrets)
|
||||
{
|
||||
Assert.DoesNotContain(secret, text);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A page at <paramref name="url"/> that answers the three commands of the copy.</summary>
|
||||
private static FakeCdpSession Page(string url, JsonArray? cookies = null, JsonObject? page = null)
|
||||
{
|
||||
var cdp = new FakeCdpSession(new VirtualClock());
|
||||
cdp.Responder = (method, _) => method switch
|
||||
{
|
||||
"Page.getFrameTree" => Frame(url),
|
||||
"Network.getCookies" => cookies is null ? Cookies() : new JsonObject { ["cookies"] = JsonNode.Parse(cookies.ToJsonString()) },
|
||||
"Runtime.evaluate" => new JsonObject { ["result"] = new JsonObject { ["type"] = "object", ["value"] = JsonNode.Parse((page ?? PageValues()).ToJsonString()) } },
|
||||
_ => null,
|
||||
};
|
||||
return cdp;
|
||||
}
|
||||
|
||||
private static JsonObject Frame(string url) =>
|
||||
new() { ["frameTree"] = new JsonObject { ["frame"] = new JsonObject { ["id"] = "F1", ["url"] = url } } };
|
||||
|
||||
private static JsonObject Cookies() => new()
|
||||
{
|
||||
["cookies"] = new JsonArray(
|
||||
Cookie("sessione_prova", "valore-sessione-segreto", "127.0.0.1"),
|
||||
Cookie("csrftoken", "valore-csrf-segreto", "127.0.0.1"),
|
||||
Cookie("percorso_api", "valore-api-segreto", "127.0.0.1", "/api/")),
|
||||
};
|
||||
|
||||
private static JsonObject Cookie(string name, string value, string domain, string path = "/", bool secure = false, long? expires = null, bool partitioned = false)
|
||||
{
|
||||
var cookie = new JsonObject
|
||||
{
|
||||
["name"] = name,
|
||||
["value"] = value,
|
||||
["domain"] = domain,
|
||||
["path"] = path,
|
||||
["expires"] = expires ?? -1,
|
||||
["session"] = expires is null,
|
||||
["secure"] = secure,
|
||||
["httpOnly"] = true,
|
||||
};
|
||||
if (partitioned)
|
||||
{
|
||||
cookie["partitionKey"] = new JsonObject { ["topLevelSite"] = "http://esempio.invalid", ["hasCrossSiteAncestor"] = false };
|
||||
}
|
||||
|
||||
return cookie;
|
||||
}
|
||||
|
||||
private static JsonObject PageValues() => new()
|
||||
{
|
||||
["ua"] = UserAgent,
|
||||
["values"] = new JsonObject
|
||||
{
|
||||
["lsd"] = "lsd-segreto",
|
||||
["fb_dtsg"] = "dtsg-di-prova",
|
||||
["account_id"] = "1234",
|
||||
["app_id"] = "applicazione",
|
||||
["rev"] = "revisione",
|
||||
["hs"] = "hs",
|
||||
["hsi"] = "hsi",
|
||||
["dpr"] = "1",
|
||||
["comet_req"] = "7",
|
||||
["ccg"] = "BUONA",
|
||||
["entry_nonce"] = "nonce-segreto",
|
||||
["estraneo"] = "non chiesto",
|
||||
},
|
||||
["docIds"] = new JsonObject { ["ProvaProfiloQuery"] = "9000000000000009", ["AltraQuery"] = "1" },
|
||||
};
|
||||
|
||||
/// <summary>A browser that went away: every command fails.</summary>
|
||||
private sealed class ThrowingCdp : ICdpSession
|
||||
{
|
||||
public Task<JsonElement> SendAsync(string method, object? parameters = null, CancellationToken ct = default) =>
|
||||
throw new CdpDisconnectedException();
|
||||
|
||||
public IDisposable On(string eventName, Action<JsonElement> handler) => throw new NotSupportedException();
|
||||
}
|
||||
|
||||
/// <summary>A browser that never answers until cancelled.</summary>
|
||||
private sealed class HangingCdp : ICdpSession
|
||||
{
|
||||
public async Task<JsonElement> SendAsync(string method, object? parameters = null, CancellationToken ct = default)
|
||||
{
|
||||
await Task.Delay(Timeout.Infinite, ct);
|
||||
return default;
|
||||
}
|
||||
|
||||
public IDisposable On(string eventName, Action<JsonElement> handler) => throw new NotSupportedException();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,393 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using Febe.Core.Collection.Requests;
|
||||
using Febe.Core.Library;
|
||||
using Febe.Core.Security;
|
||||
using Febe.Tests.Support;
|
||||
|
||||
namespace Febe.Tests.Collection;
|
||||
|
||||
/// <summary>
|
||||
/// The saved session on disk (issue #36, S4, spec §6.0, §13.2): Dati/sessione/sessione.json encrypted, owner-only,
|
||||
/// replaced at once; read back by a new start as a new capture; renewals serialised and kept in memory when the disk
|
||||
/// refuses them; «Scollega» deletes it for good; a file that cannot be read is no session, never a crash; no value in
|
||||
/// clear on disk, in a text or in a log line.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class FileSiteSessionTests
|
||||
{
|
||||
private static readonly DateTimeOffset Now = new(2026, 11, 17, 10, 0, 0, TimeSpan.Zero);
|
||||
private static readonly Uri Graph = new("https://www.instagram.com/api/graphql");
|
||||
|
||||
private static readonly string[] Secrets =
|
||||
[
|
||||
"segreto-sessione-1", "segreto-csrf-2", "segreto-percorso-3", "segreto-lsd-4", "segreto-dtsg-5", "segreto-rev-6",
|
||||
"segreto-nonce-7", "segreto-docid-8", "segreto-agente-9", "segreto-claim-10",
|
||||
];
|
||||
|
||||
[TestMethod]
|
||||
public async Task WhatIsWrittenIsReadBackByANewInstance()
|
||||
{
|
||||
using var folder = new TempFolder("sessione");
|
||||
var layout = new DataFolderLayout(folder.Path);
|
||||
var protector = Protector();
|
||||
var store = new FileSiteSession(layout.SessionFile, protector);
|
||||
Assert.AreEqual(SavedSessionState.None, store.State);
|
||||
Assert.IsNull(store.Read());
|
||||
|
||||
var values = Values();
|
||||
Assert.IsTrue(await store.ReplaceAsync(values, CancellationToken.None));
|
||||
Assert.AreSame(values, store.Read());
|
||||
Assert.AreEqual(SavedSessionState.Present, store.State);
|
||||
Assert.IsFalse(store.Unsaved);
|
||||
Assert.AreEqual(Path.Combine(folder.Path, "sessione", "sessione.json"), store.FilePath, "Dati/sessione/sessione.json.");
|
||||
|
||||
var restored = new FileSiteSession(layout.SessionFile, protector).Read();
|
||||
Assert.IsNotNull(restored);
|
||||
Assert.AreEqual(SavedSessionState.Present, new FileSiteSession(layout.SessionFile, protector).State);
|
||||
CollectionAssert.AreEqual(
|
||||
values.Cookies.Select(Describe).ToArray(),
|
||||
restored.Cookies.Select(Describe).ToArray(),
|
||||
"Name, value, domain, host-only, path, secure, HTTP-only and expiry, in order.");
|
||||
Assert.AreEqual(values.UserAgent, restored.UserAgent);
|
||||
CollectionAssert.AreEquivalent(values.Fields.ToArray(), restored.Fields.ToArray());
|
||||
CollectionAssert.AreEquivalent(values.DocIds.ToArray(), restored.DocIds.ToArray());
|
||||
Assert.AreEqual(values.CopiedAt, restored.CopiedAt);
|
||||
Assert.AreEqual("segreto-percorso-3", restored.CookieFor("ds_user_id", Graph, Now), "The path cookie still goes to /api/.");
|
||||
Assert.IsNull(restored.CookieFor("ds_user_id", new Uri("https://www.instagram.com/marta/"), Now));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task AValueReadBackIsANewCaptureSoALateRenewalOfTheOldProcessTouchesNothing()
|
||||
{
|
||||
using var folder = new TempFolder("sessione");
|
||||
var file = Path.Combine(folder.Path, "sessione", "sessione.json");
|
||||
var protector = Protector();
|
||||
var before = new FileSiteSession(file, protector);
|
||||
var values = Values();
|
||||
await before.ReplaceAsync(values, CancellationToken.None);
|
||||
|
||||
var after = new FileSiteSession(file, protector);
|
||||
var restored = after.Read()!;
|
||||
Assert.AreNotEqual(values.Capture, restored.Capture, "A new start is a new capture.");
|
||||
Assert.AreNotEqual(restored.Capture, new SiteSessionValues([], "agente").Capture, "And later captures never reuse its id.");
|
||||
|
||||
await after.UpdateAsync(new SiteSessionUpdate([Cookie("sessionid", "vecchia-risposta")], capture: values.Capture), CancellationToken.None);
|
||||
Assert.AreEqual("segreto-sessione-1", after.Read()!.Cookie("sessionid"));
|
||||
Assert.AreEqual("segreto-sessione-1", new FileSiteSession(file, protector).Read()!.Cookie("sessionid"), "Nor the file.");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheFileHoldsNoValueInClear()
|
||||
{
|
||||
using var folder = new TempFolder("sessione");
|
||||
var file = Path.Combine(folder.Path, "sessione.json");
|
||||
var store = new FileSiteSession(file, Protector());
|
||||
await store.ReplaceAsync(Values(), CancellationToken.None);
|
||||
|
||||
var bytes = File.ReadAllBytes(file);
|
||||
Assert.AreEqual("FEBS", Encoding.ASCII.GetString(bytes, 0, 4));
|
||||
foreach (var secret in Secrets.Append("sessionid").Append("instagram"))
|
||||
{
|
||||
foreach (var form in new[] { Encoding.UTF8.GetBytes(secret), Encoding.Unicode.GetBytes(secret), Encoding.ASCII.GetBytes(Convert.ToBase64String(Encoding.UTF8.GetBytes(secret))) })
|
||||
{
|
||||
Assert.AreEqual(-1, bytes.AsSpan().IndexOf(form), $"«{secret}» is on disk in clear.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task AFailedWriteKeepsTheRenewedCookiesInMemoryAndIsTriedAgainLater()
|
||||
{
|
||||
using var folder = new TempFolder("sessione");
|
||||
var file = Path.Combine(folder.Path, "sessione.json");
|
||||
var protector = new FlakyProtector(Protector());
|
||||
var log = new ConcurrentQueue<string>();
|
||||
var store = new FileSiteSession(file, protector, log.Enqueue);
|
||||
await store.ReplaceAsync(Values(), CancellationToken.None);
|
||||
var capture = store.Read()!.Capture;
|
||||
|
||||
// The site rotated csrftoken: the disk refuses, the memory keeps the new value (the old one no longer works).
|
||||
protector.Fail = true;
|
||||
await store.UpdateAsync(new SiteSessionUpdate([Csrf("segreto-rinnovo-11")], capture: capture), CancellationToken.None);
|
||||
await store.UpdateAsync(new SiteSessionUpdate([Csrf("segreto-rinnovo-12")], capture: capture), CancellationToken.None);
|
||||
Assert.AreEqual("segreto-rinnovo-12", store.Read()!.Cookie("csrftoken"));
|
||||
Assert.IsTrue(store.Unsaved);
|
||||
Assert.AreEqual("segreto-csrf-2", new FileSiteSession(file, Protector(protector)).Read()!.Cookie("csrftoken"), "The file is the old one, whole.");
|
||||
Assert.AreEqual(1, log.Count(l => l.Contains("non scritta", StringComparison.Ordinal)), "One line for a run of failures:\n" + string.Join("\n", log));
|
||||
Assert.IsFalse(Directory.GetFiles(folder.Path).Any(f => f.EndsWith(OwnerOnlyFiles.PartSuffix, StringComparison.Ordinal)));
|
||||
|
||||
// A failed copy at «Ho finito» still replaces the session in memory, and says it is not on disk.
|
||||
Assert.IsFalse(await store.ReplaceAsync(Values(csrf: "segreto-nuovo-accesso-13"), CancellationToken.None));
|
||||
Assert.AreEqual("segreto-nuovo-accesso-13", store.Read()!.Cookie("csrftoken"));
|
||||
capture = store.Read()!.Capture;
|
||||
|
||||
protector.Fail = false;
|
||||
await store.UpdateAsync(new SiteSessionUpdate([Cookie("mid", "segreto-mid-14")], capture: capture), CancellationToken.None);
|
||||
Assert.IsFalse(store.Unsaved);
|
||||
var reread = new FileSiteSession(file, Protector(protector)).Read()!;
|
||||
Assert.AreEqual("segreto-nuovo-accesso-13", reread.Cookie("csrftoken"), "The next write carries everything kept in memory.");
|
||||
Assert.AreEqual("segreto-mid-14", reread.Cookie("mid"));
|
||||
Assert.IsTrue(log.Any(l => l.Contains("di nuovo", StringComparison.Ordinal)));
|
||||
AssertNoSecret(log);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task AWriteTheDiskRefusesAfterEncryptionLeavesNoPartFileKeepsTheMemoryAndTheNextWriteSucceeds()
|
||||
{
|
||||
using var folder = new TempFolder("sessione");
|
||||
var file = Path.Combine(folder.Path, "sessione.json");
|
||||
var protector = Protector();
|
||||
var log = new ConcurrentQueue<string>();
|
||||
var store = new FileSiteSession(file, protector, log.Enqueue);
|
||||
|
||||
// Something the rename cannot replace stands where the session goes: the part file is written, the move fails.
|
||||
Directory.CreateDirectory(file);
|
||||
Assert.IsFalse(await store.ReplaceAsync(Values(), CancellationToken.None));
|
||||
Assert.IsTrue(store.Unsaved);
|
||||
Assert.AreEqual("segreto-csrf-2", store.Read()!.Cookie("csrftoken"), "Kept in memory.");
|
||||
Assert.IsEmpty(Directory.GetFiles(folder.Path, "*" + OwnerOnlyFiles.PartSuffix), "A failed write leaves no part file.");
|
||||
Assert.AreEqual(1, log.Count(l => l.Contains("non scritta", StringComparison.Ordinal)), string.Join("\n", log));
|
||||
|
||||
// The obstacle goes: the next write carries what memory kept.
|
||||
Directory.Delete(file);
|
||||
var capture = store.Read()!.Capture;
|
||||
await store.UpdateAsync(new SiteSessionUpdate([Cookie("mid", "segreto-mid-14")], capture: capture), CancellationToken.None);
|
||||
Assert.IsFalse(store.Unsaved);
|
||||
var reread = new FileSiteSession(file, protector).Read()!;
|
||||
Assert.AreEqual("segreto-csrf-2", reread.Cookie("csrftoken"));
|
||||
Assert.AreEqual("segreto-mid-14", reread.Cookie("mid"));
|
||||
|
||||
if (OperatingSystem.IsWindows())
|
||||
{
|
||||
// On Windows a file held open without sharing cannot be replaced: the old file stays whole.
|
||||
var before = File.ReadAllBytes(file);
|
||||
using (new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.None))
|
||||
{
|
||||
await store.UpdateAsync(new SiteSessionUpdate([Cookie("mid", "segreto-mid-15")], capture: capture), CancellationToken.None);
|
||||
}
|
||||
|
||||
Assert.IsTrue(store.Unsaved);
|
||||
CollectionAssert.AreEqual(before, File.ReadAllBytes(file), "The old file is intact.");
|
||||
Assert.IsEmpty(Directory.GetFiles(folder.Path, "*" + OwnerOnlyFiles.PartSuffix));
|
||||
}
|
||||
|
||||
AssertNoSecret(log);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ConcurrentUpdatesAreSerializedAndNoneIsLost()
|
||||
{
|
||||
using var folder = new TempFolder("sessione");
|
||||
var file = Path.Combine(folder.Path, "sessione.json");
|
||||
var protector = Protector();
|
||||
var store = new FileSiteSession(file, protector);
|
||||
await store.ReplaceAsync(Values(), CancellationToken.None);
|
||||
var capture = store.Read()!.Capture;
|
||||
|
||||
await Task.WhenAll(Enumerable.Range(0, 40).Select(i => Task.Run(() =>
|
||||
store.UpdateAsync(new SiteSessionUpdate([Cookie("c" + i.ToString(System.Globalization.CultureInfo.InvariantCulture), "v")], capture: capture), CancellationToken.None))));
|
||||
|
||||
Assert.AreEqual(Values().Cookies.Count + 40, store.Read()!.Cookies.Count);
|
||||
Assert.AreEqual(Values().Cookies.Count + 40, new FileSiteSession(file, protector).Read()!.Cookies.Count, "The last write holds every update.");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task DeleteRemovesTheFileAndItsLeftoversAndNoLateUpdateBringsItBack()
|
||||
{
|
||||
using var folder = new TempFolder("sessione");
|
||||
var file = Path.Combine(folder.Path, "sessione.json");
|
||||
var protector = new FlakyProtector(Protector());
|
||||
var log = new List<string>();
|
||||
var store = new FileSiteSession(file, protector, log.Add);
|
||||
await store.ReplaceAsync(Values(), CancellationToken.None);
|
||||
var capture = store.Read()!.Capture;
|
||||
File.WriteAllText(file + ".1234abcd" + OwnerOnlyFiles.PartSuffix, "resto");
|
||||
|
||||
// An update waits behind a write that is in progress; «Scollega» comes; whatever the order they get the gate
|
||||
// in, no session is left.
|
||||
using var hold = new ManualResetEventSlim(false);
|
||||
protector.Hold = hold;
|
||||
var replacing = Task.Run(() => store.ReplaceAsync(store.Read()!, CancellationToken.None));
|
||||
Assert.IsTrue(protector.Entered.Wait(TimeSpan.FromSeconds(30)));
|
||||
var updating = store.UpdateAsync(new SiteSessionUpdate([Cookie("tardivo", "x")], capture: capture), CancellationToken.None);
|
||||
var deleting = store.DeleteAsync(CancellationToken.None);
|
||||
hold.Set();
|
||||
await Task.WhenAll(replacing, updating, deleting);
|
||||
await store.UpdateAsync(new SiteSessionUpdate([Cookie("tardivo", "y")], capture: capture), CancellationToken.None);
|
||||
|
||||
Assert.IsNull(store.Read());
|
||||
Assert.AreEqual(SavedSessionState.None, store.State);
|
||||
Assert.IsFalse(File.Exists(file));
|
||||
Assert.AreEqual(0, Directory.GetFiles(folder.Path).Length, "No part file left either.");
|
||||
Assert.IsNull(new FileSiteSession(file, protector).Read());
|
||||
Assert.IsTrue(log.Any(l => l.Contains("cancellata", StringComparison.Ordinal)));
|
||||
|
||||
await store.DeleteAsync(CancellationToken.None);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task AnUnreadableFileIsNoSessionAndIsLeftAsItIs()
|
||||
{
|
||||
using var folder = new TempFolder("sessione");
|
||||
var file = Path.Combine(folder.Path, "sessione.json");
|
||||
var protector = Protector();
|
||||
await new FileSiteSession(file, protector).ReplaceAsync(Values(), CancellationToken.None);
|
||||
var written = File.ReadAllBytes(file);
|
||||
|
||||
// Another key (a new FEBE_CHIAVE_SESSIONE, another user for DPAPI), a damaged file, another format.
|
||||
var cases = new (string File, ISessionProtector Protector, byte[] Bytes)[]
|
||||
{
|
||||
(file, Protector(), written),
|
||||
(Path.Combine(folder.Path, "rovinato.json"), protector, [.. written.Take(written.Length - 3)]),
|
||||
(Path.Combine(folder.Path, "testo.json"), protector, Encoding.UTF8.GetBytes("""{"format":1,"cookies":[]}""")),
|
||||
(Path.Combine(folder.Path, "formato.json"), protector, protector.Protect(Encoding.UTF8.GetBytes("""{"format":9,"segreto":"segreto-formato-15"}"""))),
|
||||
(Path.Combine(folder.Path, "cookie.json"), protector, protector.Protect(Encoding.UTF8.GetBytes("""{"format":1,"userAgent":"a","cookies":[{"name":"a=b","value":"segreto-cookie-16","domain":"x","hostOnly":true,"path":"/","secure":false,"httpOnly":false}],"fields":{},"docIds":{}}"""))),
|
||||
};
|
||||
foreach (var (path, reader, bytes) in cases)
|
||||
{
|
||||
if (path != file)
|
||||
{
|
||||
File.WriteAllBytes(path, bytes);
|
||||
}
|
||||
|
||||
var log = new List<string>();
|
||||
var store = new FileSiteSession(path, reader, log.Add);
|
||||
Assert.IsNull(store.Read(), path);
|
||||
Assert.AreEqual(SavedSessionState.Unreadable, store.State, path);
|
||||
CollectionAssert.AreEqual(bytes, File.ReadAllBytes(path), "Left as it is.");
|
||||
Assert.AreEqual(1, log.Count);
|
||||
StringAssert.Contains(log[0], "illeggibile");
|
||||
Assert.IsFalse(log[0].Contains("segreto", StringComparison.Ordinal) || log[0].Contains(path, StringComparison.Ordinal), log[0]);
|
||||
Assert.AreEqual("Sessione salvata illeggibile.", store.ToString());
|
||||
|
||||
// A renewal finds no session; a new login replaces the file.
|
||||
await store.UpdateAsync(new SiteSessionUpdate([Cookie("x", "y")]), CancellationToken.None);
|
||||
Assert.IsNull(store.Read());
|
||||
Assert.IsTrue(await store.ReplaceAsync(Values(), CancellationToken.None));
|
||||
Assert.AreEqual(SavedSessionState.Present, new FileSiteSession(path, reader).State);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheFolderAndTheFileAreOwnerOnlyOnUnix()
|
||||
{
|
||||
using var folder = new TempFolder("sessione");
|
||||
var layout = new DataFolderLayout(folder.Path);
|
||||
await new FileSiteSession(layout.SessionFile, Protector()).ReplaceAsync(Values(), CancellationToken.None);
|
||||
|
||||
Assert.IsTrue(File.Exists(layout.SessionFile));
|
||||
Assert.AreEqual(layout.Session, Path.GetDirectoryName(layout.SessionFile));
|
||||
Assert.AreEqual(layout.Session, Path.GetDirectoryName(layout.SessionKeyFile));
|
||||
if (!OperatingSystem.IsWindows())
|
||||
{
|
||||
Assert.AreEqual(OwnerOnlyFiles.OwnerFile, File.GetUnixFileMode(layout.SessionFile));
|
||||
Assert.AreEqual(OwnerOnlyFiles.OwnerFolder, File.GetUnixFileMode(layout.Session));
|
||||
}
|
||||
|
||||
// The daily copies and the diagnostic report live elsewhere and never look in Dati/sessione.
|
||||
Assert.IsFalse(layout.Session.StartsWith(layout.Backups, StringComparison.Ordinal));
|
||||
Assert.IsFalse(layout.Session.StartsWith(layout.Diagnostics, StringComparison.Ordinal));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheTextAndTheLogLinesShowCountsOnly()
|
||||
{
|
||||
using var folder = new TempFolder("sessione");
|
||||
var file = Path.Combine(folder.Path, "sessione.json");
|
||||
var log = new List<string>();
|
||||
var protector = Protector();
|
||||
var store = new FileSiteSession(file, protector, log.Add);
|
||||
Assert.AreEqual("Nessuna sessione salvata.", store.ToString());
|
||||
await store.ReplaceAsync(Values(), CancellationToken.None);
|
||||
await store.UpdateAsync(new SiteSessionUpdate([Csrf("segreto-rinnovo-17")], claim: "segreto-claim-18"), CancellationToken.None);
|
||||
_ = new FileSiteSession(file, protector, log.Add);
|
||||
await store.DeleteAsync(CancellationToken.None);
|
||||
|
||||
var texts = log.Append(store.ToString()).Append(protector.ToString()).ToList();
|
||||
AssertNoSecret(texts);
|
||||
foreach (var text in texts)
|
||||
{
|
||||
Assert.IsFalse(text.Contains("csrftoken", StringComparison.Ordinal) || text.Contains(folder.Path, StringComparison.Ordinal), text);
|
||||
}
|
||||
|
||||
Assert.IsTrue(log.Any(l => l.Contains("Sessione salvata scritta: 4 cookie", StringComparison.Ordinal)), string.Join("\n", log));
|
||||
Assert.IsTrue(log.Any(l => l.Contains("Sessione salvata letta", StringComparison.Ordinal)));
|
||||
}
|
||||
|
||||
/// <summary>A session with a cookie of each kind, every page value and a doc_id; values from <see cref="Secrets"/>.</summary>
|
||||
private static SiteSessionValues Values(string csrf = "segreto-csrf-2") => new(
|
||||
[
|
||||
new SiteCookie("sessionid", "segreto-sessione-1", ".instagram.com", "/", hostOnly: false, secure: true, httpOnly: true, expires: Now.AddDays(365)),
|
||||
Csrf(csrf),
|
||||
SiteCookie.ForHost("ds_user_id", "segreto-percorso-3", "www.instagram.com", "/api/", secure: true),
|
||||
SiteCookie.ForHost("rur", "\"CLN\\054segreto\"", "www.instagram.com"),
|
||||
],
|
||||
"Mozilla/5.0 segreto-agente-9",
|
||||
new Dictionary<string, string>
|
||||
{
|
||||
["lsd"] = "segreto-lsd-4", ["fb_dtsg"] = "segreto-dtsg-5", ["rev"] = "segreto-rev-6", ["entry_nonce"] = "segreto-nonce-7",
|
||||
["claim"] = "segreto-claim-10", ["dpr"] = "2",
|
||||
},
|
||||
new Dictionary<string, string> { ["PolarisProfilePostsQuery"] = "segreto-docid-8" },
|
||||
Now);
|
||||
|
||||
/// <summary>The csrftoken of Instagram as the browser keeps it (Domain=.instagram.com, secure): a renewal has the same key.</summary>
|
||||
private static SiteCookie Csrf(string value) =>
|
||||
new("csrftoken", value, ".instagram.com", "/", hostOnly: false, secure: true, expires: Now.AddDays(30));
|
||||
|
||||
private static SiteCookie Cookie(string name, string value) => SiteCookie.ForHost(name, value, "www.instagram.com");
|
||||
|
||||
private static string Describe(SiteCookie c) => $"{c.Name}|{c.Value}|{c.Domain}|{c.HostOnly}|{c.Path}|{c.Secure}|{c.HttpOnly}|{c.Expires:O}";
|
||||
|
||||
private static readonly ConcurrentDictionary<ISessionProtector, byte[]> Keys = new();
|
||||
|
||||
/// <summary>A protector with a key made now (never a key in the repository).</summary>
|
||||
private static AesGcmSessionProtector Protector()
|
||||
{
|
||||
var key = RandomNumberGenerator.GetBytes(SessionKey.Length);
|
||||
var protector = new AesGcmSessionProtector(key);
|
||||
Keys[protector] = key;
|
||||
return protector;
|
||||
}
|
||||
|
||||
/// <summary>Another protector with the same key as <paramref name="flaky"/>'s.</summary>
|
||||
private static AesGcmSessionProtector Protector(FlakyProtector flaky) => new(Keys[flaky.Inner]);
|
||||
|
||||
private static void AssertNoSecret(IEnumerable<string> texts)
|
||||
{
|
||||
foreach (var text in texts)
|
||||
{
|
||||
Assert.IsFalse(text.Contains("segreto", StringComparison.Ordinal), text);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A protector that can refuse to write (as a full or read-only disk would) or hold a write halfway.</summary>
|
||||
private sealed class FlakyProtector(AesGcmSessionProtector inner) : ISessionProtector
|
||||
{
|
||||
public AesGcmSessionProtector Inner => inner;
|
||||
|
||||
public bool Fail { get; set; }
|
||||
|
||||
public ManualResetEventSlim? Hold { get; set; }
|
||||
|
||||
public ManualResetEventSlim Entered { get; } = new(false);
|
||||
|
||||
public string Scheme => inner.Scheme;
|
||||
|
||||
public byte[] Protect(ReadOnlySpan<byte> plain)
|
||||
{
|
||||
if (Hold is { } hold)
|
||||
{
|
||||
Hold = null;
|
||||
Entered.Set();
|
||||
hold.Wait(TimeSpan.FromSeconds(30));
|
||||
}
|
||||
|
||||
return Fail ? throw new IOException("Disco pieno.") : inner.Protect(plain);
|
||||
}
|
||||
|
||||
public byte[] Unprotect(ReadOnlySpan<byte> blob) => inner.Unprotect(blob);
|
||||
}
|
||||
}
|
||||
@@ -58,17 +58,19 @@ public sealed class HttpSiteRequesterShapeTests
|
||||
|
||||
Assert.AreEqual("POST /api/graphql HTTP/1.1", request.Line);
|
||||
CollectionAssert.AreEquivalent(
|
||||
new[] { "host", "accept", "content-length", "content-type", "user-agent", "x-app-id", "x-csrftoken", "x-fb-friendly-name", "x-ig-www-claim", "cookie", "accept-encoding" },
|
||||
new[] { "host", "accept", "content-length", "content-type", "user-agent", "x-app-id", "x-csrftoken", "x-fb-entry-nonce", "x-fb-friendly-name", "x-ig-www-claim", "cookie", "accept-encoding" },
|
||||
request.Headers.Select(h => h.Name).ToArray());
|
||||
Assert.AreEqual(TestSite.EntryNonce, request.Header("x-fb-entry-nonce"), "From the session (the page's BootloaderConfig.nonce on Instagram).");
|
||||
Assert.AreEqual("application/x-www-form-urlencoded", request.Header("content-type"), "As the catalog writes it, no charset added.");
|
||||
Assert.AreEqual(TestSite.ProfileQuery, request.Header("x-fb-friendly-name"));
|
||||
Assert.AreEqual("0", request.Header("x-ig-www-claim"));
|
||||
Assert.AreEqual(
|
||||
"av=17841400000000077&__a=1&fb_dtsg=dtsg-di-prova&lsd=lsd-di-prova&fb_api_req_friendly_name=ProvaProfiloQuery"
|
||||
"av=17841400000000077&__a=1&__ccg=BUONA&__comet_req=7&__hs=hs-di-prova&__hsi=hsi-di-prova&__rev=revisione-di-prova&dpr=1"
|
||||
+ "&fb_dtsg=dtsg-di-prova&lsd=lsd-di-prova&fb_api_req_friendly_name=ProvaProfiloQuery"
|
||||
+ "&variables=%7B%22username%22%3A%22marta.prova%22%2C%22scheda%22%3A%22post%22%2C%22primi%22%3A12%2C%22raccolte%22%3Atrue%7D"
|
||||
+ "&doc_id=8000000000000001",
|
||||
request.Body,
|
||||
"Fields in the order of the file; the variables as JSON.stringify writes them: 12 a number, true a boolean.");
|
||||
"Fields in the order of the file, the version fields from the session; the variables as JSON.stringify writes them: 12 a number, true a boolean.");
|
||||
Assert.AreEqual(Encoding.UTF8.GetByteCount(request.Body).ToString(System.Globalization.CultureInfo.InvariantCulture), request.Header("content-length"));
|
||||
}
|
||||
|
||||
@@ -238,7 +240,7 @@ public sealed class HttpSiteRequesterShapeTests
|
||||
using var listener = new OneShotListener("""{"profilo":{}}""");
|
||||
|
||||
// «rur» expired a minute ago: not in the cookie line.
|
||||
var session = new InMemorySiteSession(new SiteSessionValues(values.Cookies, values.UserAgent, values.Fields, values.DocIds, new Dictionary<string, DateTimeOffset> { ["rur"] = clock.Now.AddMinutes(-1) }));
|
||||
var session = new InMemorySiteSession(new SiteSessionValues(Expiring(values, "rur", clock.Now.AddMinutes(-1)), values.UserAgent, values.Fields, values.DocIds));
|
||||
using (var requester = new HttpSiteRequester(RequestCatalog.LoadTestSite(), session, HttpSiteRequesterOptions.TestSite(new Uri($"http://127.0.0.1:{listener.Port}/")), clock))
|
||||
{
|
||||
await requester.SendAsync(Profile(), Permit.Grant(ActionKind.ProfileOpen, null), CancellationToken.None);
|
||||
@@ -246,7 +248,7 @@ public sealed class HttpSiteRequesterShapeTests
|
||||
}
|
||||
|
||||
// The session cookie expired: nothing leaves, a Disconnessione.
|
||||
var expired = new InMemorySiteSession(new SiteSessionValues(values.Cookies, values.UserAgent, values.Fields, values.DocIds, new Dictionary<string, DateTimeOffset> { [TestSite.SessionCookie] = clock.Now }));
|
||||
var expired = new InMemorySiteSession(new SiteSessionValues(Expiring(values, TestSite.SessionCookie, clock.Now), values.UserAgent, values.Fields, values.DocIds));
|
||||
using var late = new HttpSiteRequester(RequestCatalog.LoadTestSite(), expired, HttpSiteRequesterOptions.TestSite(new Uri($"http://127.0.0.1:{listener.Port}/")), clock);
|
||||
var refused = await Assert.ThrowsExactlyAsync<SiteSessionMissingException>(() => late.SendAsync(Profile(), Permit.Grant(ActionKind.ProfileOpen, null), CancellationToken.None));
|
||||
Assert.AreEqual(TestSite.SessionCookie, refused.Missing);
|
||||
@@ -290,8 +292,110 @@ public sealed class HttpSiteRequesterShapeTests
|
||||
Assert.IsFalse(refusal.Contains("segreto", StringComparison.Ordinal) || refusal.Contains("proxy.example", StringComparison.Ordinal), "Never the value.");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheCookieLineCarriesOnlyCookiesWhoseDomainAndPathMatchLongerPathsFirst()
|
||||
{
|
||||
using var listener = new OneShotListener("""{"profilo":{}}""");
|
||||
var values = Session();
|
||||
var cookies = values.Cookies.Concat(
|
||||
[
|
||||
SiteCookie.ForHost("percorso_api", "p", "127.0.0.1", "/api/"),
|
||||
SiteCookie.ForHost("dati_lunghi", "d", "127.0.0.1", "/api/dati/"),
|
||||
SiteCookie.ForHost("altrove", "a", "127.0.0.1", "/accesso/"),
|
||||
SiteCookie.ForHost("quasi", "q", "127.0.0.1", "/ap"),
|
||||
SiteCookie.ForHost("estraneo", "e", "altro.example"),
|
||||
SiteCookie.ForHost("sicuro", "s", "127.0.0.1", secure: true),
|
||||
]);
|
||||
using var requester = new HttpSiteRequester(RequestCatalog.LoadTestSite(), new InMemorySiteSession(new SiteSessionValues(cookies, values.UserAgent, values.Fields, values.DocIds)), HttpSiteRequesterOptions.TestSite(new Uri($"http://127.0.0.1:{listener.Port}/")), new VirtualClock());
|
||||
|
||||
await requester.SendAsync(Profile(), Permit.Grant(ActionKind.ProfileOpen, null), CancellationToken.None);
|
||||
|
||||
Assert.AreEqual(
|
||||
"dati_lunghi=d; percorso_api=p; csrftoken=csrf-1; sessione_prova=attiva; rur=\"FRC\\05412\"",
|
||||
(await listener.Request).Header("cookie"),
|
||||
"Longer paths first, then the session's order; no other path, host, a «/ap» that is not a segment, nor a secure cookie over http.");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheCsrfHeaderTakesTheCookieThatMatchesTheRequestPath()
|
||||
{
|
||||
using var listener = new OneShotListener("""{"profilo":{}}""");
|
||||
var values = Session();
|
||||
var cookies = values.Cookies.Append(SiteCookie.ForHost("csrftoken", "csrf-api", "127.0.0.1", "/api/"));
|
||||
using var requester = new HttpSiteRequester(RequestCatalog.LoadTestSite(), new InMemorySiteSession(new SiteSessionValues(cookies, values.UserAgent, values.Fields, values.DocIds)), HttpSiteRequesterOptions.TestSite(new Uri($"http://127.0.0.1:{listener.Port}/")), new VirtualClock());
|
||||
|
||||
await requester.SendAsync(Profile(), Permit.Grant(ActionKind.ProfileOpen, null), CancellationToken.None);
|
||||
|
||||
var request = await listener.Request;
|
||||
Assert.AreEqual("csrf-api", request.Header("x-csrftoken"), "The csrftoken the browser would send first to /api/.");
|
||||
StringAssert.StartsWith(request.Header("cookie"), "csrftoken=csrf-api; csrftoken=csrf-1;");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ASessionCookieOfAnotherPathOrHostIsAMissingSession()
|
||||
{
|
||||
using var listener = new OneShotListener("""{"profilo":{}}""");
|
||||
var values = Session();
|
||||
foreach (var misplaced in new[]
|
||||
{
|
||||
SiteCookie.ForHost(TestSite.SessionCookie, SiteControl.InitialSession, "127.0.0.1", "/accesso/"),
|
||||
SiteCookie.ForHost(TestSite.SessionCookie, SiteControl.InitialSession, "127.0.0.2"),
|
||||
SiteCookie.ForHost(TestSite.SessionCookie, SiteControl.InitialSession, "127.0.0.1", secure: true),
|
||||
})
|
||||
{
|
||||
var cookies = values.Cookies.Where(c => c.Name != TestSite.SessionCookie).Append(misplaced);
|
||||
using var requester = new HttpSiteRequester(RequestCatalog.LoadTestSite(), new InMemorySiteSession(new SiteSessionValues(cookies, values.UserAgent, values.Fields, values.DocIds)), HttpSiteRequesterOptions.TestSite(new Uri($"http://127.0.0.1:{listener.Port}/")), new VirtualClock());
|
||||
var refused = await Assert.ThrowsExactlyAsync<SiteSessionMissingException>(() => requester.SendAsync(Profile(), Permit.Grant(ActionKind.ProfileOpen, null), CancellationToken.None));
|
||||
Assert.AreEqual(TestSite.SessionCookie, refused.Missing, misplaced.ToString());
|
||||
}
|
||||
|
||||
Assert.AreEqual(0, listener.Connections, "Nothing left.");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow("rev", "__rev")]
|
||||
[DataRow("hs", "__hs")]
|
||||
[DataRow("hsi", "__hsi")]
|
||||
[DataRow("dpr", "dpr")]
|
||||
[DataRow("ccg", "__ccg")]
|
||||
[DataRow("comet_req", "__comet_req")]
|
||||
[DataRow("entry_nonce", "x-fb-entry-nonce")]
|
||||
public async Task AVersionFieldTheSessionLacksStopsTheQueryBeforeItLeaves(string field, string missing)
|
||||
{
|
||||
using var listener = new OneShotListener("""{"profilo":{}}""");
|
||||
var values = Session();
|
||||
var fields = values.Fields.Where(f => f.Key != field).ToDictionary();
|
||||
using var requester = new HttpSiteRequester(RequestCatalog.LoadTestSite(), new InMemorySiteSession(new SiteSessionValues(values.Cookies, values.UserAgent, fields, values.DocIds)), HttpSiteRequesterOptions.TestSite(new Uri($"http://127.0.0.1:{listener.Port}/")), new VirtualClock());
|
||||
|
||||
var refused = await Assert.ThrowsExactlyAsync<SiteSessionMissingException>(() => requester.SendAsync(SiteRequest.For(TestSite.ProfileQuery, (CaseValues.Username, "marta.prova")), Permit.Grant(ActionKind.ProfileOpen, null), CancellationToken.None));
|
||||
|
||||
Assert.AreEqual(missing, refused.Missing, "Never guessed (rule 9).");
|
||||
Assert.AreEqual(0, listener.Connections);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ARenewalKeepsThePathAndDomainItWasSetWith()
|
||||
{
|
||||
using var listener = new OneShotListener("""{"profilo":{}}""", extraHeaders: "Set-Cookie: percorso_api=nuovo; Path=/api/\r\nSet-Cookie: senza_percorso=x\r\nSet-Cookie: csrftoken=csrf-2; Path=/\r\n");
|
||||
var session = new InMemorySiteSession(Session());
|
||||
using var requester = new HttpSiteRequester(RequestCatalog.LoadTestSite(), session, HttpSiteRequesterOptions.TestSite(new Uri($"http://127.0.0.1:{listener.Port}/")), new VirtualClock());
|
||||
|
||||
await requester.SendAsync(Profile(), Permit.Grant(ActionKind.ProfileOpen, null), CancellationToken.None);
|
||||
|
||||
var cookies = session.Read()!.Cookies;
|
||||
CollectionAssert.AreEqual(
|
||||
new[] { "csrftoken 127.0.0.1 / csrf-2", "sessione_prova 127.0.0.1 / attiva", "rur 127.0.0.1 / \"FRC\\05412\"", "percorso_api 127.0.0.1 /api/ nuovo", "senza_percorso 127.0.0.1 /api/dati/profilo x" },
|
||||
cookies.Select(c => $"{c.Name} {c.Domain} {c.Path} {c.Value}").ToArray(),
|
||||
"csrftoken renewed in place; the new ones host-only on the site, at their Path or at the default path of the request.");
|
||||
Assert.IsTrue(cookies.All(c => c.HostOnly));
|
||||
}
|
||||
|
||||
private static SiteRequest Profile() => SiteRequest.For("profilo", (CaseValues.Username, "marta.prova"));
|
||||
|
||||
/// <summary>The cookies of <paramref name="values"/> with <paramref name="name"/> expiring at <paramref name="at"/>.</summary>
|
||||
private static IEnumerable<SiteCookie> Expiring(SiteSessionValues values, string name, DateTimeOffset at) =>
|
||||
values.Cookies.Select(c => c.Name == name ? new SiteCookie(c.Name, c.Value, c.Domain, c.Path, c.HostOnly, c.Secure, c.HttpOnly, at) : c);
|
||||
|
||||
private static async Task WaitUntilAsync(Func<bool> condition)
|
||||
{
|
||||
using var limit = new CancellationTokenSource(TimeSpan.FromSeconds(30));
|
||||
@@ -305,9 +409,13 @@ public sealed class HttpSiteRequesterShapeTests
|
||||
new(RequestCatalog.LoadTestSite(), new InMemorySiteSession(Session()), HttpSiteRequesterOptions.TestSite(new Uri($"http://127.0.0.1:{port}/")), new VirtualClock());
|
||||
|
||||
private static SiteSessionValues Session() => new(
|
||||
[new("csrftoken", "csrf-1"), new(TestSite.SessionCookie, SiteControl.InitialSession), new("rur", "\"FRC\\05412\"")],
|
||||
[
|
||||
SiteCookie.ForHost("csrftoken", "csrf-1", "127.0.0.1"),
|
||||
SiteCookie.ForHost(TestSite.SessionCookie, SiteControl.InitialSession, "127.0.0.1"),
|
||||
SiteCookie.ForHost("rur", "\"FRC\\05412\"", "127.0.0.1"),
|
||||
],
|
||||
UserAgent,
|
||||
new Dictionary<string, string> { ["app_id"] = TestSite.AppId, ["lsd"] = TestSite.Lsd, ["fb_dtsg"] = TestSite.Dtsg, ["claim"] = "0", ["account_id"] = "17841400000000077" },
|
||||
HttpSiteRequesterTests.PageValues(),
|
||||
TestSite.DocIds);
|
||||
|
||||
/// <summary>The head and body of one HTTP/1.1 request, as they arrived.</summary>
|
||||
|
||||
@@ -452,6 +452,7 @@ public sealed class HttpSiteRequesterTests
|
||||
var secrets = new List<string>
|
||||
{
|
||||
Csrf, OtherCookie, SiteControl.InitialSession, "rinnovata-1", "claim-prova-1", TestSite.AppId, TestSite.Lsd, TestSite.Dtsg, AccountId,
|
||||
TestSite.Revision, TestSite.HasteSession, TestSite.HasteSessionId, TestSite.ConnectionClass, TestSite.EntryNonce,
|
||||
TestSite.DocIds[TestSite.ProfileQuery], UserAgent, "Mozilla", "marta.prova", "luca.prova", "c12", "127.0.0.1", "scheda", "primi", "accesso", "next",
|
||||
};
|
||||
secrets.AddRange(cases.Values.SelectMany(c => c.Values.Values));
|
||||
@@ -464,7 +465,7 @@ public sealed class HttpSiteRequesterTests
|
||||
}
|
||||
}
|
||||
|
||||
private static Dictionary<string, (Dictionary<string, string> Values, string PagePath)> Cases(TestSite site)
|
||||
internal static Dictionary<string, (Dictionary<string, string> Values, string PagePath)> Cases(TestSite site)
|
||||
{
|
||||
string code;
|
||||
string highlight;
|
||||
@@ -524,7 +525,7 @@ public sealed class HttpSiteRequesterTests
|
||||
|
||||
private static SiteRequest Profile() => SiteRequest.For("profilo", (CaseValues.Username, "marta.prova"));
|
||||
|
||||
private static SiteRequest Graph() => SiteRequest.For(TestSite.ProfileQuery, (CaseValues.Username, "marta.prova"));
|
||||
internal static SiteRequest Graph() => SiteRequest.For(TestSite.ProfileQuery, (CaseValues.Username, "marta.prova"));
|
||||
|
||||
private static SiteOperation Operation(string name) => Catalog.Operations.Single(o => o.Name == name);
|
||||
|
||||
@@ -542,25 +543,39 @@ public sealed class HttpSiteRequesterTests
|
||||
/// <summary>The saved session of a test: the cookies, tokens and doc_id the pages of the test site hand out.</summary>
|
||||
internal static SiteSessionValues Values(string? session = SiteControl.InitialSession, string? csrf = Csrf, string appId = TestSite.AppId, bool docIds = true)
|
||||
{
|
||||
var cookies = new List<KeyValuePair<string, string>>();
|
||||
// Host-only cookies of the test site's host, path «/», as its pages set them.
|
||||
var cookies = new List<SiteCookie>();
|
||||
if (csrf is not null)
|
||||
{
|
||||
cookies.Add(new(TestSite.CsrfCookie, csrf));
|
||||
cookies.Add(SiteCookie.ForHost(TestSite.CsrfCookie, csrf, "127.0.0.1"));
|
||||
}
|
||||
|
||||
if (session is not null)
|
||||
{
|
||||
cookies.Add(new(TestSite.SessionCookie, session));
|
||||
cookies.Add(SiteCookie.ForHost(TestSite.SessionCookie, session, "127.0.0.1"));
|
||||
}
|
||||
|
||||
cookies.Add(new("altro", OtherCookie));
|
||||
return new SiteSessionValues(
|
||||
cookies,
|
||||
UserAgent,
|
||||
new Dictionary<string, string> { ["app_id"] = appId, ["lsd"] = TestSite.Lsd, ["fb_dtsg"] = TestSite.Dtsg, ["claim"] = "0", ["account_id"] = AccountId },
|
||||
docIds ? TestSite.DocIds : null);
|
||||
cookies.Add(SiteCookie.ForHost("altro", OtherCookie, "127.0.0.1"));
|
||||
return new SiteSessionValues(cookies, UserAgent, PageValues(appId), docIds ? TestSite.DocIds : null);
|
||||
}
|
||||
|
||||
/// <summary>The values the pages of the test site hold (the «page» section of richieste.prova.json), and the claim.</summary>
|
||||
internal static Dictionary<string, string> PageValues(string appId = TestSite.AppId) => new()
|
||||
{
|
||||
["app_id"] = appId,
|
||||
["lsd"] = TestSite.Lsd,
|
||||
["fb_dtsg"] = TestSite.Dtsg,
|
||||
["claim"] = "0",
|
||||
["account_id"] = AccountId,
|
||||
["rev"] = TestSite.Revision,
|
||||
["hs"] = TestSite.HasteSession,
|
||||
["hsi"] = TestSite.HasteSessionId,
|
||||
["dpr"] = TestSite.Dpr,
|
||||
["comet_req"] = TestSite.CometReq,
|
||||
["ccg"] = TestSite.ConnectionClass,
|
||||
["entry_nonce"] = TestSite.EntryNonce,
|
||||
};
|
||||
|
||||
/// <summary>A site client for the test site with its session, clock and log.</summary>
|
||||
private sealed class Bed : IDisposable
|
||||
{
|
||||
|
||||
@@ -4,6 +4,7 @@ using System.Text.RegularExpressions;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Collection;
|
||||
using Febe.Core.Collection.Requests;
|
||||
using Febe.Tests.Collection.Support;
|
||||
|
||||
namespace Febe.Tests.Collection;
|
||||
|
||||
@@ -36,7 +37,8 @@ public sealed partial class RequestCatalogTests
|
||||
|
||||
// Only what the shapes tell whole is configured: a variable whose name the probe removed, a value it does not
|
||||
// show, or a header or field whose source is still pending leaves the operation not configured (rule 9). Every
|
||||
// Instagram operation has such headers and fields until tappa S4; for four of them only those are missing.
|
||||
// Instagram operation still has such headers and fields after S4 (values the page computes as it runs, headers of
|
||||
// the browser, removed names); for four of them only those are missing.
|
||||
Assert.AreEqual(0, instagram.Configured.Count());
|
||||
CollectionAssert.AreEquivalent(
|
||||
new[] { "PolarisProfileReelsTabContentQuery", "PolarisProfileTaggedTabContentQuery", "PolarisProfileStoryHighlightsTrayContentQuery", "media-info" },
|
||||
@@ -326,6 +328,166 @@ public sealed partial class RequestCatalogTests
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ThePageSectionSaysWhereThePageKeepsEachSessionValue()
|
||||
{
|
||||
var instagram = RequestCatalog.LoadInstagram().Page;
|
||||
Assert.IsNotNull(instagram);
|
||||
Assert.AreEqual("PolarisProfilePostsQuery_instagramRelayOperation", instagram.DocIdModuleFor("PolarisProfilePostsQuery"));
|
||||
Assert.AreEqual(new PageValueSource("LSD", "token"), instagram.Values["lsd"]);
|
||||
Assert.AreEqual(new PageValueSource("DTSGInitialData", "token"), instagram.Values["fb_dtsg"]);
|
||||
Assert.AreEqual(new PageValueSource("CurrentUserInitialData", "USER_ID"), instagram.Values["account_id"]);
|
||||
Assert.AreEqual(new PageValueSource("CurrentUserInitialData", "APP_ID"), instagram.Values["app_id"]);
|
||||
Assert.AreEqual(new PageValueSource("SiteData", "client_revision"), instagram.Values["rev"]);
|
||||
Assert.AreEqual(new PageValueSource("SiteData", "haste_session"), instagram.Values["hs"]);
|
||||
Assert.AreEqual(new PageValueSource("SiteData", "hsi"), instagram.Values["hsi"]);
|
||||
Assert.AreEqual(new PageValueSource("SiteData", "pr"), instagram.Values["dpr"]);
|
||||
Assert.AreEqual(new PageValueSource("SiteData", "comet_env"), instagram.Values["comet_req"]);
|
||||
Assert.AreEqual(new PageValueSource("WebConnectionClassServerGuess", "connectionClass"), instagram.Values["ccg"]);
|
||||
Assert.AreEqual(new PageValueSource("BootloaderConfig", "nonce"), instagram.Values["entry_nonce"]);
|
||||
CollectionAssert.AreEquivalent(SiteSessionValues.PageFields.ToArray(), instagram.Values.Keys.ToArray(), "A place for every page value.");
|
||||
|
||||
// The test site has its own module names, never Instagram's.
|
||||
var prova = RequestCatalog.LoadTestSite().Page;
|
||||
Assert.IsNotNull(prova);
|
||||
Assert.AreEqual("ProvaProfiloQuery_operazioneProva", prova.DocIdModuleFor("ProvaProfiloQuery"));
|
||||
CollectionAssert.AreEquivalent(SiteSessionValues.PageFields.ToArray(), prova.Values.Keys.ToArray());
|
||||
var instagramModules = instagram.Values.Values.Select(v => v.Module).ToHashSet(StringComparer.OrdinalIgnoreCase);
|
||||
Assert.IsFalse(prova.Values.Values.Any(v => instagramModules.Contains(v.Module)));
|
||||
Assert.IsFalse(prova.DocIdModule!.Contains("instagram", StringComparison.OrdinalIgnoreCase));
|
||||
Assert.IsTrue(prova.Values.Values.All(v => PageSources.IsIdentifier(v.Module) && PageSources.IsIdentifier(v.Property)));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheInstagramVersionFieldsComeFromTheSessionAndAllTenOperationsStayNotConfigured()
|
||||
{
|
||||
var catalog = RequestCatalog.LoadInstagram();
|
||||
Assert.AreEqual(0, catalog.Configured.Count(), "S4 configures no Instagram operation.");
|
||||
var session = new Dictionary<string, string>
|
||||
{
|
||||
["__rev"] = "rev", ["__hs"] = "hs", ["__hsi"] = "hsi", ["__ccg"] = "ccg", ["__comet_req"] = "comet_req", ["dpr"] = "dpr",
|
||||
};
|
||||
foreach (var operation in catalog.Operations.Where(o => o.Kind == OperationKind.GraphQl))
|
||||
{
|
||||
foreach (var (field, source) in session)
|
||||
{
|
||||
Assert.AreEqual(new ValueSource(ValueSourceKind.Session, source), operation.Body[field], $"{operation.Name} {field}");
|
||||
}
|
||||
|
||||
Assert.AreEqual(new ValueSource(ValueSourceKind.Session, "entry_nonce"), operation.Headers["x-fb-entry-nonce"], operation.Name);
|
||||
Assert.AreEqual(new ValueSource(ValueSourceKind.Constant, "359341"), operation.Headers["x-asbd-id"], "The BDHeaderConfig property is not established.");
|
||||
foreach (var spin in new[] { "__spin_r", "__spin_b", "__spin_t" })
|
||||
{
|
||||
Assert.AreEqual(ValueSourceKind.Pending, operation.Body[spin].Kind, $"{operation.Name} {spin}: who adds it to the request is not shown.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void EveryPendingLeftIsARuntimeValueABrowserHeaderOrARemovedName()
|
||||
{
|
||||
// A closed list: what the page computes while it runs (__req, __s, __dyn, __csr, __hblp, __hsdp, __sjsp, __crn,
|
||||
// __d, __spin_*, x-web-session-id), headers of the browser (referer, priority, sec-ch-ua*, x-ig-max-touch-points)
|
||||
// and the names the probe removed. Nothing else may stay pending without a decision.
|
||||
var allowed = new HashSet<string>(StringComparer.Ordinal)
|
||||
{
|
||||
"__req", "__s", "__dyn", "__csr", "__hblp", "__hsdp", "__sjsp", "__crn", "__d", "__spin_r", "__spin_b", "__spin_t",
|
||||
"x-web-session-id", "referer", "priority", "sec-ch-ua", "sec-ch-ua-mobile", "sec-ch-ua-platform", "x-ig-max-touch-points",
|
||||
"fb_api_analytics_tags", "qpl_active_flow_ids", RequestCatalog.RemovedName,
|
||||
};
|
||||
var pending = RequestCatalog.LoadInstagram().Operations.SelectMany(o => o.PendingValues).Distinct(StringComparer.Ordinal).ToList();
|
||||
CollectionAssert.AreEqual(Array.Empty<string>(), pending.Where(p => !allowed.Contains(p)).ToArray());
|
||||
Assert.IsFalse(pending.Contains("__rev") || pending.Contains("x-fb-entry-nonce"), "Settled in S4.");
|
||||
Assert.AreEqual(0, RequestCatalog.LoadTestSite().Operations.Sum(o => o.PendingValues.Count));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow("""{"password": "Utente.password"}""", "password")]
|
||||
[DataRow("""{"user_agent": "Navigatore.agente"}""", "user_agent")]
|
||||
[DataRow("""{"claim": "Pagina.claim"}""", "claim")]
|
||||
[DataRow("""{"doc_id": "Pagina.doc"}""", "doc_id")]
|
||||
[DataRow("""{"lsd": "LSD.token;alert(1)"}""", "Modulo.proprietà")]
|
||||
[DataRow("""{"lsd": "LSD"}""", "Modulo.proprietà")]
|
||||
[DataRow("""{"lsd": "LSD.token.altro"}""", "Modulo.proprietà")]
|
||||
[DataRow("""{"lsd": "1LSD.token"}""", "Modulo.proprietà")]
|
||||
[DataRow("""{"lsd": "LSD.to-ken"}""", "Modulo.proprietà")]
|
||||
[DataRow("""{"lsd": "require('x').y"}""", "Modulo.proprietà")]
|
||||
[DataRow("""{"lsd": ".token"}""", "Modulo.proprietà")]
|
||||
public void ThePageSectionRefusesUnknownFieldsAndNamesThatAreNotIdentifiers(string values, string expected)
|
||||
{
|
||||
var file = JsonNode.Parse(SiteMap.ReadEmbeddedText("richieste.prova.json"))!.AsObject();
|
||||
file["page"]!["values"] = JsonNode.Parse(values);
|
||||
var refused = Refuse(file.ToJsonString());
|
||||
StringAssert.Contains(refused, "page");
|
||||
StringAssert.Contains(refused, expected);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow("Modulo_relay")]
|
||||
[DataRow("{operation}_{operation}")]
|
||||
[DataRow("{operation}-relay")]
|
||||
[DataRow("{operation}.relay")]
|
||||
[DataRow("{operazione}_relay")]
|
||||
public void TheDocIdModuleHasTheOperationOnceAndIsOtherwiseAnIdentifier(string module)
|
||||
{
|
||||
var file = JsonNode.Parse(SiteMap.ReadEmbeddedText("richieste.prova.json"))!.AsObject();
|
||||
file["page"]!["docIdModule"] = module;
|
||||
StringAssert.Contains(Refuse(file.ToJsonString()), "docIdModule");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void AConfiguredOperationWhoseSessionValueHasNoPlaceInThePageIsRefused()
|
||||
{
|
||||
// No module for lsd: the configured GraphQL query that sends it is refused, naming the value.
|
||||
var file = JsonNode.Parse(SiteMap.ReadEmbeddedText("richieste.prova.json"))!.AsObject();
|
||||
file["page"]!["values"]!.AsObject().Remove("lsd");
|
||||
var refused = Refuse(file.ToJsonString());
|
||||
StringAssert.Contains(refused, "session:lsd");
|
||||
StringAssert.Contains(refused, "ProvaProfiloQuery");
|
||||
StringAssert.Contains(refused, "regola 9");
|
||||
|
||||
// No doc_id module: every configured GraphQL query is refused.
|
||||
file = JsonNode.Parse(SiteMap.ReadEmbeddedText("richieste.prova.json"))!.AsObject();
|
||||
file["page"]!.AsObject().Remove("docIdModule");
|
||||
StringAssert.Contains(Refuse(file.ToJsonString()), "session:doc_id");
|
||||
|
||||
// No page section at all: x-app-id (session:app_id) of the plain addresses has no place either.
|
||||
file = JsonNode.Parse(SiteMap.ReadEmbeddedText("richieste.prova.json"))!.AsObject();
|
||||
file.Remove("page");
|
||||
StringAssert.Contains(Refuse(file.ToJsonString()), "session:");
|
||||
|
||||
// The user agent and the claim need no place in the page; an operation that is not configured waits anyway.
|
||||
Assert.IsNotNull(RequestCatalog.Parse(Alone(Rest("post2", "/dati/post/{code}")), "richieste.prova.json"));
|
||||
var waiting = Rest("post3", "/dati/post/{code}");
|
||||
waiting["headers"] = new JsonObject { ["user-agent"] = "session:user_agent", ["x-app-id"] = "session:app_id" };
|
||||
waiting["configured"] = false;
|
||||
waiting["reason"] = "in attesa";
|
||||
Assert.IsNotNull(RequestCatalog.Parse(Alone(waiting), "richieste.prova.json"));
|
||||
|
||||
// Instagram's page section names every value its operations use, so settling the pending ones would be enough.
|
||||
Assert.AreEqual(4, SettledCatalog.Instagram().Configured.Count());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheNewSessionFieldsAreAcceptedAndUnknownOnesStillRefused()
|
||||
{
|
||||
foreach (var field in new[] { "rev", "hs", "hsi", "dpr", "ccg", "comet_req", "entry_nonce" })
|
||||
{
|
||||
var operation = Rest("post2", "/dati/post/{code}");
|
||||
operation["headers"] = new JsonObject { ["user-agent"] = "session:user_agent", ["x-prova"] = "session:" + field };
|
||||
operation["configured"] = false;
|
||||
operation["reason"] = "prova";
|
||||
Assert.AreEqual(new ValueSource(ValueSourceKind.Session, field), Get(RequestCatalog.Parse(Alone(operation), "richieste.prova.json"), "post2").Headers["x-prova"]);
|
||||
}
|
||||
|
||||
foreach (var field in new[] { "password", "spin_r", "cookie", "sessionid" })
|
||||
{
|
||||
var operation = Rest("post2", "/dati/post/{code}");
|
||||
operation["headers"] = new JsonObject { ["x-prova"] = "session:" + field };
|
||||
StringAssert.Contains(Refuse(Alone(operation)), "fonte");
|
||||
}
|
||||
}
|
||||
|
||||
private static SiteOperation Get(RequestCatalog catalog, string name) =>
|
||||
catalog.TryGet(name, out var operation) ? operation : throw new AssertFailedException($"«{name}» non è nel catalogo.");
|
||||
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
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));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using Febe.Core.Security;
|
||||
using Febe.Tests.Support;
|
||||
|
||||
namespace Febe.Tests.Collection;
|
||||
|
||||
/// <summary>
|
||||
/// The encryption of the saved session in Docker (issue #36, S4, spec §13.2): AES-256-GCM with a fresh nonce per write,
|
||||
/// the key from FEBE_CHIAVE_SESSIONE or from chiave.bin made once, owner-only, never replaced; files replaced at once.
|
||||
/// Keys are made at run time (no key in the repository, gitleaks); no text ever holds a key or a plain value.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class SessionProtectorTests
|
||||
{
|
||||
private static readonly byte[] Plain = Encoding.UTF8.GetBytes("""{"cookies":[{"name":"sessionid","value":"valore-in-chiaro-1"}]}""");
|
||||
|
||||
[TestMethod]
|
||||
public void ARoundTripGivesTheSameBytesAndEveryWriteHasAFreshNonce()
|
||||
{
|
||||
var protector = new AesGcmSessionProtector(RandomNumberGenerator.GetBytes(SessionKey.Length));
|
||||
var first = protector.Protect(Plain);
|
||||
var second = protector.Protect(Plain);
|
||||
|
||||
CollectionAssert.AreEqual(Plain, protector.Unprotect(first));
|
||||
CollectionAssert.AreEqual(Plain, protector.Unprotect(second));
|
||||
Assert.IsTrue(SessionBlob.HasHeader(first, SessionBlob.AesGcm), "FEBS, version, scheme.");
|
||||
Assert.AreEqual("FEBS", Encoding.ASCII.GetString(first, 0, 4));
|
||||
Assert.AreEqual(SessionBlob.HeaderLength + 12 + 16 + Plain.Length, first.Length);
|
||||
CollectionAssert.AreNotEqual(first, second, "A fresh nonce for every write.");
|
||||
Assert.AreEqual(-1, IndexOf(first, Encoding.UTF8.GetBytes("valore-in-chiaro-1")), "Nothing in clear.");
|
||||
Assert.AreEqual("aes-gcm", protector.Scheme);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ATamperedByteAnotherKeyOrAnotherSchemeIsUnreadableAndTheMessageHasNoValue()
|
||||
{
|
||||
var key = RandomNumberGenerator.GetBytes(SessionKey.Length);
|
||||
var protector = new AesGcmSessionProtector(key);
|
||||
var blob = protector.Protect(Plain);
|
||||
|
||||
foreach (var index in new[] { 5, SessionBlob.HeaderLength + 1, SessionBlob.HeaderLength + 13, blob.Length - 1 })
|
||||
{
|
||||
var tampered = (byte[])blob.Clone();
|
||||
tampered[index] ^= 0x01;
|
||||
var refused = Assert.ThrowsExactly<SessionUnreadableException>(() => protector.Unprotect(tampered));
|
||||
Assert.AreEqual(SessionUnreadableException.Text, refused.Message);
|
||||
Assert.IsNull(refused.InnerException, "No inner text is passed on.");
|
||||
}
|
||||
|
||||
var other = new AesGcmSessionProtector(RandomNumberGenerator.GetBytes(SessionKey.Length));
|
||||
Assert.ThrowsExactly<SessionUnreadableException>(() => other.Unprotect(blob));
|
||||
Assert.ThrowsExactly<SessionUnreadableException>(() => protector.Unprotect(blob.AsSpan(0, 10)));
|
||||
Assert.ThrowsExactly<SessionUnreadableException>(() => protector.Unprotect(Plain), "Not a blob of Febe.");
|
||||
var dpapiHeader = (byte[])blob.Clone();
|
||||
dpapiHeader[5] = SessionBlob.Dpapi;
|
||||
Assert.ThrowsExactly<SessionUnreadableException>(() => protector.Unprotect(dpapiHeader));
|
||||
|
||||
Assert.ThrowsExactly<ArgumentException>(() => new AesGcmSessionProtector(new byte[16]));
|
||||
Assert.IsFalse(protector.ToString().Contains(Convert.ToBase64String(key), StringComparison.Ordinal));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheKeyIsBase64Of32BytesOr64HexAndAWrongValueIsRefusedWithoutEchoingIt()
|
||||
{
|
||||
var key = RandomNumberGenerator.GetBytes(SessionKey.Length);
|
||||
Assert.IsTrue(SessionKey.TryParse(Convert.ToBase64String(key), out var fromBase64, out var none));
|
||||
CollectionAssert.AreEqual(key, fromBase64);
|
||||
Assert.IsNull(none);
|
||||
Assert.IsTrue(SessionKey.TryParse(" " + Convert.ToHexString(key).ToLowerInvariant() + "\n", out var fromHex, out _));
|
||||
CollectionAssert.AreEqual(key, fromHex);
|
||||
|
||||
foreach (var wrong in new[] { "chiave-troppo-corta", Convert.ToBase64String(new byte[16]), Convert.ToBase64String(new byte[33]), new string('z', 64), " " })
|
||||
{
|
||||
Assert.IsFalse(SessionKey.TryParse(wrong, out var parsed, out var problem), wrong);
|
||||
Assert.IsNull(parsed);
|
||||
Assert.IsNotNull(problem);
|
||||
StringAssert.Contains(problem, SessionKey.EnvironmentVariable);
|
||||
if (wrong.Trim().Length > 0)
|
||||
{
|
||||
Assert.IsFalse(problem.Contains(wrong.Trim(), StringComparison.Ordinal), "Never the value.");
|
||||
}
|
||||
}
|
||||
|
||||
Assert.IsFalse(SessionKey.TryParse(null, out _, out _));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ChiaveBinIsCreatedOnceOwnerOnlyAndNeverReplaced()
|
||||
{
|
||||
using var folder = new TempFolder("sessione-chiave");
|
||||
var file = folder.Combine("sessione", "chiave.bin");
|
||||
|
||||
var first = SessionKey.LoadOrCreate(file);
|
||||
var again = SessionKey.LoadOrCreate(file);
|
||||
|
||||
Assert.AreEqual(SessionKey.Length, first.Length);
|
||||
CollectionAssert.AreEqual(first, again, "Made once, then read.");
|
||||
CollectionAssert.AreEqual(first, File.ReadAllBytes(file));
|
||||
if (!OperatingSystem.IsWindows())
|
||||
{
|
||||
Assert.AreEqual(OwnerOnlyFiles.OwnerFile, File.GetUnixFileMode(file), "0600 from its creation.");
|
||||
Assert.AreEqual(OwnerOnlyFiles.OwnerFolder, File.GetUnixFileMode(folder.Combine("sessione")), "0700.");
|
||||
}
|
||||
|
||||
Assert.ThrowsExactly<IOException>(() => OwnerOnlyFiles.CreateNew(file, new byte[SessionKey.Length]), "Never replaced.");
|
||||
CollectionAssert.AreEqual(first, File.ReadAllBytes(file));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void AKeyWriteTheDiskRefusesLeavesNoChiaveBinSoTheNextStartMakesOne()
|
||||
{
|
||||
using var folder = new TempFolder("sessione-chiave");
|
||||
var file = folder.Combine("sessione", "chiave.bin");
|
||||
|
||||
// The disk fills up after the first bytes: the error comes out, and nothing short is left as «the key».
|
||||
Assert.ThrowsExactly<IOException>(() => SessionKey.LoadOrCreate(file, null, static (stream, bytes) =>
|
||||
{
|
||||
stream.Write(bytes[..4]);
|
||||
throw new IOException("Spazio esaurito sul disco (prova).");
|
||||
}));
|
||||
Assert.IsFalse(File.Exists(file), "No short chiave.bin behind.");
|
||||
Assert.IsEmpty(Directory.GetFiles(folder.Combine("sessione")), "Nor a part file.");
|
||||
Assert.IsNull(SessionKey.CheckFile(file), "The next start is not stopped by a key problem.");
|
||||
|
||||
var key = SessionKey.LoadOrCreate(file);
|
||||
Assert.AreEqual(SessionKey.Length, key.Length);
|
||||
CollectionAssert.AreEqual(key, File.ReadAllBytes(file));
|
||||
Assert.IsEmpty(Directory.GetFiles(folder.Combine("sessione"), "*" + OwnerOnlyFiles.PartSuffix));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void AChiaveBinOfTheWrongLengthIsAProblemNotARegeneration()
|
||||
{
|
||||
using var folder = new TempFolder("sessione-chiave");
|
||||
var file = folder.Combine("chiave.bin");
|
||||
File.WriteAllBytes(file, Encoding.ASCII.GetBytes("non-una-chiave"));
|
||||
|
||||
var problem = SessionKey.CheckFile(file);
|
||||
Assert.IsNotNull(problem);
|
||||
StringAssert.Contains(problem, "chiave.bin");
|
||||
Assert.IsFalse(problem.Contains("non-una-chiave", StringComparison.Ordinal));
|
||||
var refused = Assert.ThrowsExactly<InvalidDataException>(() => SessionKey.LoadOrCreate(file));
|
||||
Assert.IsFalse(refused.Message.Contains("non-una-chiave", StringComparison.Ordinal));
|
||||
CollectionAssert.AreEqual(Encoding.ASCII.GetBytes("non-una-chiave"), File.ReadAllBytes(file), "Left as it is, never made again.");
|
||||
Assert.IsNull(SessionKey.CheckFile(folder.Combine("manca.bin")), "A missing file will be made.");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void LooserModesAreNarrowedToTheOwnerOnUnix()
|
||||
{
|
||||
using var folder = new TempFolder("sessione-chiave");
|
||||
var file = folder.Combine("chiave.bin");
|
||||
File.WriteAllBytes(file, RandomNumberGenerator.GetBytes(SessionKey.Length));
|
||||
var warnings = new List<string>();
|
||||
if (OperatingSystem.IsWindows())
|
||||
{
|
||||
Assert.IsFalse(OwnerOnlyFiles.Tighten(file), "No Unix modes on Windows.");
|
||||
Assert.AreEqual(SessionKey.Length, SessionKey.LoadOrCreate(file, warnings.Add).Length);
|
||||
Assert.AreEqual(0, warnings.Count);
|
||||
return;
|
||||
}
|
||||
|
||||
File.SetUnixFileMode(file, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.GroupRead | UnixFileMode.OtherRead);
|
||||
Assert.AreEqual(SessionKey.Length, SessionKey.LoadOrCreate(file, warnings.Add).Length);
|
||||
Assert.AreEqual(OwnerOnlyFiles.OwnerFile, File.GetUnixFileMode(file));
|
||||
Assert.AreEqual(1, warnings.Count);
|
||||
StringAssert.Contains(warnings[0], "solo il proprietario");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheEnvironmentKeyWinsAndAnUnusedChiaveBinIsNamedNeverRead()
|
||||
{
|
||||
using var folder = new TempFolder("sessione-chiave");
|
||||
var file = folder.Combine("chiave.bin");
|
||||
var key = RandomNumberGenerator.GetBytes(SessionKey.Length);
|
||||
var text = Convert.ToBase64String(key);
|
||||
var log = new List<string>();
|
||||
|
||||
CollectionAssert.AreEqual(key, SessionKey.Resolve(text, file, log.Add));
|
||||
Assert.IsFalse(File.Exists(file), "With the variable, no chiave.bin is made.");
|
||||
|
||||
var stored = SessionKey.Resolve(null, file, log.Add);
|
||||
Assert.IsTrue(File.Exists(file));
|
||||
CollectionAssert.AreEqual(stored, SessionKey.Resolve(" ", file, log.Add), "An empty variable is no variable.");
|
||||
CollectionAssert.AreEqual(key, SessionKey.Resolve(text, file, log.Add));
|
||||
Assert.IsTrue(log.Any(l => l.Contains("non si usa", StringComparison.Ordinal)), string.Join("\n", log));
|
||||
|
||||
var refused = Assert.ThrowsExactly<InvalidDataException>(() => SessionKey.Resolve("chiave-sbagliata", file, log.Add));
|
||||
Assert.IsFalse(refused.Message.Contains("chiave-sbagliata", StringComparison.Ordinal));
|
||||
foreach (var line in log)
|
||||
{
|
||||
Assert.IsFalse(line.Contains(text, StringComparison.Ordinal) || line.Contains(Convert.ToBase64String(stored), StringComparison.Ordinal), line);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void AnAtomicWriteReplacesTheFileAndLeavesNoPartFile()
|
||||
{
|
||||
using var folder = new TempFolder("sessione-file");
|
||||
var file = folder.Combine("sessione.json");
|
||||
OwnerOnlyFiles.WriteAtomic(file, "uno"u8);
|
||||
OwnerOnlyFiles.WriteAtomic(file, "due"u8);
|
||||
|
||||
Assert.AreEqual("due", File.ReadAllText(file));
|
||||
CollectionAssert.AreEqual(new[] { "sessione.json" }, Directory.GetFiles(folder.Path).Select(Path.GetFileName).ToArray());
|
||||
if (!OperatingSystem.IsWindows())
|
||||
{
|
||||
Assert.AreEqual(OwnerOnlyFiles.OwnerFile, File.GetUnixFileMode(file));
|
||||
}
|
||||
|
||||
// A broken write left a part file: deleting the session takes it too.
|
||||
File.WriteAllText(file + ".abcdef12" + OwnerOnlyFiles.PartSuffix, "resto");
|
||||
File.WriteAllText(folder.Combine("altro.txt"), "non è della sessione");
|
||||
OwnerOnlyFiles.DeleteWithLeftovers(file);
|
||||
CollectionAssert.AreEqual(new[] { "altro.txt" }, Directory.GetFiles(folder.Path).Select(Path.GetFileName).ToArray());
|
||||
OwnerOnlyFiles.DeleteWithLeftovers(file);
|
||||
}
|
||||
|
||||
private static int IndexOf(byte[] haystack, byte[] needle) => haystack.AsSpan().IndexOf(needle);
|
||||
}
|
||||
@@ -143,11 +143,15 @@ public sealed class SiteAnswerSignalsTests
|
||||
private static byte[] Bytes(string text) => Encoding.UTF8.GetBytes(text);
|
||||
}
|
||||
|
||||
/// <summary>The saved session of the site client (issue #36, S2): cookies read as a browser reads them, updates in one write, no value in its text.</summary>
|
||||
/// <summary>
|
||||
/// The saved session of the site client (issue #36, S2 and S4): cookies read and sent as a browser reads and sends
|
||||
/// them, with their domain and path (RFC 6265), updates in one write, no value in any text.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class SiteSessionTests
|
||||
{
|
||||
private static readonly DateTimeOffset Now = new(2026, 11, 16, 10, 0, 0, TimeSpan.Zero);
|
||||
private static readonly Uri Graph = new("https://www.instagram.com/api/graphql");
|
||||
|
||||
[TestMethod]
|
||||
[DataRow("sessionid=abc; Path=/; HttpOnly", "abc", false)]
|
||||
@@ -163,66 +167,161 @@ public sealed class SiteSessionTests
|
||||
[DataRow("sessionid=abc; Domain=instagram.com", "abc", false)]
|
||||
public void ACookieLineIsReadAsABrowserReadsIt(string line, string value, bool deletes)
|
||||
{
|
||||
var cookie = SiteCookies.Parse(line, "www.instagram.com", Now);
|
||||
var cookie = SiteCookies.Parse(line, Graph, Now);
|
||||
Assert.IsNotNull(cookie);
|
||||
Assert.AreEqual("sessionid", cookie.Value.Name);
|
||||
Assert.AreEqual(value, cookie.Value.Value);
|
||||
Assert.AreEqual(deletes, cookie.Value.Deletes);
|
||||
Assert.AreEqual("sessionid", cookie.Cookie.Name);
|
||||
Assert.AreEqual(value, cookie.Cookie.Value);
|
||||
Assert.AreEqual(deletes, cookie.Deletes);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow("a=b", "www.instagram.com", true, "/api", false)]
|
||||
[DataRow("a=b; Path=/api/", "www.instagram.com", true, "/api/", false)]
|
||||
[DataRow("a=b; Path=relativo", "www.instagram.com", true, "/api", false)]
|
||||
[DataRow("a=b; Path=/; Domain=.instagram.com", "instagram.com", false, "/", false)]
|
||||
[DataRow("a=b; Domain=WWW.Instagram.com; Path=/", "www.instagram.com", false, "/", false)]
|
||||
[DataRow("a=b; Path=/; Secure; HttpOnly", "www.instagram.com", true, "/", true)]
|
||||
public void ACookieLineKeepsItsDomainAndPathAsABrowserReadsThem(string line, string domain, bool hostOnly, string path, bool secure)
|
||||
{
|
||||
// No Domain: host-only on the request host; no Path (or one not starting with «/»): the default path of the
|
||||
// request, «/api» for «/api/graphql» (RFC 6265 §5.1.4).
|
||||
var cookie = SiteCookies.Parse(line, Graph, Now)!.Cookie;
|
||||
Assert.AreEqual(domain, cookie.Domain);
|
||||
Assert.AreEqual(hostOnly, cookie.HostOnly);
|
||||
Assert.AreEqual(path, cookie.Path);
|
||||
Assert.AreEqual(secure, cookie.Secure);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheDefaultPathIsTheRequestPathUpToItsLastSlash()
|
||||
{
|
||||
Assert.AreEqual("/", SiteCookies.DefaultPath(new Uri("https://www.instagram.com/")));
|
||||
Assert.AreEqual("/", SiteCookies.DefaultPath(new Uri("https://www.instagram.com/marta")));
|
||||
Assert.AreEqual("/api", SiteCookies.DefaultPath(new Uri("https://www.instagram.com/api/graphql")));
|
||||
Assert.AreEqual("/api/v1/media/1/info", SiteCookies.DefaultPath(new Uri("https://www.instagram.com/api/v1/media/1/info/")));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ACookieGoesOnlyWhereItsDomainPathAndSchemeMatch()
|
||||
{
|
||||
var host = SiteCookie.ForHost("a", "1", "www.instagram.com");
|
||||
var wide = new SiteCookie("b", "2", ".instagram.com", hostOnly: false);
|
||||
var api = SiteCookie.ForHost("c", "3", "www.instagram.com", "/api");
|
||||
var secure = SiteCookie.ForHost("d", "4", "127.0.0.1", secure: true);
|
||||
|
||||
Assert.IsTrue(host.Matches(Graph, Now));
|
||||
Assert.IsFalse(host.Matches(new Uri("https://help.instagram.com/"), Now), "Host-only: not a subdomain.");
|
||||
Assert.IsTrue(wide.Matches(new Uri("https://help.instagram.com/"), Now));
|
||||
Assert.IsTrue(wide.Matches(new Uri("https://instagram.com/"), Now));
|
||||
Assert.IsFalse(wide.Matches(new Uri("https://evilinstagram.com/"), Now), "A suffix only at a dot.");
|
||||
Assert.IsTrue(api.Matches(Graph, Now));
|
||||
Assert.IsTrue(api.Matches(new Uri("https://www.instagram.com/api"), Now));
|
||||
Assert.IsFalse(api.Matches(new Uri("https://www.instagram.com/apix/graphql"), Now), "A path prefix only at a «/».");
|
||||
Assert.IsFalse(api.Matches(new Uri("https://www.instagram.com/"), Now));
|
||||
Assert.IsFalse(secure.Matches(new Uri("http://127.0.0.1:8481/api/dati"), Now), "Secure: only over https.");
|
||||
Assert.IsTrue(secure.Matches(new Uri("https://127.0.0.1:8481/api/dati"), Now));
|
||||
Assert.IsFalse(new SiteCookie("e", "5", "0.0.1", hostOnly: false).Matches(new Uri("http://127.0.0.1/"), Now), "Never a suffix of an IP address.");
|
||||
Assert.IsFalse(SiteCookie.ForHost("f", string.Empty, "www.instagram.com").Matches(Graph, Now), "An empty cookie is not sent.");
|
||||
Assert.IsFalse(SiteCookie.ForHost("g", "7", "www.instagram.com", expires: Now).Matches(Graph, Now), "Expired.");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheCookiesOfARequestComeLongerPathsFirstThenInTheStoredOrder()
|
||||
{
|
||||
var values = new SiteSessionValues(
|
||||
[
|
||||
SiteCookie.ForHost("csrftoken", "radice", "www.instagram.com"),
|
||||
SiteCookie.ForHost("zeta", "z", "www.instagram.com"),
|
||||
SiteCookie.ForHost("csrftoken", "api", "www.instagram.com", "/api/"),
|
||||
new SiteCookie("mid", "m", "instagram.com", hostOnly: false),
|
||||
SiteCookie.ForHost("altrove", "x", "www.instagram.com", "/accounts/"),
|
||||
SiteCookie.ForHost("estraneo", "x", "www.facebook.com"),
|
||||
],
|
||||
"agente");
|
||||
|
||||
CollectionAssert.AreEqual(
|
||||
new[] { "csrftoken=api", "csrftoken=radice", "zeta=z", "mid=m" },
|
||||
values.CookiesFor(Graph, Now).Select(c => $"{c.Name}={c.Value}").ToArray());
|
||||
Assert.AreEqual("api", values.CookieFor("csrftoken", Graph, Now), "The one with the longest path, as x-csrftoken takes it.");
|
||||
Assert.AreEqual("radice", values.CookieFor("csrftoken", new Uri("https://www.instagram.com/marta/"), Now));
|
||||
Assert.IsNull(values.CookieFor("altrove", Graph, Now));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void AQuotedValueIsKeptAsTheBrowserKeepsItAndTheExpiryIsRead()
|
||||
{
|
||||
// RFC 6265 §5.2: the quotes are part of the value; sent back without them the cookie would not be the browser's.
|
||||
var rur = SiteCookies.Parse("rur=\"CLN\\05412\\0541795\"; Domain=.instagram.com; Path=/; Max-Age=3600", "www.instagram.com", Now)!.Value;
|
||||
var rur = SiteCookies.Parse("rur=\"CLN\\05412\\0541795\"; Domain=.instagram.com; Path=/; Max-Age=3600", Graph, Now)!.Cookie;
|
||||
Assert.AreEqual("\"CLN\\05412\\0541795\"", rur.Value);
|
||||
Assert.AreEqual(Now.AddHours(1), rur.Expires, "Max-Age from now.");
|
||||
|
||||
Assert.AreEqual(new DateTimeOffset(2027, 11, 16, 10, 0, 0, TimeSpan.Zero), SiteCookies.Parse("a=b; expires=Tue, 16 Nov 2027 10:00:00 GMT", "www.instagram.com", Now)!.Value.Expires);
|
||||
Assert.IsNull(SiteCookies.Parse("a=b; Path=/", "www.instagram.com", Now)!.Value.Expires, "No expiry: it lasts as the session.");
|
||||
Assert.IsNull(SiteCookies.Parse("a=b; Max-Age=0", "www.instagram.com", Now)!.Value.Expires, "A deletion has no expiry.");
|
||||
Assert.AreEqual(new DateTimeOffset(2027, 11, 16, 10, 0, 0, TimeSpan.Zero), SiteCookies.Parse("a=b; expires=Tue, 16 Nov 2027 10:00:00 GMT", Graph, Now)!.Cookie.Expires);
|
||||
Assert.IsNull(SiteCookies.Parse("a=b; Path=/", Graph, Now)!.Cookie.Expires, "No expiry: it lasts as the session.");
|
||||
Assert.IsNull(SiteCookies.Parse("a=b; Max-Age=0", Graph, Now)!.Cookie.Expires, "A deletion has no expiry.");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task NewCookiesKeepTheOrderOfTheSiteAndExpiredOnesAreNotSent()
|
||||
{
|
||||
var session = new InMemorySiteSession(new SiteSessionValues(
|
||||
[new("csrftoken", "c1"), new("sessionid", "s1"), new("vecchio", "v1")],
|
||||
"agente",
|
||||
expires: new Dictionary<string, DateTimeOffset> { ["vecchio"] = Now.AddMinutes(1) }));
|
||||
[Cookie("csrftoken", "c1"), Cookie("sessionid", "s1"), Cookie("vecchio", "v1", Now.AddMinutes(1))],
|
||||
"agente"));
|
||||
var capture = session.Read()!.Capture;
|
||||
|
||||
// Ten names, in an order no hash keeps by chance.
|
||||
var names = new[] { "ig_nrcb", "ps_l", "zz", "aa", "mid", "datr", "ps_n", "wd", "b1", "a9" };
|
||||
await session.UpdateAsync(
|
||||
new SiteSessionUpdate(names.Select(n => new KeyValuePair<string, string>(n, "x-" + n)), expires: new Dictionary<string, DateTimeOffset> { ["wd"] = Now.AddDays(7) }, capture: capture),
|
||||
new SiteSessionUpdate(names.Select(n => Cookie(n, "x-" + n, n == "wd" ? Now.AddDays(7) : null)), capture: capture),
|
||||
CancellationToken.None);
|
||||
|
||||
var values = session.Read()!;
|
||||
CollectionAssert.AreEqual(new[] { "csrftoken", "sessionid", "vecchio" }.Concat(names).ToArray(), values.Cookies.Select(c => c.Key).ToArray());
|
||||
CollectionAssert.AreEqual(new[] { "csrftoken", "sessionid", "vecchio" }.Concat(names).ToArray(), values.Cookies.Select(c => c.Name).ToArray());
|
||||
Assert.AreEqual(capture, values.Capture, "A renewal keeps the capture.");
|
||||
Assert.AreEqual(Now.AddDays(7), values.Expires["wd"]);
|
||||
Assert.AreEqual(Now.AddDays(7), values.Cookies.Single(c => c.Name == "wd").Expires);
|
||||
|
||||
Assert.AreEqual("v1", values.CookieAt("vecchio", Now));
|
||||
Assert.IsNull(values.CookieAt("vecchio", Now.AddMinutes(1)), "Expired: the browser would not send it.");
|
||||
Assert.IsFalse(values.CookiesAt(Now.AddMinutes(2)).Any(c => c.Key == "vecchio"));
|
||||
Assert.IsNull(values.CookieAt("wd", Now.AddDays(8)));
|
||||
Assert.AreEqual("s1", values.CookieAt("sessionid", Now.AddYears(5)), "No expiry: as long as the session.");
|
||||
Assert.AreEqual("v1", values.CookieFor("vecchio", Graph, Now));
|
||||
Assert.IsNull(values.CookieFor("vecchio", Graph, Now.AddMinutes(1)), "Expired: the browser would not send it.");
|
||||
Assert.IsFalse(values.CookiesFor(Graph, Now.AddMinutes(2)).Any(c => c.Name == "vecchio"));
|
||||
Assert.IsNull(values.CookieFor("wd", Graph, Now.AddDays(8)));
|
||||
Assert.AreEqual("s1", values.CookieFor("sessionid", Graph, Now.AddYears(5)), "No expiry: as long as the session.");
|
||||
|
||||
// Renewed without an expiry: the old expiry goes.
|
||||
await session.UpdateAsync(new SiteSessionUpdate([new("wd", "x2")], capture: capture), CancellationToken.None);
|
||||
Assert.IsFalse(session.Read()!.Expires.ContainsKey("wd"));
|
||||
await session.UpdateAsync(new SiteSessionUpdate([Cookie("wd", "x2")], capture: capture), CancellationToken.None);
|
||||
Assert.IsNull(session.Read()!.Cookies.Single(c => c.Name == "wd").Expires);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheSameNameOnTwoPathsIsTwoCookiesAndADeletionTouchesOnlyItsKey()
|
||||
{
|
||||
var session = new InMemorySiteSession(new SiteSessionValues(
|
||||
[
|
||||
Cookie("csrftoken", "radice"),
|
||||
SiteCookie.ForHost("csrftoken", "api", "www.instagram.com", "/api/"),
|
||||
new SiteCookie("csrftoken", "dominio", "instagram.com", hostOnly: false),
|
||||
],
|
||||
"agente"));
|
||||
Assert.AreEqual(3, session.Read()!.Cookies.Count, "Name, domain, path and host-only make the key.");
|
||||
|
||||
// The site renews the one at «/api/» and deletes the host-only one at «/»: the domain cookie stays as it was.
|
||||
var renewal = SiteCookies.Parse("csrftoken=nuovo; Path=/api/", Graph, Now)!;
|
||||
var deletion = SiteCookies.Parse("csrftoken=; Path=/; Max-Age=0", Graph, Now)!;
|
||||
Assert.IsTrue(deletion.Deletes);
|
||||
await session.UpdateAsync(new SiteSessionUpdate([renewal.Cookie], [deletion.Cookie.Key]), CancellationToken.None);
|
||||
|
||||
var cookies = session.Read()!.Cookies;
|
||||
CollectionAssert.AreEqual(new[] { "/api/ nuovo", "/ dominio" }, cookies.Select(c => $"{c.Path} {c.Value}").ToArray(), "Renewed in place, the deleted one gone.");
|
||||
Assert.IsFalse(cookies[1].HostOnly);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheLateAnswerOfAReplacedSessionChangesNothing()
|
||||
{
|
||||
var session = new InMemorySiteSession(new SiteSessionValues([new("sessionid", "vecchia")], "agente"));
|
||||
var session = new InMemorySiteSession(new SiteSessionValues([Cookie("sessionid", "vecchia")], "agente"));
|
||||
var old = session.Read()!.Capture;
|
||||
session.Replace(new SiteSessionValues([new("sessionid", "nuova")], "agente"));
|
||||
session.Replace(new SiteSessionValues([Cookie("sessionid", "nuova")], "agente"));
|
||||
Assert.AreNotEqual(old, session.Read()!.Capture, "A new login is a new capture.");
|
||||
|
||||
await session.UpdateAsync(new SiteSessionUpdate(cookiesDeleted: ["sessionid"], claim: "vecchio", capture: old), CancellationToken.None);
|
||||
await session.UpdateAsync(new SiteSessionUpdate(cookiesDeleted: [Cookie("sessionid", string.Empty).Key], claim: "vecchio", capture: old), CancellationToken.None);
|
||||
Assert.AreEqual("nuova", session.Read()!.Cookie("sessionid"));
|
||||
Assert.AreEqual(SiteSessionValues.InitialClaim, session.Read()!.Field("claim", "Op"), "No claim yet: the page's «0».");
|
||||
Assert.AreEqual(0, session.Updates);
|
||||
@@ -231,44 +330,91 @@ public sealed class SiteSessionTests
|
||||
[TestMethod]
|
||||
[DataRow("sessionid=abc; Domain=facebook.com")]
|
||||
[DataRow("sessionid=abc; Domain=evilinstagram.com")]
|
||||
[DataRow("sessionid=abc; Domain=com")]
|
||||
[DataRow("sessionid=abc; Domain=help.instagram.com")]
|
||||
[DataRow("sessionid=a\u0001b")]
|
||||
[DataRow("sessionid=caffè")]
|
||||
[DataRow("senza-uguale")]
|
||||
[DataRow("=abc")]
|
||||
[DataRow("nome con spazio=abc")]
|
||||
public void ACookieOfAnotherDomainOrNotACookieIsIgnored(string line) =>
|
||||
Assert.IsNull(SiteCookies.Parse(line, "www.instagram.com", Now));
|
||||
Assert.IsNull(SiteCookies.Parse(line, Graph, Now));
|
||||
|
||||
[TestMethod]
|
||||
public void ACookieThatABrowserWouldNotKeepIsRefusedWithoutItsValue()
|
||||
{
|
||||
foreach (var make in new Func<SiteCookie>[]
|
||||
{
|
||||
() => SiteCookie.ForHost("a=b", "segreto", "www.instagram.com"),
|
||||
() => SiteCookie.ForHost("a", "segreto;altro", "www.instagram.com"),
|
||||
() => SiteCookie.ForHost("a", "segreto\r\nx: y", "www.instagram.com"),
|
||||
() => SiteCookie.ForHost("a", "segreto", "www.instagram.com", "senza-barra"),
|
||||
() => SiteCookie.ForHost("a", "segreto", "host con spazi"),
|
||||
})
|
||||
{
|
||||
var refused = Assert.ThrowsExactly<ArgumentException>(() => make());
|
||||
Assert.IsFalse(refused.Message.Contains("segreto", StringComparison.Ordinal), refused.Message);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task AnUpdateIsAppliedAtOnceAndTheTextShowsNoValue()
|
||||
{
|
||||
var session = new InMemorySiteSession(new SiteSessionValues(
|
||||
[new("csrftoken", "segreto-1"), new("sessionid", "segreto-2"), new("rur", "segreto-3")],
|
||||
[Cookie("csrftoken", "segreto-1"), Cookie("sessionid", "segreto-2"), Cookie("rur", "segreto-3")],
|
||||
"Mozilla/5.0 segreto-agente",
|
||||
new Dictionary<string, string> { ["claim"] = "0", ["lsd"] = "segreto-4" },
|
||||
new Dictionary<string, string> { ["claim"] = "0", ["lsd"] = "segreto-4", ["rev"] = "segreto-11", ["entry_nonce"] = "segreto-12" },
|
||||
new Dictionary<string, string> { ["Op"] = "segreto-5" }));
|
||||
|
||||
await session.UpdateAsync(new SiteSessionUpdate(new Dictionary<string, string> { ["csrftoken"] = "segreto-6", ["nuovo"] = "segreto-7" }, ["rur"], "segreto-8"), CancellationToken.None);
|
||||
var update = new SiteSessionUpdate([Cookie("csrftoken", "segreto-6"), Cookie("nuovo", "segreto-7")], [Cookie("rur", string.Empty).Key], "segreto-8");
|
||||
await session.UpdateAsync(update, CancellationToken.None);
|
||||
await session.UpdateAsync(new SiteSessionUpdate(), CancellationToken.None);
|
||||
|
||||
var values = session.Read()!;
|
||||
CollectionAssert.AreEqual(new[] { "csrftoken", "sessionid", "nuovo" }, values.Cookies.Select(c => c.Key).ToArray(), "Renewed in place, new at the end, deleted gone.");
|
||||
CollectionAssert.AreEqual(new[] { "csrftoken", "sessionid", "nuovo" }, values.Cookies.Select(c => c.Name).ToArray(), "Renewed in place, new at the end, deleted gone.");
|
||||
Assert.AreEqual("segreto-6", values.Cookie("csrftoken"));
|
||||
Assert.AreEqual("segreto-8", values.Field("claim", "Op"));
|
||||
Assert.AreEqual("segreto-5", values.Field("doc_id", "Op"));
|
||||
Assert.AreEqual("segreto-11", values.Field("rev", "Op"));
|
||||
Assert.IsNull(values.Field("doc_id", "Altra"));
|
||||
Assert.AreEqual("Mozilla/5.0 segreto-agente", values.Field("user_agent", "Op"));
|
||||
Assert.AreEqual(1, session.Updates, "An empty update writes nothing.");
|
||||
|
||||
foreach (var text in new[] { session.ToString(), values.ToString(), new SiteSessionUpdate(new Dictionary<string, string> { ["a"] = "segreto-9" }, ["b"], "segreto-10").ToString() })
|
||||
var texts = new List<string> { session.ToString(), values.ToString(), update.ToString(), $"{values}", $"{update}" };
|
||||
texts.AddRange(values.Cookies.Select(c => c.ToString()));
|
||||
texts.AddRange(update.CookiesDeleted.Select(k => k.ToString()));
|
||||
texts.Add(SiteCookies.Parse("csrftoken=segreto-9; Path=/", Graph, Now)!.ToString());
|
||||
foreach (var text in texts)
|
||||
{
|
||||
Assert.IsFalse(text.Contains("segreto", StringComparison.Ordinal), text);
|
||||
Assert.IsFalse(text.Contains("csrftoken", StringComparison.Ordinal), text);
|
||||
}
|
||||
|
||||
Assert.ThrowsExactly<ArgumentException>(() => new SiteSessionValues([new("a=b", "c")], "agente"));
|
||||
foreach (var text in new[] { session.ToString(), values.ToString(), update.ToString() })
|
||||
{
|
||||
Assert.IsFalse(text.Contains("csrftoken", StringComparison.Ordinal), "The session's text has counts only: " + text);
|
||||
}
|
||||
|
||||
Assert.ThrowsExactly<ArgumentException>(() => new SiteSessionValues([], "agente", new Dictionary<string, string> { ["password"] = "x" }));
|
||||
Assert.ThrowsExactly<ArgumentException>(() => new SiteSessionValues([], "agente", new Dictionary<string, string> { ["user_agent"] = "x" }), "The user agent is not a page value.");
|
||||
|
||||
var empty = new InMemorySiteSession(null);
|
||||
await empty.UpdateAsync(new SiteSessionUpdate(claim: "x"), CancellationToken.None);
|
||||
Assert.IsNull(empty.Read(), "No session: an update creates none.");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheNewPageFieldsAreSessionFieldsAndTheVocabularyIsClosed()
|
||||
{
|
||||
foreach (var field in new[] { "rev", "hs", "hsi", "dpr", "ccg", "comet_req", "entry_nonce", "lsd", "fb_dtsg", "app_id", "account_id" })
|
||||
{
|
||||
Assert.IsTrue(SiteSessionValues.PageFields.Contains(field), field);
|
||||
Assert.IsTrue(ValueSource.SessionFields.Contains(field), field);
|
||||
}
|
||||
|
||||
CollectionAssert.AreEquivalent(new[] { "user_agent", "claim", "doc_id" }, ValueSource.SessionFields.Except(SiteSessionValues.PageFields).ToArray());
|
||||
Assert.IsFalse(ValueSource.SessionFields.Contains("spin_r"), "__spin_* stay pending: who adds them to the request is not shown.");
|
||||
}
|
||||
|
||||
private static SiteCookie Cookie(string name, string value, DateTimeOffset? expires = null) =>
|
||||
SiteCookie.ForHost(name, value, "www.instagram.com", expires: expires);
|
||||
}
|
||||
@@ -5,13 +5,14 @@ using Febe.Core.Collection.Requests;
|
||||
namespace Febe.Tests.Collection.Support;
|
||||
|
||||
/// <summary>
|
||||
/// The shipped Instagram catalog as tappa S4 will leave it for some operations: their headers and fields with a
|
||||
/// «pending» source dropped and the operation configured. Only for the tests of the site client contract, which need
|
||||
/// an Instagram operation the guard lets through; the shipped file keeps them not configured (rule 9).
|
||||
/// The shipped Instagram catalog as it would be once the «pending» sources are settled for some operations: their
|
||||
/// headers and fields with a «pending» source dropped and the operation configured (the «page» section already names a
|
||||
/// place for every session value they use). Only for the tests of the site client contract, which need an Instagram
|
||||
/// operation the guard lets through; the shipped file keeps them not configured (rule 9).
|
||||
/// </summary>
|
||||
public static class SettledCatalog
|
||||
{
|
||||
/// <summary>The operations whose variables the shapes show whole (only the headers and fields wait for S4).</summary>
|
||||
/// <summary>The operations whose variables the shapes show whole (only headers and fields still «pending» wait).</summary>
|
||||
public static IReadOnlyList<string> KnownVariables { get; } =
|
||||
[
|
||||
"PolarisProfileReelsTabContentQuery", "PolarisProfileTaggedTabContentQuery",
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
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));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
using Febe.App;
|
||||
using Febe.Core.Library;
|
||||
using Febe.Desktop.Core;
|
||||
using Febe.Tests.Desktop.Support;
|
||||
using Febe.Tests.Support;
|
||||
using Febe.Web.Engine;
|
||||
|
||||
namespace Febe.Tests.Desktop;
|
||||
|
||||
/// <summary>
|
||||
/// Issue #36, S4, spec §12 and §13.2, on the Windows side without Windows: the option «raccolta» of Febe.exe (pages by
|
||||
/// default) and the protector of the saved session, which comes from the Windows-only shell (DPAPI there, a fake here).
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class DesktopSessionOptionsTests
|
||||
{
|
||||
[TestMethod]
|
||||
public void TheCommandLineReadsRaccoltaAndPagesIsTheDefault()
|
||||
{
|
||||
var folders = new DesktopFolders("a", "b");
|
||||
Assert.IsTrue(DesktopCommandLine.TryParse([], out var plain, out var problem), problem);
|
||||
Assert.AreEqual(CollectionRoute.Pages, plain.Collection, "nothing changes by default");
|
||||
Assert.AreEqual(CollectionRoute.Pages, plain.AppOptions("c", folders).Collection);
|
||||
|
||||
Assert.IsTrue(DesktopCommandLine.TryParse(["--sito-di-prova", "http://127.0.0.1:8481", "--raccolta", "RICHIESTE"], out var requests, out problem), problem);
|
||||
Assert.AreEqual(CollectionRoute.Requests, requests.Collection);
|
||||
Assert.AreEqual(CollectionRoute.Requests, requests.AppOptions("c", folders).Collection);
|
||||
|
||||
Assert.IsFalse(DesktopCommandLine.TryParse(["--raccolta", "browser"], out _, out problem));
|
||||
StringAssert.Contains(problem, "pagine oppure richieste");
|
||||
Assert.IsFalse(DesktopCommandLine.TryParse(["--raccolta"], out _, out problem));
|
||||
StringAssert.Contains(problem, "Dopo --raccolta");
|
||||
StringAssert.Contains(DesktopCommandLine.Usage, "--raccolta pagine|richieste");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheProtectorIsTheShellsAndTheLogNamesOnlyItsScheme()
|
||||
{
|
||||
using var temp = new TempFolder("desktop-sessione");
|
||||
using var console = new StringWriter();
|
||||
var clock = new ManualClock(new DateTimeOffset(2026, 11, 17, 10, 0, 0, TimeSpan.Zero));
|
||||
using var log = new FebeLog(null, console, clock);
|
||||
var shell = new FakeDesktopShell();
|
||||
var platform = new DesktopPlatform(new DesktopOptions(), shell, new MemoryLocationStore(), dataFolderFixed: true);
|
||||
var data = new DataFolderLayout(temp.Combine("dati"));
|
||||
var context = new FebePlatformContext(
|
||||
new FebeAppOptions { DataFolder = data.Root, LibraryFolder = temp.Combine("libreria") },
|
||||
data,
|
||||
null!,
|
||||
clock,
|
||||
log,
|
||||
new BrowserUseTracker());
|
||||
|
||||
var protector = platform.CreateSessionProtector(context);
|
||||
Assert.AreSame(shell.SessionProtector, protector);
|
||||
StringAssert.Contains(console.ToString(), "Sessione salvata: cifrata con " + protector.Scheme);
|
||||
Assert.IsFalse(Directory.Exists(data.Session), "no key file on Windows: DPAPI needs none");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,313 @@
|
||||
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()!;
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,12 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
using Febe.App;
|
||||
using Febe.Browser.Cdp;
|
||||
using Febe.Browser.Hosting;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Security;
|
||||
using Febe.Desktop.Core;
|
||||
using Febe.Web.Native;
|
||||
|
||||
@@ -31,6 +33,11 @@ internal sealed class FakeDesktopShell : IDesktopShell
|
||||
/// <summary>Called with each browser as it is created, before Febe uses it (to set up the fake page).</summary>
|
||||
public Action<FakeBrowser>? OnCreated { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// DPAPI exists only on Windows: here AES-256-GCM, with a key made at run time (never a literal key in the tests).
|
||||
/// </summary>
|
||||
public ISessionProtector SessionProtector { get; } = new AesGcmSessionProtector(RandomNumberGenerator.GetBytes(SessionKey.Length));
|
||||
|
||||
public string? WebView2Version() => RuntimeVersion;
|
||||
|
||||
public IFebeBrowser CreateWebView2Browser(WebView2BrowserSettings settings, FebePlatformContext context)
|
||||
@@ -226,9 +233,44 @@ internal sealed class FakeCdp : ICdpSession
|
||||
{
|
||||
private readonly Lock _gate = new();
|
||||
private readonly Dictionary<string, List<Action<JsonElement>>> _handlers = new(StringComparer.Ordinal);
|
||||
private int _captureReads;
|
||||
private int _cookieReads;
|
||||
|
||||
public bool LoggedIn { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// What the copy of the session (issue #36, S4) reads from this page with its one evaluation (the user agent, the
|
||||
/// values and doc_id of the modules); null: the page answers nothing to it. Low-entropy test values only.
|
||||
/// </summary>
|
||||
public JsonObject? PageCapture { get; set; } = DefaultPageCapture();
|
||||
|
||||
/// <summary>How many times the copy's evaluation (the one that reads <c>navigator.userAgent</c>) was asked.</summary>
|
||||
public int CaptureReads => Volatile.Read(ref _captureReads);
|
||||
|
||||
/// <summary>How many times <c>Network.getCookies</c> was asked.</summary>
|
||||
public int CookieReads => Volatile.Read(ref _cookieReads);
|
||||
|
||||
/// <summary>The values of the test site's page, as the copy would find them.</summary>
|
||||
public static JsonObject DefaultPageCapture() => new()
|
||||
{
|
||||
["ua"] = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Finestra di prova",
|
||||
["values"] = new JsonObject
|
||||
{
|
||||
["lsd"] = Febe.SitoDiProva.TestSite.Lsd,
|
||||
["fb_dtsg"] = Febe.SitoDiProva.TestSite.Dtsg,
|
||||
["app_id"] = Febe.SitoDiProva.TestSite.AppId,
|
||||
["account_id"] = "1234",
|
||||
["rev"] = Febe.SitoDiProva.TestSite.Revision,
|
||||
["hs"] = Febe.SitoDiProva.TestSite.HasteSession,
|
||||
["hsi"] = Febe.SitoDiProva.TestSite.HasteSessionId,
|
||||
["dpr"] = Febe.SitoDiProva.TestSite.Dpr,
|
||||
["comet_req"] = Febe.SitoDiProva.TestSite.CometReq,
|
||||
["ccg"] = Febe.SitoDiProva.TestSite.ConnectionClass,
|
||||
["entry_nonce"] = Febe.SitoDiProva.TestSite.EntryNonce,
|
||||
},
|
||||
["docIds"] = new JsonObject { [Febe.SitoDiProva.TestSite.ProfileQuery] = Febe.SitoDiProva.TestSite.DocIds[Febe.SitoDiProva.TestSite.ProfileQuery] },
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Like the test site, which sets its session cookie on any visit: a navigation to an address starting with this
|
||||
/// logs in, and the page reports itself loaded. Null: only the test logs in.
|
||||
@@ -257,8 +299,9 @@ internal sealed class FakeCdp : ICdpSession
|
||||
{
|
||||
"Page.getFrameTree" => new JsonObject { ["frameTree"] = new JsonObject { ["frame"] = new JsonObject { ["id"] = "F1", ["url"] = Url } } },
|
||||
"Page.navigate" => Navigate(parameters),
|
||||
// The session cookie of Instagram, and the test site's one.
|
||||
"Network.getCookies" => new JsonObject { ["cookies"] = LoggedIn ? new JsonArray(new JsonObject { ["name"] = "sessionid" }, new JsonObject { ["name"] = "sessione_prova" }) : new JsonArray() },
|
||||
// The session cookie of Instagram, and the test site's ones (with the values and places the copy keeps).
|
||||
"Network.getCookies" => Cookies(),
|
||||
"Runtime.evaluate" when IsCapture(parameters) => Capture(),
|
||||
"Runtime.evaluate" when LogsInOnVisit is not null => new JsonObject { ["result"] = new JsonObject { ["type"] = "string", ["value"] = "complete" } },
|
||||
_ => new JsonObject(),
|
||||
};
|
||||
@@ -286,6 +329,48 @@ internal sealed class FakeCdp : ICdpSession
|
||||
});
|
||||
}
|
||||
|
||||
private static bool IsCapture(object? parameters) =>
|
||||
(parameters as JsonObject)?["expression"]?.GetValue<string>() is { } expression
|
||||
&& expression.Contains("navigator.userAgent", StringComparison.Ordinal);
|
||||
|
||||
private JsonObject Cookies()
|
||||
{
|
||||
Interlocked.Increment(ref _cookieReads);
|
||||
if (!LoggedIn)
|
||||
{
|
||||
return new JsonObject { ["cookies"] = new JsonArray() };
|
||||
}
|
||||
|
||||
static JsonObject Cookie(string name, string value, string domain, string path = "/") => new()
|
||||
{
|
||||
["name"] = name,
|
||||
["value"] = value,
|
||||
["domain"] = domain,
|
||||
["path"] = path,
|
||||
["expires"] = -1,
|
||||
["session"] = true,
|
||||
["secure"] = false,
|
||||
["httpOnly"] = true,
|
||||
};
|
||||
|
||||
return new JsonObject
|
||||
{
|
||||
["cookies"] = new JsonArray(
|
||||
Cookie("sessionid", "sessione-di-prova", ".instagram.com"),
|
||||
Cookie("sessione_prova", "sessione-di-prova", "127.0.0.1"),
|
||||
Cookie("csrftoken", "csrf-di-prova", "127.0.0.1"),
|
||||
Cookie("percorso_api", "solo-sotto-api", "127.0.0.1", "/api/")),
|
||||
};
|
||||
}
|
||||
|
||||
private JsonObject Capture()
|
||||
{
|
||||
Interlocked.Increment(ref _captureReads);
|
||||
return PageCapture is { } page
|
||||
? new JsonObject { ["result"] = new JsonObject { ["type"] = "object", ["value"] = JsonNode.Parse(page.ToJsonString()) } }
|
||||
: new JsonObject();
|
||||
}
|
||||
|
||||
private JsonObject Navigate(object? parameters)
|
||||
{
|
||||
var url = (parameters as JsonObject)?["url"]?.GetValue<string>();
|
||||
|
||||
@@ -0,0 +1,267 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using Febe.App;
|
||||
using Febe.Browser.Hosting;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Library;
|
||||
using Febe.Core.Security;
|
||||
using Febe.Server;
|
||||
using Febe.Tests.Support;
|
||||
using Febe.Web.Engine;
|
||||
|
||||
namespace Febe.Tests.Server;
|
||||
|
||||
/// <summary>
|
||||
/// Issue #36, S4, spec §11 and §13.2, on the Docker side: the option «raccolta» (pages by default), the key of the saved
|
||||
/// session from FEBE_CHIAVE_SESSIONE or Dati/sessione/chiave.bin, its checks at start-up, and the child processes that
|
||||
/// never inherit the password or the key. No value of a secret ever appears in a text. Keys are made at run time.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class SessionKeyOptionsTests
|
||||
{
|
||||
private const string Password = "password-di-prova";
|
||||
|
||||
[TestMethod]
|
||||
public void TheCollectionRouteIsPagesByDefaultAndComesFromTheOptionOrTheEnvironment()
|
||||
{
|
||||
Assert.IsTrue(ServerOptions.TryParse([], Env(("FEBE_PASSWORD", Password)), out var plain, out var problem), problem);
|
||||
Assert.AreEqual(CollectionRoute.Pages, plain.Collection, "nothing changes by default");
|
||||
Assert.AreEqual(CollectionRoute.Pages, plain.AppOptions().Collection);
|
||||
|
||||
Assert.IsTrue(ServerOptions.TryParse([], Env(("FEBE_PASSWORD", Password), ("FEBE_RACCOLTA", "richieste")), out var fromEnvironment, out problem), problem);
|
||||
Assert.AreEqual(CollectionRoute.Requests, fromEnvironment.Collection);
|
||||
Assert.AreEqual(CollectionRoute.Requests, fromEnvironment.AppOptions().Collection);
|
||||
|
||||
Assert.IsTrue(ServerOptions.TryParse(["--raccolta", "Pagine"], Env(("FEBE_RACCOLTA", "richieste")), out var commandLineWins, out problem), problem);
|
||||
Assert.AreEqual(CollectionRoute.Pages, commandLineWins.Collection, "the command line wins over the environment");
|
||||
|
||||
Assert.IsTrue(ServerOptions.TryParse(["--raccolta", "richieste"], Env(), out var fromOption, out problem), problem);
|
||||
Assert.AreEqual(CollectionRoute.Requests, fromOption.Collection);
|
||||
|
||||
Assert.IsFalse(ServerOptions.TryParse(["--raccolta", "browser"], Env(), out _, out problem));
|
||||
StringAssert.Contains(problem, "--raccolta");
|
||||
StringAssert.Contains(problem, "pagine oppure richieste");
|
||||
Assert.IsFalse(ServerOptions.TryParse(["--raccolta"], Env(), out _, out problem));
|
||||
StringAssert.Contains(problem, "Dopo --raccolta");
|
||||
Assert.IsFalse(ServerOptions.TryParse([], Env(("FEBE_RACCOLTA", "tutto")), out _, out problem));
|
||||
StringAssert.Contains(problem, "FEBE_RACCOLTA");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void FebeChiaveSessioneIsReadAndNeverInWarningsTheTextOrTheProblems()
|
||||
{
|
||||
var key = RandomNumberGenerator.GetBytes(SessionKey.Length);
|
||||
var text = Convert.ToBase64String(key);
|
||||
Assert.IsTrue(ServerOptions.TryParse([], Env(("FEBE_PASSWORD", Password), (SessionKey.EnvironmentVariable, text)), out var o, out var problem), problem);
|
||||
CollectionAssert.AreEqual(key, o.SessionKey);
|
||||
Assert.IsNull(o.SessionKeyProblem);
|
||||
Assert.IsEmpty(o.Warnings);
|
||||
|
||||
// The generated text of a record would print the password and the key: this one says only whether they are set.
|
||||
foreach (var shown in new[] { o.ToString(), $"{o}", o.AppOptions().ToString() })
|
||||
{
|
||||
Assert.DoesNotContain(Password, shown);
|
||||
Assert.DoesNotContain(text, shown);
|
||||
Assert.DoesNotContain(Convert.ToHexString(key), shown);
|
||||
}
|
||||
|
||||
StringAssert.Contains(o.ToString(), "FEBE_CHIAVE_SESSIONE = impostata");
|
||||
StringAssert.Contains(o.ToString(), "FEBE_PASSWORD = impostata");
|
||||
Assert.IsEmpty(StartupChecks.Run(o with { DataFolder = Path.GetTempPath() }).Where(p => p.Code.StartsWith("chiave", StringComparison.Ordinal)));
|
||||
|
||||
// 64 hexadecimal digits are a key too.
|
||||
Assert.IsTrue(ServerOptions.TryParse([], Env((SessionKey.EnvironmentVariable, Convert.ToHexString(key))), out var hex, out problem), problem);
|
||||
CollectionAssert.AreEqual(key, hex.SessionKey);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow("non-una-chiave")]
|
||||
[DataRow("corta")]
|
||||
public void AWrongSessionKeyIsAStartupProblemThatNeverEchoesTheValue(string wrong)
|
||||
{
|
||||
foreach (var value in new[] { wrong, Convert.ToBase64String(RandomNumberGenerator.GetBytes(16)), Convert.ToBase64String(RandomNumberGenerator.GetBytes(48)) })
|
||||
{
|
||||
Assert.IsTrue(ServerOptions.TryParse([], Env(("FEBE_PASSWORD", Password), (SessionKey.EnvironmentVariable, value)), out var o, out var parseProblem), parseProblem);
|
||||
Assert.IsNull(o.SessionKey);
|
||||
Assert.IsNotNull(o.SessionKeyProblem);
|
||||
Assert.DoesNotContain(value, o.SessionKeyProblem);
|
||||
Assert.DoesNotContain(value, o.ToString());
|
||||
StringAssert.Contains(o.ToString(), "FEBE_CHIAVE_SESSIONE = non valida");
|
||||
|
||||
// Always said, whatever the «raccolta»: the engine and the browser do not start.
|
||||
foreach (var route in new[] { CollectionRoute.Pages, CollectionRoute.Requests })
|
||||
{
|
||||
var problem = StartupChecks.Run(o with { DataFolder = Path.GetTempPath(), Collection = route }).Single();
|
||||
Assert.AreEqual(StartupChecks.SessionKeyInvalid, problem.Code);
|
||||
StringAssert.Contains(problem.Message, "32 byte");
|
||||
StringAssert.Contains(problem.Remedy, "openssl rand -base64 32");
|
||||
foreach (var shown in new[] { problem.Title, problem.Message, problem.Remedy, problem.ToString() })
|
||||
{
|
||||
Assert.DoesNotContain(value, shown);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void AChiaveBinThatIsNotAKeyStopsOnlyTheRequestsRoute()
|
||||
{
|
||||
using var temp = new TempFolder("chiave-sessione");
|
||||
var data = new DataFolderLayout(temp.Path);
|
||||
Directory.CreateDirectory(data.Session);
|
||||
File.WriteAllBytes(data.SessionKeyFile, Encoding.ASCII.GetBytes("prova"));
|
||||
Assert.IsTrue(ServerOptions.TryParse(["--dati", temp.Path], Env(("FEBE_PASSWORD", Password)), out var o, out var parseProblem), parseProblem);
|
||||
|
||||
Assert.IsEmpty(StartupChecks.Run(o), "by the pages chiave.bin is never read");
|
||||
|
||||
var problem = StartupChecks.Run(o with { Collection = CollectionRoute.Requests }).Single();
|
||||
Assert.AreEqual(StartupChecks.SessionKeyFileInvalid, problem.Code);
|
||||
StringAssert.Contains(problem.Message, "chiave.bin");
|
||||
StringAssert.Contains(problem.Message, "5 byte");
|
||||
StringAssert.Contains(problem.Remedy, "Cancella Dati/sessione/chiave.bin");
|
||||
Assert.DoesNotContain("prova", problem.Message);
|
||||
|
||||
// With the variable set, chiave.bin is not read at all.
|
||||
var key = Convert.ToBase64String(RandomNumberGenerator.GetBytes(SessionKey.Length));
|
||||
Assert.IsTrue(ServerOptions.TryParse(["--dati", temp.Path, "--raccolta", "richieste"], Env(("FEBE_PASSWORD", Password), (SessionKey.EnvironmentVariable, key)), out var withKey, out parseProblem), parseProblem);
|
||||
Assert.IsEmpty(StartupChecks.Run(withKey));
|
||||
|
||||
// A missing chiave.bin is no problem: it will be made.
|
||||
File.Delete(data.SessionKeyFile);
|
||||
Assert.IsEmpty(StartupChecks.Run(o with { Collection = CollectionRoute.Requests }));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheDockerProtectorTakesTheKeyFromTheVariableOrFromChiaveBinAndLogsNoKey()
|
||||
{
|
||||
using var temp = new TempFolder("chiave-sessione");
|
||||
using var console = new StringWriter();
|
||||
var clock = new ManualClock(new DateTimeOffset(2026, 11, 17, 10, 0, 0, TimeSpan.Zero));
|
||||
using var log = new FebeLog(null, console, clock);
|
||||
var data = new DataFolderLayout(temp.Combine("dati"));
|
||||
var context = new FebePlatformContext(
|
||||
new FebeAppOptions { DataFolder = data.Root, LibraryFolder = temp.Combine("libreria") },
|
||||
data,
|
||||
null!,
|
||||
clock,
|
||||
log,
|
||||
new BrowserUseTracker());
|
||||
var plain = Encoding.UTF8.GetBytes("testo della sessione di prova");
|
||||
|
||||
// No variable: chiave.bin is made once, owner-only, and the next start reads the same key.
|
||||
Assert.IsTrue(ServerOptions.TryParse(["--dati", data.Root], Env(("FEBE_PASSWORD", Password)), out var o, out var problem), problem);
|
||||
var first = new DockerPlatform(o).CreateSessionProtector(context);
|
||||
Assert.AreEqual("aes-gcm", first.Scheme);
|
||||
Assert.AreEqual(SessionKey.Length, new FileInfo(data.SessionKeyFile).Length);
|
||||
if (!OperatingSystem.IsWindows())
|
||||
{
|
||||
Assert.AreEqual(OwnerOnlyFiles.OwnerFile, File.GetUnixFileMode(data.SessionKeyFile));
|
||||
Assert.AreEqual(OwnerOnlyFiles.OwnerFolder, File.GetUnixFileMode(data.Session));
|
||||
}
|
||||
|
||||
var stored = File.ReadAllBytes(data.SessionKeyFile);
|
||||
var blob = first.Protect(plain);
|
||||
var second = new DockerPlatform(o).CreateSessionProtector(context);
|
||||
CollectionAssert.AreEqual(plain, second.Unprotect(blob), "the same chiave.bin after a restart");
|
||||
CollectionAssert.AreEqual(stored, File.ReadAllBytes(data.SessionKeyFile), "chiave.bin is never replaced");
|
||||
|
||||
// The variable wins; the unused chiave.bin is named, not read.
|
||||
var key = RandomNumberGenerator.GetBytes(SessionKey.Length);
|
||||
var text = Convert.ToBase64String(key);
|
||||
Assert.IsTrue(ServerOptions.TryParse(["--dati", data.Root], Env(("FEBE_PASSWORD", Password), (SessionKey.EnvironmentVariable, text)), out var withKey, out problem), problem);
|
||||
var fromVariable = new DockerPlatform(withKey).CreateSessionProtector(context);
|
||||
Assert.ThrowsExactly<SessionUnreadableException>(() => fromVariable.Unprotect(blob), "another key");
|
||||
CollectionAssert.AreEqual(plain, new AesGcmSessionProtector(key).Unprotect(fromVariable.Protect(plain)));
|
||||
|
||||
var lines = console.ToString();
|
||||
StringAssert.Contains(lines, "chiave da Dati/sessione/chiave.bin");
|
||||
StringAssert.Contains(lines, "chiave da FEBE_CHIAVE_SESSIONE");
|
||||
StringAssert.Contains(lines, "chiave.bin non si usa");
|
||||
foreach (var secret in new[] { text, Convert.ToHexString(key), Convert.ToBase64String(stored), Convert.ToHexString(stored), Password })
|
||||
{
|
||||
Assert.DoesNotContain(secret, lines);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ChildProcessesNeverInheritThePasswordOrTheSessionKey()
|
||||
{
|
||||
var environment = new Dictionary<string, string?>(StringComparer.Ordinal)
|
||||
{
|
||||
["PATH"] = "/usr/bin",
|
||||
["FEBE_PASSWORD"] = Password,
|
||||
["febe_chiave_sessione"] = "chiave-di-prova",
|
||||
[SessionKey.EnvironmentVariable] = "chiave-di-prova",
|
||||
["FEBE_PORTA"] = "8480",
|
||||
};
|
||||
ChildProcessEnvironment.RemoveSecrets(environment);
|
||||
CollectionAssert.AreEquivalent(new[] { "PATH", "FEBE_PORTA" }, environment.Keys.ToList());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ChromiumStartsWithoutThePasswordOrTheKeyWhateverItsOptionsHold()
|
||||
{
|
||||
// The options of the launch are applied first, the secrets are removed last: neither the parent's environment
|
||||
// nor an option can hand them to the browser, which runs the site's code.
|
||||
await using var host = new ChromiumProcessHost(new ChromiumLaunchOptions
|
||||
{
|
||||
Environment = new Dictionary<string, string?>
|
||||
{
|
||||
["LANG"] = "it_IT.UTF-8",
|
||||
["FEBE_PASSWORD"] = Password,
|
||||
[SessionKey.EnvironmentVariable] = "chiave-di-prova",
|
||||
},
|
||||
});
|
||||
var info = host.BuildStartInfo("chromium", ["--no-first-run"], new BrowserOptions("/tmp/febe-profilo", 1280, 900, 9333) { Display = ":99" });
|
||||
Assert.AreEqual("it_IT.UTF-8", info.Environment["LANG"]);
|
||||
Assert.AreEqual(":99", info.Environment["DISPLAY"]);
|
||||
foreach (var name in ChildProcessEnvironment.SecretVariables)
|
||||
{
|
||||
Assert.IsFalse(info.Environment.Keys.Any(k => string.Equals(k, name, StringComparison.OrdinalIgnoreCase)), name);
|
||||
}
|
||||
|
||||
await using var xvfb = new XvfbProcess(executable: "Xvfb");
|
||||
var display = xvfb.BuildStartInfo("Xvfb");
|
||||
Assert.IsFalse(display.Environment.Keys.Any(ChildProcessEnvironment.IsSecret));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DoNotParallelize]
|
||||
public void FfmpegAndFfprobeStartWithoutThePasswordOrTheKeyOfFebesEnvironment()
|
||||
{
|
||||
// Febe's own environment holds both (as in Docker): ffprobe and ffmpeg must not inherit them (spec §13.2).
|
||||
using var folder = new TempFolder("figli");
|
||||
var tool = folder.Combine("strumento-di-prova");
|
||||
File.WriteAllText(tool, string.Empty);
|
||||
var before = ChildProcessEnvironment.SecretVariables.Select(n => (Name: n, Value: Environment.GetEnvironmentVariable(n))).ToList();
|
||||
try
|
||||
{
|
||||
foreach (var name in ChildProcessEnvironment.SecretVariables)
|
||||
{
|
||||
Environment.SetEnvironmentVariable(name, "valore-di-prova");
|
||||
}
|
||||
|
||||
Assert.IsTrue(new System.Diagnostics.ProcessStartInfo("x").Environment.Keys.Any(ChildProcessEnvironment.IsSecret), "The parent holds them.");
|
||||
var probe = Febe.Core.Import.FfprobeVideoMetadataProbe.TryCreate(tool)!.BuildStartInfo("video-di-prova.mp4");
|
||||
var frame = VideoFrameExtractor.TryCreate(tool)!.BuildStartInfo("video-di-prova.mp4", "1");
|
||||
foreach (var info in new[] { probe, frame })
|
||||
{
|
||||
Assert.IsFalse(info.Environment.Keys.Any(ChildProcessEnvironment.IsSecret), info.FileName);
|
||||
CollectionAssert.Contains(info.ArgumentList.ToArray(), "video-di-prova.mp4");
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
foreach (var (name, value) in before)
|
||||
{
|
||||
Environment.SetEnvironmentVariable(name, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static Func<string, string?> Env(params (string Name, string Value)[] values)
|
||||
{
|
||||
var map = values.ToDictionary(v => v.Name, v => v.Value, StringComparer.Ordinal);
|
||||
return name => map.GetValueOrDefault(name);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user