Client del sito contro il sito di prova (#36, S2)
HttpSiteRequester è l'unica classe che parla col sito: va solo a https://www.instagram.com/ o a un sito di prova di loopback, non segue i rinvii, una richiesta per volta col permesso del Governatore, solo le intestazioni del catalogo con l'user agent della sessione, e registra solo operazione, forma del percorso e stato. Cookie rinnovati e claim finiscono nella sessione (ISiteSession, per ora in memoria; la copia cifrata è S4). SiteAnswerSignals traduce le risposte nei segnali di §7.6: 429 rallenta; rinvii, 401/403, HTML o campi mancanti valgono come Verifica (H16). Il sito di prova risponde alle richieste dirette come dice richieste.prova.json e simula i casi d'arresto; una visita senza sessione viva apre una sessione nuova anche per il client. Nulla è ancora collegato al motore (S3). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
e10c25d12d
commit
ce9691fe1c
19 files changed
+3563
-51
No files matched your search
@@ -0,0 +1,450 @@
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Text;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Collection.Requests;
|
||||
using Febe.SitoDiProva;
|
||||
using Febe.Tests.Browser.TestSupport;
|
||||
using Febe.Tests.Collection.Support;
|
||||
|
||||
namespace Febe.Tests.Collection;
|
||||
|
||||
/// <summary>
|
||||
/// What the HTTP site client (issue #36, S2) puts on the wire, read by a bare listener on 127.0.0.1: the headers of the
|
||||
/// catalog with the session's values and nothing else, the cookies as one line, the GraphQL form with the variables
|
||||
/// typed as the template; and where it refuses to go at all. Never Instagram: an Instagram address is only built,
|
||||
/// never asked.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class HttpSiteRequesterShapeTests
|
||||
{
|
||||
private const string UserAgent = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36";
|
||||
|
||||
[TestMethod]
|
||||
public async Task APlainAddressCarriesTheCatalogHeadersTheSessionCookiesAndNothingElse()
|
||||
{
|
||||
using var listener = new OneShotListener("""{"profilo":{"nome":"x"}}""");
|
||||
using var requester = Requester(listener.Port);
|
||||
|
||||
// An activity of the host (ASP.NET Core starts one per request) must not add «traceparent» to what leaves.
|
||||
using var activity = new System.Diagnostics.Activity("prova").Start();
|
||||
var answer = await requester.SendAsync(SiteRequest.For("profilo", (CaseValues.Username, "marta.prova")), Permit.Grant(ActionKind.ProfileOpen, null), CancellationToken.None);
|
||||
var request = await listener.Request;
|
||||
|
||||
Assert.AreEqual(200, answer.Status);
|
||||
Assert.IsTrue(answer.RootFieldsPresent);
|
||||
Assert.AreEqual("GET /api/dati/profilo/marta.prova?scheda=post HTTP/1.1", request.Line);
|
||||
CollectionAssert.AreEquivalent(
|
||||
new[] { "host", "accept", "user-agent", "x-app-id", "x-csrftoken", "cookie", "accept-encoding" },
|
||||
request.Headers.Select(h => h.Name).ToArray(),
|
||||
"Only the catalog's headers, the cookie line, and what the HTTP stack must write.");
|
||||
Assert.AreEqual(UserAgent, request.Header("user-agent"), "Copied as it is, double space included (rule 4).");
|
||||
Assert.AreEqual("application/json", request.Header("accept"));
|
||||
Assert.AreEqual(TestSite.AppId, request.Header("x-app-id"));
|
||||
Assert.AreEqual("csrf-1", request.Header("x-csrftoken"), "The value of the cookie csrftoken.");
|
||||
Assert.AreEqual("csrftoken=csrf-1; sessione_prova=attiva; rur=\"FRC\\05412\"", request.Header("cookie"), "One line, the session's order.");
|
||||
Assert.AreEqual("gzip, deflate, br", request.Header("accept-encoding"));
|
||||
Assert.AreEqual($"127.0.0.1:{listener.Port}", request.Header("host"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task AGraphQlQueryIsTheFormOfThePageWithTheVariablesTypedAsTheTemplate()
|
||||
{
|
||||
using var listener = new OneShotListener("""{"profilo":{"nome":"x"}}""");
|
||||
using var requester = Requester(listener.Port);
|
||||
|
||||
await requester.SendAsync(SiteRequest.For(TestSite.ProfileQuery, (CaseValues.Username, "marta.prova")), Permit.Grant(ActionKind.ProfileOpen, null), CancellationToken.None);
|
||||
var request = await listener.Request;
|
||||
|
||||
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" },
|
||||
request.Headers.Select(h => h.Name).ToArray());
|
||||
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"
|
||||
+ "&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.");
|
||||
Assert.AreEqual(Encoding.UTF8.GetByteCount(request.Body).ToString(System.Globalization.CultureInfo.InvariantCulture), request.Header("content-length"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void VariablesAndFormFieldsAreWrittenAsThePageWritesThem()
|
||||
{
|
||||
var search = RequestCatalog.LoadInstagram().Operations.Single(o => o.Name == "PolarisSearchBoxRefetchableQuery");
|
||||
var variables = HttpSiteRequester.Variables(search, SiteRequest.For(search.Name, (CaseValues.SearchText, "caffè & «latte» <b>\"x\"")));
|
||||
StringAssert.Contains(variables, "\"query\":\"caffè & «latte» <b>\\\"x\\\"\"", "No escaping of letters or of < > & (JSON.stringify).");
|
||||
Assert.IsFalse(variables.Contains("\": ", StringComparison.Ordinal) || variables.Contains(", \"", StringComparison.Ordinal), "No spaces between tokens.");
|
||||
|
||||
Assert.AreEqual("a+b%26c%3Dd%C3%A8*-._%2B%2F", HttpSiteRequester.FormEncode("a b&c=dè*-._+/"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task NoRedirectIsFollowed()
|
||||
{
|
||||
using var listener = new OneShotListener(string.Empty, status: "302 Found", extraHeaders: "Location: http://127.0.0.1:1/accounts/login/?next=%2Fmarta.prova%2F\r\nSet-Cookie: sessione_prova=; expires=Thu, 01 Jan 1970 00:00:00 GMT; 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());
|
||||
|
||||
var answer = await requester.SendAsync(SiteRequest.For("profilo", (CaseValues.Username, "marta.prova")), Permit.Grant(ActionKind.ProfileOpen, null), CancellationToken.None);
|
||||
|
||||
Assert.AreEqual(302, answer.Status);
|
||||
Assert.AreEqual("/accounts/login/", answer.RedirectPathShape);
|
||||
Assert.IsTrue(answer.Deletes(TestSite.SessionCookie));
|
||||
Assert.IsNull(session.Read()!.Cookie(TestSite.SessionCookie));
|
||||
Assert.AreEqual(1, listener.Connections, "One request: the redirect was not followed (port 1 was never tried either).");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow("prova", "http://example.com/")]
|
||||
[DataRow("prova", "http://10.1.2.3:8080/")]
|
||||
[DataRow("prova", "https://www.instagram.com/")]
|
||||
[DataRow("prova", "http://localhost:8481/")]
|
||||
[DataRow("prova", "http://127.0.0.1:8481/api/")]
|
||||
[DataRow("prova", "http://utente:segreto@127.0.0.1:8481/")]
|
||||
[DataRow("prova", "ftp://127.0.0.1/")]
|
||||
[DataRow("instagram", "http://www.instagram.com/")]
|
||||
[DataRow("instagram", "https://instagram.com/")]
|
||||
[DataRow("instagram", "https://www.instagram.com:8443/")]
|
||||
[DataRow("instagram", "https://www.instagram.com.example.net/")]
|
||||
[DataRow("instagram", "https://127.0.0.1/")]
|
||||
public void AnyOtherAddressIsRefusedBeforeAnyConnection(string site, string address)
|
||||
{
|
||||
var catalog = site == "instagram" ? SettledCatalog.Instagram() : RequestCatalog.LoadTestSite();
|
||||
var options = site == "instagram" ? HttpSiteRequesterOptions.Instagram() with { SiteAddress = new Uri(address) } : HttpSiteRequesterOptions.TestSite(new Uri(address));
|
||||
var refused = Assert.ThrowsExactly<ArgumentException>(() => new HttpSiteRequester(catalog, new InMemorySiteSession(Session()), options, new VirtualClock()));
|
||||
Assert.IsFalse(refused.Message.Contains("segreto", StringComparison.Ordinal));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheOnlyAddressesAreInstagramOverHttpsAndLoopbackTestSites()
|
||||
{
|
||||
Assert.IsNull(HttpSiteRequester.RefusalOfAddress(SettledCatalog.Instagram(), HttpSiteRequesterOptions.InstagramAddress));
|
||||
Assert.IsNull(HttpSiteRequester.RefusalOfAddress(RequestCatalog.LoadTestSite(), new Uri("http://127.0.0.1:8481/")));
|
||||
Assert.IsNull(HttpSiteRequester.RefusalOfAddress(RequestCatalog.LoadTestSite(), new Uri("http://127.0.0.2:8481/")));
|
||||
Assert.IsNull(HttpSiteRequester.RefusalOfAddress(RequestCatalog.LoadTestSite(), new Uri("https://[::1]:8443/")));
|
||||
|
||||
// Built, never asked: the constructor opens no connection.
|
||||
using var instagram = new HttpSiteRequester(SettledCatalog.Instagram(), new InMemorySiteSession(null), HttpSiteRequesterOptions.Instagram(), new VirtualClock());
|
||||
Assert.AreEqual("https://www.instagram.com/", instagram.Site.AbsoluteUri);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheHandlerFollowsNothingKeepsNoCookiesAndSpeaksHttp2OrHttp11()
|
||||
{
|
||||
using var site = HttpSiteRequester.CreateHandler(HttpSiteRequesterOptions.Instagram(), loopback: false);
|
||||
Assert.IsFalse(site.AllowAutoRedirect);
|
||||
Assert.IsFalse(site.UseCookies);
|
||||
Assert.IsTrue(site.UseProxy, "The system proxy, as WebView2.");
|
||||
Assert.IsNull(site.Proxy, "Null is HttpClient.DefaultProxy, the system's.");
|
||||
Assert.AreEqual(System.Net.DecompressionMethods.GZip | System.Net.DecompressionMethods.Deflate | System.Net.DecompressionMethods.Brotli, site.AutomaticDecompression);
|
||||
Assert.AreEqual(TimeSpan.FromSeconds(10), site.ConnectTimeout);
|
||||
Assert.IsNull(site.ActivityHeadersPropagator, "No traceparent or Request-Id added to the request.");
|
||||
|
||||
using var local = HttpSiteRequester.CreateHandler(HttpSiteRequesterOptions.TestSite(new Uri("http://127.0.0.1:1/")), loopback: true);
|
||||
Assert.IsFalse(local.UseProxy, "A loopback test site is never reached through a proxy.");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ARenewedCookieAndTheClaimAreKeptAndTheAnswerShowsOnlyTheirNames()
|
||||
{
|
||||
using var listener = new OneShotListener("""{"profilo":{}}""", extraHeaders: "Set-Cookie: csrftoken=csrf-2; Max-Age=31449600; Path=/; Secure\r\nSet-Cookie: estraneo=1; Domain=altro.example; Path=/\r\nx-ig-set-www-claim: hmac.nuovo\r\nRetry-After: 30\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());
|
||||
|
||||
var answer = await requester.SendAsync(SiteRequest.For("profilo", (CaseValues.Username, "marta.prova")), Permit.Grant(ActionKind.ProfileOpen, null), CancellationToken.None);
|
||||
|
||||
CollectionAssert.AreEqual(new[] { "csrftoken" }, answer.CookiesSet.ToArray(), "A cookie of another domain is not the site's.");
|
||||
Assert.IsTrue(answer.SetsClaim);
|
||||
Assert.AreEqual(TimeSpan.FromSeconds(30), answer.RetryAfter);
|
||||
Assert.AreEqual("csrf-2", session.Read()!.Cookie("csrftoken"));
|
||||
Assert.IsNull(session.Read()!.Cookie("estraneo"));
|
||||
Assert.AreEqual("hmac.nuovo", session.Read()!.Fields["claim"]);
|
||||
Assert.IsFalse(answer.ToString().Contains("csrf-2", StringComparison.Ordinal));
|
||||
Assert.IsFalse(answer.ToString().Contains("hmac", StringComparison.Ordinal));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheVariablesAreWhatJsonStringifyWrites()
|
||||
{
|
||||
var search = RequestCatalog.LoadInstagram().Operations.Single(o => o.Name == "PolarisSearchBoxRefetchableQuery");
|
||||
var variables = HttpSiteRequester.Variables(search, SiteRequest.For(search.Name, (CaseValues.SearchText, "mare \U0001F30A \\ \"blu\"")));
|
||||
StringAssert.Contains(variables, "\"query\":\"mare \U0001F30A \\\\ \\\"blu\\\"\"", "The emoji as it is, never \\uD83C\\uDF0A.");
|
||||
using (var parsed = System.Text.Json.JsonDocument.Parse(variables))
|
||||
{
|
||||
Assert.IsNotNull(parsed, "Still JSON.");
|
||||
}
|
||||
|
||||
// JSON.stringify (ECMA-262 QuoteJSONString): U+2028, U+2029 and DEL as they are; controls and a lone surrogate
|
||||
// as lower-case \u; the short escapes.
|
||||
var text = new System.Text.StringBuilder();
|
||||
HttpSiteRequester.WriteString(text, "a\u2028b\u2029c\u007F d\u0001e\u001f\b\f\n\r\t" + "\ud800" + "!");
|
||||
Assert.AreEqual("\"a\u2028b\u2029c\u007F d\\u0001e\\u001f\\b\\f\\n\\r\\t\\ud800!\"", text.ToString());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task ARenewalCountsAsSoonAsTheHeadersArriveWhateverHappensToTheBody()
|
||||
{
|
||||
// The body is larger than allowed: no answer, but the site rotated the cookie and the claim with the headers.
|
||||
using (var listener = new OneShotListener(new string('x', 4096), extraHeaders: "Set-Cookie: sessione_prova=rinnovata; Path=/\r\nSet-Cookie: rur=\"CLN\\05412\"; Path=/\r\nx-ig-set-www-claim: hmac.nuovo\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}/")) with { MaxBodyBytes = 64 }, new VirtualClock());
|
||||
var large = await Assert.ThrowsExactlyAsync<SiteUnreachableException>(() => requester.SendAsync(Profile(), Permit.Grant(ActionKind.ProfileOpen, null), CancellationToken.None));
|
||||
Assert.AreEqual(SiteUnreachableReason.TooLarge, large.Reason);
|
||||
Assert.AreEqual("rinnovata", session.Read()!.Cookie(TestSite.SessionCookie));
|
||||
Assert.AreEqual("\"CLN\\05412\"", session.Read()!.Cookie("rur"), "Quotes kept, as the browser keeps them.");
|
||||
Assert.AreEqual("hmac.nuovo", session.Read()!.Fields["claim"]);
|
||||
}
|
||||
|
||||
// The body never ends and the caller cancels while it is read: the deletion of the session cookie still counts.
|
||||
using (var listener = new OneShotListener("{\"pro", extraHeaders: "Set-Cookie: sessione_prova=; expires=Thu, 01 Jan 1970 00:00:00 GMT; Path=/\r\n", declaredLength: 1000, holdOpen: true))
|
||||
{
|
||||
var session = new InMemorySiteSession(Session());
|
||||
var log = new List<string>();
|
||||
using var requester = new HttpSiteRequester(RequestCatalog.LoadTestSite(), session, HttpSiteRequesterOptions.TestSite(new Uri($"http://127.0.0.1:{listener.Port}/")), new VirtualClock(), log.Add);
|
||||
using var caller = new CancellationTokenSource();
|
||||
var sending = requester.SendAsync(Profile(), Permit.Grant(ActionKind.ProfileOpen, null), caller.Token);
|
||||
await listener.Request;
|
||||
await WaitUntilAsync(() => session.Updates == 1);
|
||||
await caller.CancelAsync();
|
||||
await Assert.ThrowsAsync<OperationCanceledException>(() => sending);
|
||||
Assert.IsNull(session.Read()!.Cookie(TestSite.SessionCookie));
|
||||
Assert.IsTrue(log.Any(l => l.Contains("ha cancellato il cookie di sessione", StringComparison.Ordinal)));
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow("gzip")]
|
||||
[DataRow("br")]
|
||||
[DataRow("deflate")]
|
||||
public async Task ABodyThatDoesNotDecompressIsBrokenNotTooLarge(string encoding)
|
||||
{
|
||||
using var listener = new OneShotListener(string.Empty, extraHeaders: $"Content-Encoding: {encoding}\r\n", raw: [0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]);
|
||||
using var requester = Requester(listener.Port);
|
||||
var broken = await Assert.ThrowsExactlyAsync<SiteUnreachableException>(() => requester.SendAsync(Profile(), Permit.Grant(ActionKind.ProfileOpen, null), CancellationToken.None));
|
||||
Assert.AreEqual(SiteUnreachableReason.Broken, broken.Reason);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task AnExpiredSessionCookieIsAMissingSessionAndAnExpiredCookieIsNotSent()
|
||||
{
|
||||
var clock = new VirtualClock(new DateTimeOffset(2026, 11, 16, 10, 0, 0, TimeSpan.Zero));
|
||||
var values = Session();
|
||||
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) }));
|
||||
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);
|
||||
Assert.AreEqual("csrftoken=csrf-1; sessione_prova=attiva", (await listener.Request).Header("cookie"));
|
||||
}
|
||||
|
||||
// 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 }));
|
||||
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);
|
||||
Assert.AreEqual(1, listener.Connections);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task WithoutAClaimYetTheQuerySendsThePagesZero()
|
||||
{
|
||||
using var listener = new OneShotListener("""{"profilo":{}}""");
|
||||
var values = Session();
|
||||
var fields = values.Fields.Where(f => f.Key != "claim").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());
|
||||
await requester.SendAsync(SiteRequest.For(TestSite.ProfileQuery, (CaseValues.Username, "marta.prova")), Permit.Grant(ActionKind.ProfileOpen, null), CancellationToken.None);
|
||||
Assert.AreEqual("0", (await listener.Request).Header("x-ig-www-claim"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task DisposeEndsARequestInFlightAsACancellationAndRefusesLaterOnes()
|
||||
{
|
||||
using var listener = new OneShotListener("{", declaredLength: 1000, holdOpen: true);
|
||||
var requester = Requester(listener.Port);
|
||||
var sending = requester.SendAsync(Profile(), Permit.Grant(ActionKind.ProfileOpen, null), CancellationToken.None);
|
||||
await listener.Request;
|
||||
requester.Dispose();
|
||||
await Assert.ThrowsAsync<OperationCanceledException>(() => sending);
|
||||
await Assert.ThrowsExactlyAsync<ObjectDisposedException>(() => requester.SendAsync(Profile(), Permit.Grant(ActionKind.ProfileOpen, null), CancellationToken.None));
|
||||
requester.Dispose();
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void OnWindowsTheProxyVariablesWebView2IgnoresStopTheClient()
|
||||
{
|
||||
var none = new Dictionary<string, string?>();
|
||||
var set = new Dictionary<string, string?> { ["HTTPS_PROXY"] = "http://utente:segreto@proxy.example:3128", ["NO_PROXY"] = "localhost" };
|
||||
Assert.IsNull(HttpSiteRequester.EnvironmentProxyRefusal(windows: true, n => none.GetValueOrDefault(n)));
|
||||
Assert.IsNull(HttpSiteRequester.EnvironmentProxyRefusal(windows: false, n => set.GetValueOrDefault(n)), "In Docker Chromium reads them too.");
|
||||
var refusal = HttpSiteRequester.EnvironmentProxyRefusal(windows: true, n => set.GetValueOrDefault(n));
|
||||
Assert.IsNotNull(refusal);
|
||||
StringAssert.Contains(refusal, "HTTPS_PROXY");
|
||||
Assert.IsFalse(refusal.Contains("segreto", StringComparison.Ordinal) || refusal.Contains("proxy.example", StringComparison.Ordinal), "Never the value.");
|
||||
}
|
||||
|
||||
private static SiteRequest Profile() => SiteRequest.For("profilo", (CaseValues.Username, "marta.prova"));
|
||||
|
||||
private static async Task WaitUntilAsync(Func<bool> condition)
|
||||
{
|
||||
using var limit = new CancellationTokenSource(TimeSpan.FromSeconds(30));
|
||||
while (!condition())
|
||||
{
|
||||
await Task.Delay(10, limit.Token);
|
||||
}
|
||||
}
|
||||
|
||||
private static HttpSiteRequester Requester(int port) =>
|
||||
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\"")],
|
||||
UserAgent,
|
||||
new Dictionary<string, string> { ["app_id"] = TestSite.AppId, ["lsd"] = TestSite.Lsd, ["fb_dtsg"] = TestSite.Dtsg, ["claim"] = "0", ["account_id"] = "17841400000000077" },
|
||||
TestSite.DocIds);
|
||||
|
||||
/// <summary>The head and body of one HTTP/1.1 request, as they arrived.</summary>
|
||||
private sealed record RawRequest(string Line, IReadOnlyList<(string Name, string Value)> Headers, string Body)
|
||||
{
|
||||
public string Header(string name) => Headers.Single(h => h.Name == name).Value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A bare HTTP/1.1 listener on 127.0.0.1 that reads requests as they arrive and answers each with the same
|
||||
/// response, closing the connection: what the client really wrote, with nothing in between.
|
||||
/// </summary>
|
||||
private sealed class OneShotListener : IDisposable
|
||||
{
|
||||
private readonly TcpListener _listener;
|
||||
private readonly TaskCompletionSource<RawRequest> _first = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
private readonly CancellationTokenSource _stop = new();
|
||||
private readonly byte[] _response;
|
||||
private int _connections;
|
||||
|
||||
private readonly bool _holdOpen;
|
||||
|
||||
/// <param name="body">The body, as UTF-8.</param>
|
||||
/// <param name="status">Status line after the version.</param>
|
||||
/// <param name="extraHeaders">More header lines, each ending in CRLF.</param>
|
||||
/// <param name="raw">The body as bytes, in place of <paramref name="body"/>.</param>
|
||||
/// <param name="declaredLength">The Content-Length to declare, when it is not the body's (a body that never ends).</param>
|
||||
/// <param name="holdOpen">Keeps the connection open after writing, until disposed.</param>
|
||||
public OneShotListener(string body, string status = "200 OK", string extraHeaders = "", byte[]? raw = null, int? declaredLength = null, bool holdOpen = false)
|
||||
{
|
||||
Port = LocalTestSite.FreePort();
|
||||
_listener = new TcpListener(IPAddress.Loopback, Port);
|
||||
_listener.Start();
|
||||
var bytes = raw ?? Encoding.UTF8.GetBytes(body);
|
||||
_holdOpen = holdOpen;
|
||||
_response = [.. Encoding.ASCII.GetBytes($"HTTP/1.1 {status}\r\nContent-Type: application/json; charset=utf-8\r\nContent-Length: {declaredLength ?? bytes.Length}\r\n{extraHeaders}Connection: close\r\n\r\n"), .. bytes];
|
||||
_ = Task.Run(LoopAsync);
|
||||
}
|
||||
|
||||
public int Port { get; }
|
||||
|
||||
public int Connections => Volatile.Read(ref _connections);
|
||||
|
||||
public Task<RawRequest> Request => _first.Task.WaitAsync(TimeSpan.FromSeconds(30));
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_stop.Cancel();
|
||||
_listener.Stop();
|
||||
_stop.Dispose();
|
||||
}
|
||||
|
||||
private async Task LoopAsync()
|
||||
{
|
||||
while (!_stop.IsCancellationRequested)
|
||||
{
|
||||
TcpClient client;
|
||||
try
|
||||
{
|
||||
client = await _listener.AcceptTcpClientAsync(_stop.Token);
|
||||
}
|
||||
catch (Exception ex) when (ex is OperationCanceledException or SocketException or ObjectDisposedException)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
Interlocked.Increment(ref _connections);
|
||||
using (client)
|
||||
{
|
||||
try
|
||||
{
|
||||
var stream = client.GetStream();
|
||||
var request = await ReadAsync(stream);
|
||||
_first.TrySetResult(request);
|
||||
await stream.WriteAsync(_response, _stop.Token);
|
||||
if (_holdOpen)
|
||||
{
|
||||
await Task.Delay(Timeout.Infinite, _stop.Token);
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or OperationCanceledException or InvalidDataException)
|
||||
{
|
||||
_first.TrySetException(ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<RawRequest> ReadAsync(NetworkStream stream)
|
||||
{
|
||||
var buffer = new List<byte>();
|
||||
var chunk = new byte[4096];
|
||||
int end;
|
||||
while ((end = IndexOfHeadEnd(buffer)) < 0)
|
||||
{
|
||||
var read = await stream.ReadAsync(chunk, _stop.Token);
|
||||
if (read == 0)
|
||||
{
|
||||
throw new InvalidDataException("Richiesta interrotta.");
|
||||
}
|
||||
|
||||
buffer.AddRange(chunk.AsSpan(0, read).ToArray());
|
||||
}
|
||||
|
||||
var head = Encoding.ASCII.GetString([.. buffer.Take(end)]).Split("\r\n");
|
||||
var headers = head.Skip(1).Select(l =>
|
||||
{
|
||||
var colon = l.IndexOf(':', StringComparison.Ordinal);
|
||||
return (l[..colon].Trim().ToLowerInvariant(), l[(colon + 1)..].Trim());
|
||||
}).ToList();
|
||||
var length = headers.Where(h => h.Item1 == "content-length").Select(h => int.Parse(h.Item2, System.Globalization.CultureInfo.InvariantCulture)).FirstOrDefault();
|
||||
var body = buffer.Skip(end + 4).ToList();
|
||||
while (body.Count < length)
|
||||
{
|
||||
var read = await stream.ReadAsync(chunk, _stop.Token);
|
||||
if (read == 0)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
body.AddRange(chunk.AsSpan(0, read).ToArray());
|
||||
}
|
||||
|
||||
return new RawRequest(head[0], headers, Encoding.UTF8.GetString([.. body]));
|
||||
}
|
||||
|
||||
private static int IndexOfHeadEnd(List<byte> buffer)
|
||||
{
|
||||
for (var i = 0; i + 3 < buffer.Count; i++)
|
||||
{
|
||||
if (buffer[i] == '\r' && buffer[i + 1] == '\n' && buffer[i + 2] == '\r' && buffer[i + 3] == '\n')
|
||||
{
|
||||
return i;
|
||||
}
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,598 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Collection;
|
||||
using Febe.Core.Collection.Readers;
|
||||
using Febe.Core.Collection.Recipes;
|
||||
using Febe.Core.Collection.Requests;
|
||||
using Febe.SitoDiProva;
|
||||
using Febe.Tests.Support;
|
||||
using VirtualClock = Febe.Tests.Browser.TestSupport.VirtualClock;
|
||||
|
||||
namespace Febe.Tests.Collection;
|
||||
|
||||
/// <summary>
|
||||
/// The HTTP site client (issue #36, S2) against the real test site on 127.0.0.1, never Instagram: every configured
|
||||
/// operation of <c>richieste.prova.json</c> returns the data the pages read, the stop cases of §7.6 come back as answers
|
||||
/// and signals, redirects are never followed, the session keeps what the site renews, one request at a time, nothing
|
||||
/// leaves without its permit, and the log holds no value.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
[TestCategory(SyntheticSite.Category)]
|
||||
public sealed class HttpSiteRequesterTests
|
||||
{
|
||||
private const string UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36";
|
||||
private const string Csrf = "gettone-csrf-di-prova-7";
|
||||
private const string OtherCookie = "valore-di-un-altro-cookie";
|
||||
private const string AccountId = "17841400000000077";
|
||||
|
||||
private static readonly RequestCatalog Catalog = RequestCatalog.LoadTestSite();
|
||||
private static readonly SiteAnswerSignals Signals = new(SignalRules.LoadTestSite(), TestSite.SessionCookie);
|
||||
|
||||
[TestMethod]
|
||||
public async Task EveryConfiguredOperationReturnsTheDataThePagesRead()
|
||||
{
|
||||
// A fixed clock for the site: the signed addresses of the two answers must be the same to compare them.
|
||||
await using var site = await SyntheticSite.StartAsync(new FixedTime(DateTimeOffset.UtcNow));
|
||||
using var bed = new Bed(site);
|
||||
var cases = Cases(site);
|
||||
CollectionAssert.AreEquivalent(Catalog.Configured.Select(o => o.Name).ToArray(), cases.Keys.ToArray(), "Every configured operation has a case here.");
|
||||
|
||||
var reads = 0;
|
||||
foreach (var operation in Catalog.Configured)
|
||||
{
|
||||
var (values, pagePath) = cases[operation.Name];
|
||||
var answer = await bed.SendAsync(new SiteRequest(operation.Name, values), operation.Category);
|
||||
|
||||
Assert.AreEqual(200, answer.Status, operation.Name);
|
||||
Assert.AreEqual("application/json", answer.MimeType, operation.Name);
|
||||
Assert.IsTrue(answer.RootFieldsPresent, operation.Name);
|
||||
Assert.IsNull(Signals.Classify(operation, answer, bed.Clock.Now), operation.Name);
|
||||
|
||||
var page = await site.GetDataAsync(pagePath);
|
||||
Assert.IsTrue(JsonNode.DeepEquals(JsonNode.Parse(page), JsonNode.Parse(answer.Body.Span)), $"{operation.Name}: not the JSON of {pagePath}.");
|
||||
|
||||
// Through the delivery to the readers of lettori.prova.json, as the captured answer of the page.
|
||||
var requested = await ReadAsync(answer.Body, answer, bed.Clock);
|
||||
var captured = await ReadAsync(System.Text.Encoding.UTF8.GetBytes(page), answer, bed.Clock);
|
||||
CollectionAssert.AreEqual(captured, requested, operation.Name);
|
||||
reads += requested.Sum(r => r.Length);
|
||||
}
|
||||
|
||||
Assert.IsTrue(reads > 2000, "The readers keep something of the answers, so the comparison proves something.");
|
||||
Assert.AreEqual(Catalog.Configured.Count(), site.Control.DirectRequests.Count);
|
||||
Assert.IsTrue(site.Control.DirectRequests.All(r => r.StartsWith("GET /api/dati/", StringComparison.Ordinal) || r.StartsWith("POST /api/graphql", StringComparison.Ordinal)));
|
||||
StringAssert.StartsWith(site.Control.DirectRequests.Single(r => r.Contains("graphql", StringComparison.Ordinal)), "POST /api/graphql");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheStopCasesComeBackAsAnswersAndSignalsAndRedirectsAreNeverFollowed()
|
||||
{
|
||||
await using var site = await SyntheticSite.StartAsync();
|
||||
using var bed = new Bed(site);
|
||||
var profile = Profile();
|
||||
|
||||
site.Control.ReplyToDirect(DirectReply.TooManyRequests);
|
||||
var slow = await bed.SendAsync(profile, ActionKind.ProfileOpen);
|
||||
Assert.AreEqual(429, slow.Status);
|
||||
Assert.AreEqual(TimeSpan.FromSeconds(60), slow.RetryAfter);
|
||||
var throttle = Classify(slow);
|
||||
Assert.AreEqual(SignalLevel.Throttle, throttle.Signal.Level);
|
||||
Assert.AreEqual("http-429", throttle.Signal.Code);
|
||||
|
||||
site.Control.ReplyToDirect(DirectReply.RedirectToLogin);
|
||||
var login = await bed.SendAsync(profile, ActionKind.ProfileOpen);
|
||||
Assert.AreEqual(302, login.Status);
|
||||
Assert.IsTrue(login.IsRedirect);
|
||||
Assert.AreEqual("/{testo}/", login.RedirectPathShape, "Only the shape: no host, no query string with the path asked.");
|
||||
Assert.AreEqual(SiteAnswerSignals.RedirectCode, Classify(login).Signal.Code);
|
||||
Assert.AreEqual(SignalLevel.Challenge, Classify(login).Signal.Level);
|
||||
|
||||
site.Control.ReplyToDirect(DirectReply.RedirectToChallenge);
|
||||
var challenge = await bed.SendAsync(Graph(), ActionKind.ProfileOpen);
|
||||
Assert.AreEqual(302, challenge.Status);
|
||||
Assert.AreEqual(SiteAnswerSignals.RedirectCode, Classify(challenge).Signal.Code);
|
||||
|
||||
site.Control.ReplyToDirect(DirectReply.HtmlInsteadOfJson);
|
||||
var html = await bed.SendAsync(profile, ActionKind.ProfileOpen);
|
||||
Assert.IsTrue(html.IsHtml);
|
||||
Assert.IsFalse(html.RootFieldsPresent);
|
||||
Assert.AreEqual(SiteAnswerSignals.HtmlCode, Classify(html).Signal.Code);
|
||||
|
||||
site.Control.ReplyToDirect(DirectReply.MissingRootField);
|
||||
var missing = await bed.SendAsync(profile, ActionKind.ProfileOpen);
|
||||
Assert.AreEqual(200, missing.Status);
|
||||
Assert.IsTrue(missing.IsDeclaredData);
|
||||
Assert.IsFalse(missing.RootFieldsPresent);
|
||||
Assert.AreEqual(SiteAnswerSignals.MissingFieldsCode, Classify(missing).Signal.Code);
|
||||
Assert.AreEqual(SiteAnswerSignals.H16, Classify(missing).Hypothesis);
|
||||
|
||||
// The whole site's stop modes reach the site client too.
|
||||
site.Control.Set(StopMode.Challenge);
|
||||
var mode = await bed.SendAsync(profile, ActionKind.ProfileOpen);
|
||||
Assert.IsTrue(mode.IsRedirect);
|
||||
site.Control.Set(StopMode.Normal);
|
||||
|
||||
var fine = await bed.SendAsync(profile, ActionKind.ProfileOpen);
|
||||
Assert.AreEqual(200, fine.Status);
|
||||
Assert.IsNull(Signals.Classify(Operation("profilo"), fine, bed.Clock.Now));
|
||||
|
||||
Assert.AreEqual(0, site.Control.LoginPageVisits, "A redirect is a signal, never an address to visit.");
|
||||
Assert.AreEqual(0, site.Control.ChallengePageVisits);
|
||||
Assert.HasCount(7, site.Control.DirectRequests);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheSessionKeepsWhatTheSiteRenewsAndADeletedSessionCookieIsReported()
|
||||
{
|
||||
await using var site = await SyntheticSite.StartAsync();
|
||||
using var bed = new Bed(site);
|
||||
|
||||
site.Control.ReplyToDirect(DirectReply.RenewSessionCookie);
|
||||
var renewed = await bed.SendAsync(Profile(), ActionKind.ProfileOpen);
|
||||
Assert.AreEqual(200, renewed.Status);
|
||||
CollectionAssert.AreEqual(new[] { TestSite.SessionCookie }, renewed.CookiesSet.ToArray());
|
||||
Assert.AreEqual("rinnovata-1", bed.Session.Read()!.Cookie(TestSite.SessionCookie));
|
||||
Assert.IsFalse(site.Control.IsSession(SiteControl.InitialSession), "The old value stopped working on the site.");
|
||||
Assert.AreEqual(200, (await bed.SendAsync(Profile(), ActionKind.ProfileOpen)).Status, "The renewed cookie is the one sent now.");
|
||||
|
||||
site.Control.ReplyToDirect(DirectReply.SetClaim);
|
||||
var claimed = await bed.SendAsync(Graph(), ActionKind.ProfileOpen);
|
||||
Assert.IsTrue(claimed.SetsClaim);
|
||||
Assert.AreEqual("claim-prova-1", bed.Session.Read()!.Fields["claim"]);
|
||||
Assert.AreEqual(200, (await bed.SendAsync(Graph(), ActionKind.ProfileOpen)).Status);
|
||||
|
||||
site.Control.ReplyToDirect(DirectReply.DeleteSessionCookie);
|
||||
var deleted = await bed.SendAsync(Profile(), ActionKind.ProfileOpen);
|
||||
Assert.AreEqual(200, deleted.Status, "The data came, but the session is over.");
|
||||
Assert.IsTrue(deleted.Deletes(TestSite.SessionCookie));
|
||||
var signal = Classify(deleted);
|
||||
Assert.AreEqual(SiteAnswerSignals.SessionCookieDeletedCode, signal.Signal.Code);
|
||||
Assert.AreEqual(SignalLevel.Challenge, signal.Signal.Level);
|
||||
Assert.IsNull(bed.Session.Read()!.Cookie(TestSite.SessionCookie));
|
||||
Assert.IsTrue(bed.Log.Any(l => l.Contains("ha cancellato il cookie di sessione", StringComparison.Ordinal)));
|
||||
|
||||
var sent = site.Control.DirectRequests.Count;
|
||||
var refused = await Assert.ThrowsExactlyAsync<SiteSessionMissingException>(() => bed.SendAsync(Profile(), ActionKind.ProfileOpen));
|
||||
Assert.AreEqual(TestSite.SessionCookie, refused.Missing);
|
||||
Assert.AreEqual(SignalLevel.Disconnect, SiteAnswerSignals.ForMissingSession(refused, bed.Clock.Now).Signal.Level);
|
||||
Assert.HasCount(sent, site.Control.DirectRequests, "Without the session cookie nothing leaves.");
|
||||
Assert.AreEqual(3, bed.Session.Updates);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task AnEndedSessionAMissingValueOrAWrongHeaderIsWhatARealSiteWouldAnswer()
|
||||
{
|
||||
await using var site = await SyntheticSite.StartAsync();
|
||||
|
||||
// A session cookie the site does not know (expired): a plain address is sent to the login page, a query gets 401.
|
||||
using (var stale = new Bed(site, Values(session: "scaduta")))
|
||||
{
|
||||
var rest = await stale.SendAsync(Profile(), ActionKind.ProfileOpen);
|
||||
Assert.AreEqual(302, rest.Status);
|
||||
Assert.AreEqual(SiteAnswerSignals.RedirectCode, Classify(rest).Signal.Code);
|
||||
var graph = await stale.SendAsync(Graph(), ActionKind.ProfileOpen);
|
||||
Assert.AreEqual(401, graph.Status);
|
||||
Assert.AreEqual(SiteAnswerSignals.UnauthorizedCode, Classify(graph).Signal.Code);
|
||||
Assert.AreEqual(0, site.Control.LoginPageVisits);
|
||||
}
|
||||
|
||||
// A header of the catalog with a value the site does not expect: 400 with a JSON without the fields.
|
||||
using (var wrongApp = new Bed(site, Values(appId: "un-altra-applicazione")))
|
||||
{
|
||||
var answer = await wrongApp.SendAsync(Profile(), ActionKind.ProfileOpen);
|
||||
Assert.AreEqual(400, answer.Status);
|
||||
Assert.AreEqual(SiteAnswerSignals.MissingFieldsCode, Classify(answer).Signal.Code);
|
||||
}
|
||||
|
||||
// Values the catalog asks for and the session does not have: nothing leaves.
|
||||
var before = site.Control.DirectRequests.Count;
|
||||
foreach (var (values, missing) in new[]
|
||||
{
|
||||
(Values(csrf: null), "x-csrftoken"),
|
||||
(Values(session: null), TestSite.SessionCookie),
|
||||
(Values(docIds: false), "doc_id"),
|
||||
})
|
||||
{
|
||||
using var bed = new Bed(site, values);
|
||||
var refused = await Assert.ThrowsExactlyAsync<SiteSessionMissingException>(() => bed.SendAsync(Graph(), ActionKind.ProfileOpen));
|
||||
Assert.AreEqual(missing, refused.Missing);
|
||||
}
|
||||
|
||||
using (var none = new Bed(site, noSession: true))
|
||||
{
|
||||
var refused = await Assert.ThrowsExactlyAsync<SiteSessionMissingException>(() => none.SendAsync(Profile(), ActionKind.ProfileOpen));
|
||||
Assert.IsNull(refused.Missing);
|
||||
}
|
||||
|
||||
Assert.HasCount(before, site.Control.DirectRequests);
|
||||
|
||||
// The site checks the token against its cookie, as a real site does (H16-generic answer): a plain client here,
|
||||
// only to show the test site refuses what the site client never sends.
|
||||
using var plain = new HttpClient(new SocketsHttpHandler { UseProxy = false, UseCookies = false, AllowAutoRedirect = false });
|
||||
using var request = new HttpRequestMessage(HttpMethod.Get, site.Url("/api/dati/inizio"));
|
||||
request.Headers.TryAddWithoutValidation("cookie", $"{TestSite.SessionCookie}={SiteControl.InitialSession}; {TestSite.CsrfCookie}={Csrf}");
|
||||
request.Headers.TryAddWithoutValidation("x-csrftoken", "un-altro-gettone");
|
||||
request.Headers.TryAddWithoutValidation("x-app-id", TestSite.AppId);
|
||||
request.Headers.TryAddWithoutValidation("accept", "application/json");
|
||||
request.Headers.TryAddWithoutValidation("user-agent", UserAgent);
|
||||
using var forbidden = await plain.SendAsync(request);
|
||||
Assert.AreEqual(403, (int)forbidden.StatusCode);
|
||||
Assert.AreEqual("text/html", forbidden.Content.Headers.ContentType?.MediaType);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheSiteChecksTheTypesOfTheVariablesAndTheFriendlyName()
|
||||
{
|
||||
await using var site = await SyntheticSite.StartAsync();
|
||||
|
||||
// An edited copy of the catalog that writes «primi» as a text: the request is not the page's, the site refuses it.
|
||||
var file = JsonNode.Parse(Febe.Core.Collection.SiteMap.ReadEmbeddedText("richieste.prova.json"))!.AsObject();
|
||||
var query = file["operations"]!.AsArray().Single(o => o!["name"]!.GetValue<string>() == TestSite.ProfileQuery)!;
|
||||
query["variables"]!["primi"] = "12";
|
||||
using (var typed = new Bed(site, catalog: RequestCatalog.Parse(file.ToJsonString(), "richieste.prova.json (modificato)")))
|
||||
{
|
||||
var answer = await typed.SendAsync(Graph(), ActionKind.ProfileOpen);
|
||||
Assert.AreEqual(400, answer.Status);
|
||||
Assert.AreEqual(SiteAnswerSignals.MissingFieldsCode, Classify(answer).Signal.Code);
|
||||
}
|
||||
|
||||
// A doc_id of another operation.
|
||||
var docIds = new Dictionary<string, string> { [TestSite.ProfileQuery] = "8000000000000002" };
|
||||
var values = Values();
|
||||
using var wrongDoc = new Bed(site, new SiteSessionValues(values.Cookies, values.UserAgent, values.Fields, docIds));
|
||||
Assert.AreEqual(400, (await wrongDoc.SendAsync(Graph(), ActionKind.ProfileOpen)).Status);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task OneRequestAtATimeAndTheOthersAreRefusedNotQueued()
|
||||
{
|
||||
await using var site = await SyntheticSite.StartAsync();
|
||||
using var bed = new Bed(site);
|
||||
site.Control.DirectDelay = TimeSpan.FromSeconds(1);
|
||||
site.Control.ReplyToDirect(DirectReply.TooManyRequests);
|
||||
|
||||
var first = bed.SendAsync(Profile(), ActionKind.ProfileOpen);
|
||||
await WaitUntilAsync(() => site.Control.DirectRequests.Count == 1);
|
||||
|
||||
// While the first is in flight: refused at once, not queued behind it (a queued one would leave right after a
|
||||
// 429 before anybody read it, rule 8).
|
||||
var others = await Task.WhenAll(Enumerable.Range(0, 3).Select(_ => Task.Run(async () =>
|
||||
{
|
||||
var refused = await Assert.ThrowsExactlyAsync<SiteRequestRefusedException>(() => bed.SendAsync(Profile(), ActionKind.ProfileOpen));
|
||||
return refused.Message;
|
||||
})));
|
||||
|
||||
Assert.AreEqual(429, (await first).Status);
|
||||
Assert.IsTrue(others.All(m => m.Contains("in corso", StringComparison.Ordinal)));
|
||||
Assert.HasCount(1, site.Control.DirectRequests, "Nothing left after the 429.");
|
||||
Assert.AreEqual(1, site.Control.MaxDirectInFlight, "Never two requests in flight.");
|
||||
|
||||
// Once the answer is in, the next may leave.
|
||||
site.Control.DirectDelay = TimeSpan.Zero;
|
||||
Assert.AreEqual(200, (await bed.SendAsync(Profile(), ActionKind.ProfileOpen)).Status);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheStopModesOfTheSiteCountTheRequestsOfTheSiteClientToo()
|
||||
{
|
||||
await using var site = await SyntheticSite.StartAsync();
|
||||
using var bed = new Bed(site);
|
||||
|
||||
// «After one data request»: the site client's requests count, as the pages' do.
|
||||
site.Control.Set(StopMode.TooManyRequests, afterDataRequests: 1);
|
||||
Assert.AreEqual(200, (await bed.SendAsync(Profile(), ActionKind.ProfileOpen)).Status);
|
||||
Assert.AreEqual(429, (await bed.SendAsync(Profile(), ActionKind.ProfileOpen)).Status);
|
||||
|
||||
// The session ends: the cookie goes, and on the site too.
|
||||
site.Control.Set(StopMode.SessionEnded);
|
||||
var ended = await bed.SendAsync(Profile(), ActionKind.ProfileOpen);
|
||||
Assert.AreEqual(302, ended.Status);
|
||||
Assert.IsTrue(ended.Deletes(TestSite.SessionCookie));
|
||||
Assert.IsFalse(site.Control.IsSession(SiteControl.InitialSession));
|
||||
Assert.IsNull(bed.Session.Read()!.Cookie(TestSite.SessionCookie));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheSessionThePagesOpenWorksForTheSiteClientAndEndsOnBothSides()
|
||||
{
|
||||
await using var site = await SyntheticSite.StartAsync();
|
||||
using var browser = new HttpClient(new SocketsHttpHandler { UseProxy = false, UseCookies = false, AllowAutoRedirect = false });
|
||||
|
||||
// The first visit is a login: a new value, never the fixed one, and the site client accepts it once copied.
|
||||
var (_, _, first) = await VisitAsync(browser, site, "/", null);
|
||||
Assert.IsFalse(string.IsNullOrEmpty(first));
|
||||
Assert.AreNotEqual(SiteControl.InitialSession, first);
|
||||
Assert.IsTrue(site.Control.IsSession(first));
|
||||
using (var copied = new Bed(site, Values(session: first)))
|
||||
{
|
||||
Assert.AreEqual(200, (await copied.SendAsync(Profile(), ActionKind.ProfileOpen)).Status);
|
||||
}
|
||||
|
||||
// The session expires on the page side: the browser loses the cookie and the site ends the value, so the same
|
||||
// value copied in the site client is refused afterwards.
|
||||
site.Control.Set(StopMode.SessionEnded);
|
||||
var (status, location, deleted) = await VisitAsync(browser, site, "/profilo/marta.prova", first);
|
||||
Assert.AreEqual(302, status);
|
||||
Assert.AreEqual("/sessione-scaduta", location);
|
||||
Assert.AreEqual(string.Empty, deleted, "The page deletes the cookie.");
|
||||
Assert.IsFalse(site.Control.IsSession(first));
|
||||
site.Control.Set(StopMode.Normal);
|
||||
using (var stale = new Bed(site, Values(session: first)))
|
||||
{
|
||||
var refused = await stale.SendAsync(Profile(), ActionKind.ProfileOpen);
|
||||
Assert.AreEqual(302, refused.Status);
|
||||
Assert.AreEqual("/{testo}/", refused.RedirectPathShape);
|
||||
}
|
||||
|
||||
// A new login (a visit without the cookie) opens a new session the site client accepts.
|
||||
var (_, _, second) = await VisitAsync(browser, site, "/", null);
|
||||
Assert.IsFalse(string.IsNullOrEmpty(second));
|
||||
Assert.AreNotEqual(first, second);
|
||||
using (var renewed = new Bed(site, Values(session: second)))
|
||||
{
|
||||
Assert.AreEqual(200, (await renewed.SendAsync(Profile(), ActionKind.ProfileOpen)).Status);
|
||||
}
|
||||
|
||||
// A browser that kept a value the site ended gets a new one at its next visit.
|
||||
var (_, _, third) = await VisitAsync(browser, site, "/", first);
|
||||
Assert.IsTrue(site.Control.IsSession(third));
|
||||
Assert.AreNotEqual(first, third);
|
||||
|
||||
// The data of the pages end the session too when it expires.
|
||||
site.Control.Set(StopMode.SessionEnded);
|
||||
using (var data = new HttpRequestMessage(HttpMethod.Get, site.Url("/dati/inizio")))
|
||||
{
|
||||
data.Headers.TryAddWithoutValidation("cookie", $"{TestSite.SessionCookie}={second}");
|
||||
using var answer = await browser.SendAsync(data);
|
||||
Assert.AreEqual(401, (int)answer.StatusCode);
|
||||
}
|
||||
|
||||
Assert.IsFalse(site.Control.IsSession(second));
|
||||
site.Control.Set(StopMode.Normal);
|
||||
using (var ended = new Bed(site, Values(session: second)))
|
||||
{
|
||||
Assert.AreEqual(302, (await ended.SendAsync(Profile(), ActionKind.ProfileOpen)).Status);
|
||||
}
|
||||
|
||||
Assert.AreEqual(0, site.Control.LoginPageVisits);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheLateAnswerOfAReplacedSessionDoesNotTouchTheNewOne()
|
||||
{
|
||||
await using var site = await SyntheticSite.StartAsync();
|
||||
using var bed = new Bed(site);
|
||||
site.Control.DirectDelay = TimeSpan.FromMilliseconds(500);
|
||||
site.Control.ReplyToDirect(DirectReply.DeleteSessionCookie);
|
||||
|
||||
var sending = bed.SendAsync(Profile(), ActionKind.ProfileOpen);
|
||||
await WaitUntilAsync(() => site.Control.DirectRequests.Count == 1);
|
||||
|
||||
// A new login while the request is in flight: «Ho finito» copies a new session.
|
||||
bed.Session.Replace(Values(session: "nuova-sessione"));
|
||||
var answer = await sending;
|
||||
|
||||
Assert.IsTrue(answer.Deletes(TestSite.SessionCookie), "The answer still says what the site did.");
|
||||
Assert.AreEqual("nuova-sessione", bed.Session.Read()!.Cookie(TestSite.SessionCookie), "But the new session is not changed by the old one's answer.");
|
||||
Assert.AreEqual(0, bed.Session.Updates);
|
||||
}
|
||||
|
||||
private static async Task WaitUntilAsync(Func<bool> condition)
|
||||
{
|
||||
using var limit = new CancellationTokenSource(TimeSpan.FromSeconds(30));
|
||||
while (!condition())
|
||||
{
|
||||
await Task.Delay(10, limit.Token);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task NothingLeavesWithoutAPermitGrantedForThatRequest()
|
||||
{
|
||||
await using var site = await SyntheticSite.StartAsync();
|
||||
using var bed = new Bed(site);
|
||||
|
||||
var denied = Permit.Deny(ActionKind.ProfileOpen, null, DenialReason.HourlyBudgetReached, "Tetto orario raggiunto.");
|
||||
await Assert.ThrowsExactlyAsync<SiteRequestRefusedException>(() => bed.Requester.SendAsync(Profile(), denied, CancellationToken.None));
|
||||
await Assert.ThrowsExactlyAsync<SiteRequestRefusedException>(() => bed.Requester.SendAsync(Profile(), Permit.Grant(ActionKind.StoryView, null), CancellationToken.None));
|
||||
await Assert.ThrowsExactlyAsync<SiteRequestRefusedException>(() => bed.Requester.SendAsync(new SiteRequest("cerca", new Dictionary<string, string> { [CaseValues.SearchText] = "marta" }), Permit.Grant(ActionKind.ProfileSearch, null), CancellationToken.None));
|
||||
Assert.IsEmpty(site.Control.DirectRequests);
|
||||
|
||||
var permit = Permit.Grant(ActionKind.ProfileOpen, null);
|
||||
await bed.Requester.SendAsync(Profile(), permit, CancellationToken.None);
|
||||
var again = await Assert.ThrowsExactlyAsync<SiteRequestRefusedException>(() => bed.Requester.SendAsync(Profile(), permit, CancellationToken.None));
|
||||
StringAssert.Contains(again.Message, "già stato usato");
|
||||
Assert.HasCount(1, site.Control.DirectRequests);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task NoAnswerIsAnErrorWithoutTheAddress()
|
||||
{
|
||||
await using var site = await SyntheticSite.StartAsync();
|
||||
site.Control.DirectDelay = TimeSpan.FromSeconds(5);
|
||||
using var slow = new Bed(site, options: HttpSiteRequesterOptions.TestSite(new Uri(site.SiteUrl + "/")) with { Timeout = TimeSpan.FromMilliseconds(300) });
|
||||
var timeout = await Assert.ThrowsExactlyAsync<SiteUnreachableException>(() => slow.SendAsync(Profile(), ActionKind.ProfileOpen));
|
||||
Assert.AreEqual(SiteUnreachableReason.Timeout, timeout.Reason);
|
||||
AssertNoAddress(timeout.Message, site.SitePort);
|
||||
|
||||
var closed = Browser.TestSupport.LocalTestSite.FreePort();
|
||||
using var nobody = new Bed(site, options: HttpSiteRequesterOptions.TestSite(new Uri($"http://127.0.0.1:{closed}/")));
|
||||
var unreachable = await Assert.ThrowsExactlyAsync<SiteUnreachableException>(() => nobody.SendAsync(Profile(), ActionKind.ProfileOpen));
|
||||
Assert.AreEqual(SiteUnreachableReason.Unreachable, unreachable.Reason);
|
||||
AssertNoAddress(unreachable.Message, closed);
|
||||
Assert.IsNull(unreachable.InnerException, "The network error may name the address: it is not passed on.");
|
||||
|
||||
using var caller = new CancellationTokenSource(TimeSpan.FromMilliseconds(200));
|
||||
using var patient = new Bed(site);
|
||||
await Assert.ThrowsAsync<OperationCanceledException>(() => patient.Requester.SendAsync(Profile(), Permit.Grant(ActionKind.ProfileOpen, null), caller.Token));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheLogNamesOnlyOperationsPathShapesAndStatuses()
|
||||
{
|
||||
await using var site = await SyntheticSite.StartAsync();
|
||||
using var bed = new Bed(site);
|
||||
var cases = Cases(site);
|
||||
foreach (var operation in Catalog.Configured)
|
||||
{
|
||||
await bed.SendAsync(new SiteRequest(operation.Name, cases[operation.Name].Values), operation.Category);
|
||||
}
|
||||
|
||||
foreach (var reply in new[] { DirectReply.RedirectToLogin, DirectReply.SetClaim, DirectReply.RenewSessionCookie, DirectReply.DeleteSessionCookie })
|
||||
{
|
||||
site.Control.ReplyToDirect(reply);
|
||||
await bed.SendAsync(Graph(), ActionKind.ProfileOpen);
|
||||
}
|
||||
|
||||
Assert.IsTrue(bed.Log.Count >= Catalog.Configured.Count() + 4);
|
||||
Assert.IsTrue(bed.Log.Any(l => l.Contains("«ProvaProfiloQuery» /api/graphql, stato 200", StringComparison.Ordinal)), string.Join("\n", bed.Log));
|
||||
Assert.IsTrue(bed.Log.Any(l => l.Contains("«profilo» /api/dati/profilo/{testo}, stato 200", StringComparison.Ordinal)), string.Join("\n", bed.Log));
|
||||
var secrets = new List<string>
|
||||
{
|
||||
Csrf, OtherCookie, SiteControl.InitialSession, "rinnovata-1", "claim-prova-1", TestSite.AppId, TestSite.Lsd, TestSite.Dtsg, AccountId,
|
||||
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));
|
||||
foreach (var line in bed.Log)
|
||||
{
|
||||
foreach (var secret in secrets)
|
||||
{
|
||||
Assert.IsFalse(line.Contains(secret, StringComparison.OrdinalIgnoreCase), $"«{secret}» in «{line}».");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static Dictionary<string, (Dictionary<string, string> Values, string PagePath)> Cases(TestSite site)
|
||||
{
|
||||
string code;
|
||||
string highlight;
|
||||
lock (site.World.Gate)
|
||||
{
|
||||
var marta = site.World.FindByUsername("marta.prova")!;
|
||||
code = marta.Posts[0].Code;
|
||||
highlight = marta.Highlights[0].Id;
|
||||
}
|
||||
|
||||
static Dictionary<string, string> V(params (string Name, string Value)[] values) => values.ToDictionary(v => v.Name, v => v.Value, StringComparer.Ordinal);
|
||||
return new(StringComparer.Ordinal)
|
||||
{
|
||||
["inizio"] = (V(), "/dati/inizio"),
|
||||
["profilo"] = (V((CaseValues.Username, "marta.prova")), "/dati/profilo/marta.prova?scheda=post"),
|
||||
["profilo-altri"] = (V((CaseValues.Username, "luca.prova"), (CaseValues.Cursor, "c12")), "/dati/profilo/luca.prova/altri?dopo=c12&scheda=post"),
|
||||
[TestSite.ProfileQuery] = (V((CaseValues.Username, "marta.prova")), "/dati/profilo/marta.prova?scheda=post"),
|
||||
["taggati"] = (V((CaseValues.Username, "marta.prova")), "/dati/profilo/marta.prova?scheda=taggati"),
|
||||
["post"] = (V((CaseValues.Code, code)), "/dati/post/" + code),
|
||||
["storie"] = (V((CaseValues.Username, "marta.prova")), "/dati/storie/marta.prova"),
|
||||
["evidenza"] = (V((CaseValues.HighlightId, highlight)), "/dati/evidenza/" + Uri.EscapeDataString(highlight)),
|
||||
["seguiti"] = (V(), "/dati/seguiti"),
|
||||
};
|
||||
}
|
||||
|
||||
private static async Task<string[]> ReadAsync(ReadOnlyMemory<byte> body, SiteAnswer answer, VirtualClock clock)
|
||||
{
|
||||
var collector = new CaptureCollector(new ShapeReader(ReaderVocabulary.LoadTestSite()), clock);
|
||||
var descriptor = new ResponseDescriptor("r1", HostKind.Site, "http://127.0.0.1" + answer.PathShape, "127.0.0.1", answer.PathShape, answer.Status, answer.MimeType, "Fetch", false, clock.Now);
|
||||
Assert.AreEqual(1, await new ResponseDelivery("Client del sito").DeliverBodyAsync(descriptor, body, [collector], CancellationToken.None));
|
||||
return [.. collector.Since(0).Select(r => JsonSerializer.Serialize(r.Result))];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A page visit as the browser makes it, with <paramref name="session"/> as its cookie: the status, the redirect and
|
||||
/// the value of the session cookie the page set (empty when it deleted it, null when it set none).
|
||||
/// </summary>
|
||||
private static async Task<(int Status, string? Location, string? Session)> VisitAsync(HttpClient browser, TestSite site, string path, string? session)
|
||||
{
|
||||
using var request = new HttpRequestMessage(HttpMethod.Get, site.Url(path));
|
||||
if (session is not null)
|
||||
{
|
||||
request.Headers.TryAddWithoutValidation("cookie", $"{TestSite.SessionCookie}={session}");
|
||||
}
|
||||
|
||||
using var response = await browser.SendAsync(request);
|
||||
string? set = null;
|
||||
if (response.Headers.TryGetValues("Set-Cookie", out var cookies))
|
||||
{
|
||||
var prefix = TestSite.SessionCookie + "=";
|
||||
set = cookies.Where(c => c.StartsWith(prefix, StringComparison.Ordinal)).Select(c => c[prefix.Length..].Split(';')[0]).LastOrDefault();
|
||||
}
|
||||
|
||||
return ((int)response.StatusCode, response.Headers.Location?.OriginalString, set);
|
||||
}
|
||||
|
||||
private static SiteRequest Profile() => SiteRequest.For("profilo", (CaseValues.Username, "marta.prova"));
|
||||
|
||||
private static SiteRequest Graph() => SiteRequest.For(TestSite.ProfileQuery, (CaseValues.Username, "marta.prova"));
|
||||
|
||||
private static SiteOperation Operation(string name) => Catalog.Operations.Single(o => o.Name == name);
|
||||
|
||||
private static SiteAnswerSignal Classify(SiteAnswer answer) =>
|
||||
Signals.Classify(Operation(answer.Operation), answer, DateTimeOffset.UnixEpoch) ?? throw new AssertFailedException($"Nessun segnale per {answer}.");
|
||||
|
||||
private static void AssertNoAddress(string message, int port)
|
||||
{
|
||||
Assert.IsFalse(message.Contains("127.0.0.1", StringComparison.Ordinal), message);
|
||||
Assert.IsFalse(message.Contains(port.ToString(System.Globalization.CultureInfo.InvariantCulture), StringComparison.Ordinal), message);
|
||||
Assert.IsFalse(message.Contains("marta", StringComparison.Ordinal), message);
|
||||
Assert.IsFalse(message.Contains("http", StringComparison.Ordinal), message);
|
||||
}
|
||||
|
||||
/// <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>>();
|
||||
if (csrf is not null)
|
||||
{
|
||||
cookies.Add(new(TestSite.CsrfCookie, csrf));
|
||||
}
|
||||
|
||||
if (session is not null)
|
||||
{
|
||||
cookies.Add(new(TestSite.SessionCookie, session));
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>A site client for the test site with its session, clock and log.</summary>
|
||||
private sealed class Bed : IDisposable
|
||||
{
|
||||
private readonly ConcurrentQueue<string> _log = new();
|
||||
|
||||
/// <param name="site">The test site.</param>
|
||||
/// <param name="values">The saved session; <see cref="Values"/> by default.</param>
|
||||
/// <param name="options">Options; the test site's by default.</param>
|
||||
/// <param name="noSession">No saved session at all.</param>
|
||||
/// <param name="catalog">The catalog; the shipped one by default.</param>
|
||||
public Bed(TestSite site, SiteSessionValues? values = null, HttpSiteRequesterOptions? options = null, bool noSession = false, RequestCatalog? catalog = null)
|
||||
{
|
||||
Session = new InMemorySiteSession(noSession ? null : values ?? Values());
|
||||
Requester = new HttpSiteRequester(catalog ?? Catalog, Session, options ?? HttpSiteRequesterOptions.TestSite(new Uri(site.SiteUrl + "/")), Clock, _log.Enqueue);
|
||||
}
|
||||
|
||||
public InMemorySiteSession Session { get; }
|
||||
|
||||
public VirtualClock Clock { get; } = new();
|
||||
|
||||
public HttpSiteRequester Requester { get; }
|
||||
|
||||
public IReadOnlyList<string> Log => [.. _log];
|
||||
|
||||
public Task<SiteAnswer> SendAsync(SiteRequest request, ActionKind kind) =>
|
||||
Requester.SendAsync(request, Permit.Grant(kind, null), CancellationToken.None);
|
||||
|
||||
public void Dispose() => Requester.Dispose();
|
||||
}
|
||||
|
||||
/// <summary>A clock that does not move.</summary>
|
||||
private sealed class FixedTime(DateTimeOffset now) : TimeProvider
|
||||
{
|
||||
public override DateTimeOffset GetUtcNow() => now;
|
||||
}
|
||||
}
|
||||
@@ -203,6 +203,16 @@ public sealed partial class RequestCatalogTests
|
||||
ownAgent["headers"] = new JsonObject { ["user-agent"] = "constant:Febe/1.0" };
|
||||
StringAssert.Contains(Refuse(Alone(ownAgent)), "user-agent");
|
||||
|
||||
// A configured operation without the browser's user agent would leave with none (rule 4).
|
||||
var noAgent = Rest("post2", "/dati/post/{code}");
|
||||
noAgent.Remove("headers");
|
||||
StringAssert.Contains(Refuse(Alone(noAgent)), "user-agent");
|
||||
var notConfigured = Rest("post2", "/dati/post/{code}");
|
||||
notConfigured.Remove("headers");
|
||||
notConfigured["configured"] = false;
|
||||
notConfigured["reason"] = "da campioni";
|
||||
Assert.IsNotNull(RequestCatalog.Parse(Alone(notConfigured), "richieste.prova.json"), "Not configured: it never leaves, the line can wait.");
|
||||
|
||||
var unknownValue = Rest("post2", "/dati/post/{password}");
|
||||
StringAssert.Contains(Refuse(Alone(unknownValue)), "valore del caso");
|
||||
|
||||
@@ -350,6 +360,7 @@ public sealed partial class RequestCatalogTests
|
||||
["path"] = path,
|
||||
["category"] = "post",
|
||||
["configured"] = true,
|
||||
["headers"] = new JsonObject { ["user-agent"] = "session:user_agent" },
|
||||
["rootFields"] = new JsonArray("contenuto"),
|
||||
["sample"] = "000005-post-serie",
|
||||
};
|
||||
@@ -362,7 +373,7 @@ public sealed partial class RequestCatalogTests
|
||||
["path"] = "/api/graphql",
|
||||
["category"] = "profilo",
|
||||
["configured"] = true,
|
||||
["headers"] = new JsonObject { ["x-fb-friendly-name"] = "operation" },
|
||||
["headers"] = new JsonObject { ["user-agent"] = "session:user_agent", ["x-fb-friendly-name"] = "operation" },
|
||||
["body"] = new JsonObject { ["variables"] = "variables", ["doc_id"] = "session:doc_id", ["fb_api_req_friendly_name"] = "operation" },
|
||||
["variables"] = new JsonObject { ["id"] = "{account_id}" },
|
||||
["rootFields"] = new JsonArray("data.user"),
|
||||
|
||||
@@ -0,0 +1,274 @@
|
||||
using System.Text;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Collection;
|
||||
using Febe.Core.Collection.Requests;
|
||||
using Febe.Tests.Collection.Support;
|
||||
|
||||
namespace Febe.Tests.Collection;
|
||||
|
||||
/// <summary>
|
||||
/// The stop signals of §7.6 read from the answers of the site client (issue #36, S2), whatever brought them: 429 as for
|
||||
/// the browser, and until the true shapes are known (H16) a redirect, a 401 or 403, an HTML or a JSON without the
|
||||
/// expected fields, a deleted session cookie are a Verifica; a JSON with its fields is no signal.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class SiteAnswerSignalsTests
|
||||
{
|
||||
private static readonly DateTimeOffset At = new(2026, 11, 16, 10, 0, 0, TimeSpan.Zero);
|
||||
private static readonly SiteOperation Tray = SettledCatalog.Instagram().Operations.Single(o => o.Name == "PolarisProfileStoryHighlightsTrayContentQuery");
|
||||
private static readonly SiteOperation Profile = RequestCatalog.LoadTestSite().Operations.Single(o => o.Name == "profilo");
|
||||
private static readonly SiteAnswerSignals Instagram = new(SignalRules.LoadDefault(), "sessionid");
|
||||
private static readonly SiteAnswerSignals Prova = new(SignalRules.LoadTestSite(), "sessione_prova");
|
||||
|
||||
[TestMethod]
|
||||
public void AJsonWithItsFieldsIsNoSignal()
|
||||
{
|
||||
Assert.IsNull(Prova.Classify(Profile, Json(Profile, 200, """{"profilo":{"nome":"marta"}}"""), At));
|
||||
Assert.IsNull(Prova.Classify(Profile, Json(Profile, 200, """{"profilo":{}}""", rootFieldsPresent: true), At));
|
||||
|
||||
// A cookie renewed or another cookie deleted is not a stop.
|
||||
Assert.IsNull(Prova.Classify(Profile, new SiteAnswer(Profile, 200, "application/json", Bytes("""{"profilo":{}}"""), cookiesSet: ["sessione_prova"], cookiesDeleted: ["altro"], setsClaim: true), At));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void A429IsARallentamentoAsForTheBrowser()
|
||||
{
|
||||
var signal = Instagram.Classify(Tray, new SiteAnswer(Tray, 429, "text/html", ReadOnlyMemory<byte>.Empty, retryAfter: TimeSpan.FromMinutes(2)), At)!;
|
||||
Assert.AreEqual(SignalLevel.Throttle, signal.Signal.Level);
|
||||
Assert.AreEqual("http-429", signal.Signal.Code);
|
||||
Assert.AreEqual(At, signal.Signal.At);
|
||||
StringAssert.Contains(signal.Message, "429");
|
||||
StringAssert.Contains(signal.Message, "120 s");
|
||||
|
||||
Assert.AreEqual(SignalLevel.Throttle, Prova.Classify(Profile, Json(Profile, 429, """{"errore":"troppe-richieste"}"""), At)!.Signal.Level);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow(301)]
|
||||
[DataRow(302)]
|
||||
[DataRow(303)]
|
||||
[DataRow(307)]
|
||||
public void ARedirectIsAVerificaAndShowsOnlyTheShapeOfWhereItPointed(int status)
|
||||
{
|
||||
var answer = new SiteAnswer(Tray, status, "text/html", ReadOnlyMemory<byte>.Empty, redirectTo: "https://www.instagram.com/accounts/login/?next=%2Fmarta.prova%2F");
|
||||
var signal = Instagram.Classify(Tray, answer, At)!;
|
||||
Assert.AreEqual(SignalLevel.Challenge, signal.Signal.Level);
|
||||
Assert.AreEqual(SiteAnswerSignals.RedirectCode, signal.Signal.Code);
|
||||
Assert.AreEqual(SiteAnswerSignals.H16, signal.Hypothesis);
|
||||
StringAssert.Contains(signal.Message, "/accounts/login/");
|
||||
StringAssert.Contains(signal.Message, "non seguito");
|
||||
Assert.IsFalse(signal.Message.Contains("marta", StringComparison.Ordinal));
|
||||
Assert.IsFalse(signal.Message.Contains("instagram.com", StringComparison.Ordinal));
|
||||
Assert.AreEqual(Tray.PathShape, signal.Signal.Url, "The address of the signal is the path shape, never a value.");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void A401OrA403IsAVerifica()
|
||||
{
|
||||
Assert.AreEqual(SiteAnswerSignals.UnauthorizedCode, Instagram.Classify(Tray, Json(Tray, 401, """{"message":"login_required"}"""), At)!.Signal.Code);
|
||||
var forbidden = Instagram.Classify(Tray, new SiteAnswer(Tray, 403, "text/html", Bytes("<html><body>CSRF</body></html>")), At)!;
|
||||
Assert.AreEqual(SiteAnswerSignals.ForbiddenCode, forbidden.Signal.Code);
|
||||
Assert.AreEqual(SignalLevel.Challenge, forbidden.Signal.Level);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void AnHtmlANonJsonOrAJsonWithoutTheExpectedFieldsIsAVerifica()
|
||||
{
|
||||
Assert.AreEqual(SiteAnswerSignals.HtmlCode, Classify(new SiteAnswer(Profile, 200, "text/html; charset=utf-8", Bytes("<!DOCTYPE html><html></html>"))));
|
||||
Assert.AreEqual(SiteAnswerSignals.HtmlCode, Classify(new SiteAnswer(Profile, 200, "application/json", Bytes("\n <!doctype HTML><html></html>"))), "Declared JSON, but an HTML document.");
|
||||
Assert.AreEqual(SiteAnswerSignals.NotJsonCode, Classify(new SiteAnswer(Profile, 200, "text/javascript", Bytes("for (;;);{\"a\":1}"))));
|
||||
Assert.AreEqual(SiteAnswerSignals.NotJsonCode, Classify(new SiteAnswer(Profile, 200, "application/json", ReadOnlyMemory<byte>.Empty)));
|
||||
|
||||
var missing = Prova.Classify(Profile, Json(Profile, 200, """{"risposta":{"voci":[]}}"""), At)!;
|
||||
Assert.AreEqual(SiteAnswerSignals.MissingFieldsCode, missing.Signal.Code);
|
||||
Assert.AreEqual(SignalLevel.Challenge, missing.Signal.Level);
|
||||
StringAssert.Contains(missing.Message, "profilo", "Names the expected fields.");
|
||||
Assert.IsFalse(missing.Message.Contains("voci", StringComparison.Ordinal), "Never the body.");
|
||||
|
||||
Assert.AreEqual(SiteAnswerSignals.MissingFieldsCode, Classify(Json(Profile, 200, """{"profilo":null}""")), "A null field is missing.");
|
||||
Assert.AreEqual(SiteAnswerSignals.MissingFieldsCode, Classify(Json(Profile, 200, """{"profilo":{}}""", rootFieldsPresent: false)), "What the site client saw wins.");
|
||||
Assert.AreEqual(SiteAnswerSignals.MissingFieldsCode, Classify(Json(Profile, 400, """{"errore":"richiesta-non-valida"}""")));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheSessionCookieDeletedIsAVerificaEvenWithGoodData()
|
||||
{
|
||||
var answer = new SiteAnswer(Tray, 200, "text/javascript", Bytes("""{"data":{}}"""), cookiesDeleted: ["sessionid"]);
|
||||
var signal = Instagram.Classify(Tray, answer, At)!;
|
||||
Assert.AreEqual(SiteAnswerSignals.SessionCookieDeletedCode, signal.Signal.Code);
|
||||
Assert.AreEqual(SignalLevel.Challenge, signal.Signal.Level);
|
||||
StringAssert.Contains(signal.Message, "cookie di sessione");
|
||||
Assert.AreEqual(SiteAnswerSignals.SessionCookieDeletedCode, Instagram.Classify(Tray, new SiteAnswer(Tray, 302, null, ReadOnlyMemory<byte>.Empty, redirectTo: "/accounts/login/", cookiesDeleted: ["sessionid"]), At)!.Signal.Code);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheTextRulesOfTheSiteApplyToShortJsonAnswers()
|
||||
{
|
||||
var wait = Instagram.Classify(Tray, Json(Tray, 400, """{"message":"Please wait a few minutes before you try again.","status":"fail"}"""), At)!;
|
||||
Assert.AreEqual(SignalLevel.Throttle, wait.Signal.Level);
|
||||
Assert.AreEqual("wait-text", wait.Signal.Code);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void AJsonNotFoundOrServerErrorIsLeftToTheCallerButAnHtmlOneStops()
|
||||
{
|
||||
Assert.IsNull(Classify(Json(Profile, 404, """{"errore":"non-trovato"}""")));
|
||||
Assert.IsNull(Classify(Json(Profile, 500, """{"status":"fail"}""")));
|
||||
|
||||
// §6.0: not JSON where JSON is expected stops the session, whatever the status (an HTML login or error page).
|
||||
Assert.AreEqual(SiteAnswerSignals.HtmlCode, Classify(new SiteAnswer(Profile, 404, "text/html", Bytes("<!DOCTYPE html><html></html>"))));
|
||||
Assert.AreEqual(SiteAnswerSignals.HtmlCode, Classify(new SiteAnswer(Profile, 500, "text/html", Bytes("<html></html>"))));
|
||||
Assert.AreEqual(SiteAnswerSignals.NotJsonCode, Classify(new SiteAnswer(Profile, 503, null, ReadOnlyMemory<byte>.Empty)));
|
||||
|
||||
// The text rules apply to a short JSON of any status.
|
||||
Assert.AreEqual("wait-text", Instagram.Classify(Tray, Json(Tray, 500, """{"message":"Please wait a few minutes before you try again."}"""), At)!.Signal.Code);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void AMissingSessionIsADisconnessioneAndAnAnswerOfAnotherOperationIsRefused()
|
||||
{
|
||||
var none = SiteAnswerSignals.ForMissingSession(new SiteSessionMissingException("…", missing: null), At);
|
||||
Assert.AreEqual(SignalLevel.Disconnect, none.Signal.Level);
|
||||
Assert.AreEqual(SiteAnswerSignals.SessionMissingCode, none.Signal.Code);
|
||||
StringAssert.Contains(SiteAnswerSignals.ForMissingSession(new SiteSessionMissingException("…", "x-csrftoken"), At).Message, "x-csrftoken");
|
||||
|
||||
Assert.ThrowsExactly<ArgumentException>(() => Prova.Classify(Profile, Json(Tray, 200, "{}"), At));
|
||||
}
|
||||
|
||||
private static string? Classify(SiteAnswer answer) => Prova.Classify(Profile, answer, At)?.Signal.Code;
|
||||
|
||||
private static SiteAnswer Json(SiteOperation operation, int status, string body, bool? rootFieldsPresent = null) =>
|
||||
new(operation, status, "application/json; charset=utf-8", Bytes(body), rootFieldsPresent: rootFieldsPresent);
|
||||
|
||||
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>
|
||||
[TestClass]
|
||||
public sealed class SiteSessionTests
|
||||
{
|
||||
private static readonly DateTimeOffset Now = new(2026, 11, 16, 10, 0, 0, TimeSpan.Zero);
|
||||
|
||||
[TestMethod]
|
||||
[DataRow("sessionid=abc; Path=/; HttpOnly", "abc", false)]
|
||||
[DataRow("sessionid=\"abc\"; Path=/", "\"abc\"", false)]
|
||||
[DataRow("sessionid=\"\"; Path=/", "\"\"", true)]
|
||||
[DataRow("sessionid=; Path=/", "", true)]
|
||||
[DataRow("sessionid=abc; Max-Age=0; Path=/", "abc", true)]
|
||||
[DataRow("sessionid=abc; Max-Age=-1", "abc", true)]
|
||||
[DataRow("sessionid=abc; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/", "abc", true)]
|
||||
[DataRow("sessionid=abc; expires=Wed, 16 Nov 2027 10:00:00 GMT; path=/", "abc", false)]
|
||||
[DataRow("sessionid=abc; expires=Thu, 01 Jan 1970 00:00:00 GMT; Max-Age=3600", "abc", false)]
|
||||
[DataRow("sessionid=abc; Domain=.instagram.com; Path=/", "abc", false)]
|
||||
[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);
|
||||
Assert.IsNotNull(cookie);
|
||||
Assert.AreEqual("sessionid", cookie.Value.Name);
|
||||
Assert.AreEqual(value, cookie.Value.Value);
|
||||
Assert.AreEqual(deletes, cookie.Value.Deletes);
|
||||
}
|
||||
|
||||
[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;
|
||||
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.");
|
||||
}
|
||||
|
||||
[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) }));
|
||||
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),
|
||||
CancellationToken.None);
|
||||
|
||||
var values = session.Read()!;
|
||||
CollectionAssert.AreEqual(new[] { "csrftoken", "sessionid", "vecchio" }.Concat(names).ToArray(), values.Cookies.Select(c => c.Key).ToArray());
|
||||
Assert.AreEqual(capture, values.Capture, "A renewal keeps the capture.");
|
||||
Assert.AreEqual(Now.AddDays(7), values.Expires["wd"]);
|
||||
|
||||
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.");
|
||||
|
||||
// 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"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheLateAnswerOfAReplacedSessionChangesNothing()
|
||||
{
|
||||
var session = new InMemorySiteSession(new SiteSessionValues([new("sessionid", "vecchia")], "agente"));
|
||||
var old = session.Read()!.Capture;
|
||||
session.Replace(new SiteSessionValues([new("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);
|
||||
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);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow("sessionid=abc; Domain=facebook.com")]
|
||||
[DataRow("sessionid=abc; Domain=evilinstagram.com")]
|
||||
[DataRow("senza-uguale")]
|
||||
[DataRow("=abc")]
|
||||
[DataRow("nome con spazio=abc")]
|
||||
public void ACookieOfAnotherDomainOrNotACookieIsIgnored(string line) =>
|
||||
Assert.IsNull(SiteCookies.Parse(line, "www.instagram.com", Now));
|
||||
|
||||
[TestMethod]
|
||||
public async Task AnUpdateIsAppliedAtOnceAndTheTextShowsNoValue()
|
||||
{
|
||||
var session = new InMemorySiteSession(new SiteSessionValues(
|
||||
[new("csrftoken", "segreto-1"), new("sessionid", "segreto-2"), new("rur", "segreto-3")],
|
||||
"Mozilla/5.0 segreto-agente",
|
||||
new Dictionary<string, string> { ["claim"] = "0", ["lsd"] = "segreto-4" },
|
||||
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);
|
||||
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.");
|
||||
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.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() })
|
||||
{
|
||||
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"));
|
||||
Assert.ThrowsExactly<ArgumentException>(() => new SiteSessionValues([], "agente", new Dictionary<string, string> { ["password"] = "x" }));
|
||||
|
||||
var empty = new InMemorySiteSession(null);
|
||||
await empty.UpdateAsync(new SiteSessionUpdate(claim: "x"), CancellationToken.None);
|
||||
Assert.IsNull(empty.Read(), "No session: an update creates none.");
|
||||
}
|
||||
}
|
||||
@@ -24,11 +24,12 @@ internal static class SyntheticSite
|
||||
public static int Seed => ParseSeed(Environment.GetEnvironmentVariable(Variable));
|
||||
|
||||
/// <summary>Starts the test site with the seed of this run, and says which one in the output of the test.</summary>
|
||||
public static Task<TestSite> StartAsync()
|
||||
/// <param name="time">Clock of the site (dates, signed addresses); the system clock by default.</param>
|
||||
public static Task<TestSite> StartAsync(TimeProvider? time = null)
|
||||
{
|
||||
var seed = Seed;
|
||||
Console.WriteLine($"Sito di prova con il seme {seed.ToString(CultureInfo.InvariantCulture)} (si cambia con {Variable}).");
|
||||
return TestSite.StartAsync(new TestSiteOptions { Seed = seed });
|
||||
return TestSite.StartAsync(new TestSiteOptions { Seed = seed, Time = time ?? TimeProvider.System });
|
||||
}
|
||||
|
||||
/// <summary>The seed written in <paramref name="value"/>: the default when it is empty, an error when it is not a number.</summary>
|
||||
|
||||
Reference in new issue
Block a user