Sessione salvata cifrata, copiata a «Ho finito» (#36, S4)
verifica / controlli (push) Successful in 22s
verifica / prove (push) Successful in 16m46s
verifica / installatore (push) Successful in 4m43s
verifica / immagine (push) Successful in 21m2s

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:
Alby96andClaude Opus 5.5 committed 2026-11-17 16:43:43 +01:00
1 parent 3046b2da47
commit c87768766c
69 files changed
+5936 -415

No files matched your search

@@ -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));
}
}