Giunto per le richieste dirette, senza cambiare comportamento (#36, S1)
verifica / controlli (push) Successful in 17s
verifica / prove (push) Successful in 18m22s
verifica / installatore (push) Successful in 4m43s
verifica / immagine (push) Successful in 17m20s

Le risposte catturate dal browser e quelle che il client del sito chiederà
devono arrivare ai lettori e ai segnali nello stesso modo: la consegna passa
in ResponseDelivery (Core), che ResponseTap usa con gli stessi conteggi e
messaggi. Arrivano i contratti SiteRequest, SiteAnswer e ISiteRequester con
SiteRequestGuard (un permesso concesso, della categoria giusta, per una sola
richiesta) e RequestCatalog, che legge richieste.<sito>.json e tiene nel
codice i divieti: nomi con Mutation, chat, telemetria, /ajax/, /ws/, percorsi
con segmenti strani. Nessun doc_id nel repository; nessuna operazione di
Instagram è ancora configurata perché le forme della sonda non dicono da dove
vengano alcuni campi (tappa S4). ScriptedRequester risponde dai campioni
ripuliti per le prove. Nulla di nuovo è collegato al motore.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-16 12:59:32 +01:00
1 parent d4675a5e21
commit 76dd1b6032
15 files changed
+3488 -68

No files matched your search

@@ -0,0 +1,374 @@
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.RegularExpressions;
using Febe.Core.Abstractions;
using Febe.Core.Collection;
using Febe.Core.Collection.Requests;
namespace Febe.Tests.Collection;
/// <summary>
/// The catalog of the site client (issue #36, S1): both shipped files load, every operation is documented by a real
/// cleaned sample, and the refusals live in the code, so an edited copy in the Data folder cannot lift them.
/// </summary>
[TestClass]
public sealed partial class RequestCatalogTests
{
[TestMethod]
public void BothShippedCatalogsLoadAndAreEditableWithoutRecompiling()
{
var instagram = RequestCatalog.LoadInstagram();
var prova = RequestCatalog.LoadTestSite();
Assert.AreEqual("instagram", instagram.Site);
Assert.AreEqual("prova", prova.Site);
Assert.IsTrue(File.Exists(Path.Combine(AppContext.BaseDirectory, "config", "richieste.instagram.json")));
Assert.IsTrue(File.Exists(Path.Combine(AppContext.BaseDirectory, "config", "richieste.prova.json")));
CollectionAssert.AreEquivalent(
new[]
{
"PolarisSearchBoxRefetchableQuery", "PolarisProfilePageContentQuery", "PolarisProfilePostsQuery",
"PolarisProfileReelsTabContentQuery", "PolarisProfileTaggedTabContentQuery",
"PolarisProfileStoryHighlightsTrayContentQuery", "PolarisStoriesV3ReelPageStandaloneQuery",
"PolarisStoriesV3HighlightsPageQuery", "PolarisStoriesV3HighlightsPagePaginationQuery", "media-info",
},
instagram.Operations.Select(o => o.Name).ToArray());
// 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.
Assert.AreEqual(0, instagram.Configured.Count());
CollectionAssert.AreEquivalent(
new[] { "PolarisProfileReelsTabContentQuery", "PolarisProfileTaggedTabContentQuery", "PolarisProfileStoryHighlightsTrayContentQuery", "media-info" },
instagram.Operations.Where(o => o.NotConfiguredReason!.Contains("pending", StringComparison.Ordinal)).Select(o => o.Name).ToArray());
Assert.IsTrue(instagram.Operations.All(o => o.PendingValues.Count > 0));
Assert.IsTrue(instagram.Operations.Where(o => !o.IsConfigured).All(o => !string.IsNullOrWhiteSpace(o.NotConfiguredReason)));
Assert.IsFalse(instagram.Operations.Any(o => o.Name.Contains("Following", StringComparison.OrdinalIgnoreCase)), "No shapes with answers for the followed list yet.");
Assert.IsTrue(prova.Configured.Count() >= 8);
}
[TestMethod]
public void TheInstagramCatalogHoldsNoDocIdNorAnyLongNumber()
{
// doc_id values are read from the page modules at login (S4): the file names the source only.
var text = SiteMap.ReadEmbeddedText("richieste.instagram.json");
Assert.IsFalse(LongNumber().IsMatch(text), "No identifier, doc_id or application id in the repository.");
foreach (var operation in RequestCatalog.LoadInstagram().Operations.Where(o => o.Kind == OperationKind.GraphQl))
{
Assert.AreEqual(new ValueSource(ValueSourceKind.Session, "doc_id"), operation.Body["doc_id"]);
Assert.AreEqual(new ValueSource(ValueSourceKind.Cookie, "csrftoken"), operation.Headers["x-csrftoken"], "Decision of 16 November.");
Assert.AreEqual(new ValueSource(ValueSourceKind.Session, "user_agent"), operation.Headers["user-agent"]);
Assert.IsFalse(operation.Headers.ContainsKey("cookie"));
}
}
[TestMethod]
[DataRow("instagram")]
[DataRow("prova")]
public void EveryOperationIsDocumentedByACleanedSampleThatHasItsRootFields(string site)
{
var catalog = site == "instagram" ? RequestCatalog.LoadInstagram() : RequestCatalog.LoadTestSite();
var folder = Path.Combine(AppContext.BaseDirectory, "campioni", site);
foreach (var operation in catalog.Operations.Where(o => o.Sample is not null))
{
var file = Path.Combine(folder, operation.Sample + ".json");
Assert.IsTrue(File.Exists(file), $"{operation.Name}: manca {operation.Sample}.");
using var sample = JsonDocument.Parse(File.ReadAllText(file));
Assert.IsTrue(operation.HasRootFields(sample.RootElement.GetProperty("corpo")), $"{operation.Name}: {operation.Sample} non ha {string.Join(", ", operation.RootFields)}.");
Assert.IsTrue(operation.RootFields.Count > 0);
}
foreach (var operation in catalog.Configured)
{
Assert.IsNotNull(operation.Sample, $"{operation.Name} is configured without a sample.");
}
}
[TestMethod]
public void PathShapesNameNoValueAndValuesMustMatch()
{
var media = Get(RequestCatalog.LoadInstagram(), "media-info");
Assert.AreEqual("/api/v1/media/{numero}/info/", media.PathShape);
Assert.AreEqual(ActionKind.SinglePost, media.Category);
Assert.IsNull(media.CheckValues(SiteRequest.For("media-info", (CaseValues.MediaId, "3141592653"))));
StringAssert.Contains(media.CheckValues(new SiteRequest("media-info")), "media_id");
StringAssert.Contains(media.CheckValues(SiteRequest.For("media-info", (CaseValues.MediaId, "1"), (CaseValues.Cursor, "c"))), "cursor");
var following = Get(RequestCatalog.LoadTestSite(), "seguiti");
Assert.IsNull(following.CheckValues(new SiteRequest("seguiti")), "The cursor is optional on the first page.");
Assert.IsNull(following.CheckValues(SiteRequest.For("seguiti", (CaseValues.Cursor, "c12"))));
var reels = Get(RequestCatalog.LoadInstagram(), "PolarisProfileReelsTabContentQuery");
CollectionAssert.AreEquivalent(new[] { CaseValues.AccountId }, reels.RequiredValues.ToArray(), "From the variables template.");
Assert.AreEqual(ActionKind.BackfillPage, reels.Category);
Assert.IsTrue(reels.PendingValues.Count > 0, "Page values and the name removed by the probe wait for S4.");
}
[TestMethod]
[DataRow("PolarisStoriesV3SeenMutation")]
[DataRow("usePolarisLikeMediaXIGLikeMutation")]
[DataRow("usePolarisRegisterInRecentSearchesMutation")]
[DataRow("PolarisFollowMUTATION")]
[DataRow("SomethingMutation_subscribe")]
public void WritesAreRefusedEvenInAnEditedCopy(string name)
{
var refused = Refuse(ShippedWith(GraphQl(name)));
StringAssert.Contains(refused, name);
StringAssert.Contains(refused, "Mutation");
}
[TestMethod]
[DataRow("IGDInboxTrayQuery")]
[DataRow("IGDBadgeCountOffMsysQuery")]
[DataRow("PolarisDirectInboxQuery")]
[DataRow("IGPresenceUnifiedSetupQuery")]
[DataRow("useIGDSystemFolderUnreadThreadCountQuery")]
[DataRow("QuickPromotionSupportIGSchemaBatchFetchQuery")]
[DataRow("PolarisAPIGetFrCookieQuery")]
[DataRow("PolarisStoriesV3AdsPoolQuery")]
[DataRow("PolarisProfileDirectOrPartnershipInboxMessageEligibilityQuery")]
public void ChatInboxPresenceAndTelemetryFamiliesAreRefused(string name) =>
StringAssert.Contains(Refuse(ShippedWith(GraphQl(name))), "rifiutata");
[TestMethod]
[DataRow("/logging_client_events")]
[DataRow("/ajax/bz")]
[DataRow("/ajax/bulk-route-definitions/")]
[DataRow("/ajax/navigation/")]
[DataRow("/ajax/qualcosa/")]
[DataRow("/ws/chat/")]
[DataRow("/api/v1/web/likes/{media_id}/like/")]
[DataRow("/api/v1/discover/web/explore_grid/")]
[DataRow("https://www.facebook.com/ajax/sync/")]
[DataRow("//edge-chat.facebook.com/pull")]
[DataRow("/api/v1/media/{media_id}/info/?x=1")]
[DataRow("/{username}/{cursor}/")]
[DataRow("/AJAX/BZ")]
[DataRow("/ws")]
[DataRow("/./ajax/bz")]
[DataRow("/api/v1/./web/search/topsearch/")]
[DataRow("/api/v1//web/fxcal/")]
[DataRow("/api/v1/media/{media_id}/./info/")]
[DataRow("/api/v1/media/{media_id}/../../web/likes/")]
[DataRow("/ajax;x/bz")]
[DataRow("/api/v1/%77eb/likes/")]
[DataRow("/api/graphql")]
[DataRow("/graphql/query")]
[DataRow("/api/graphql/")]
[DataRow("/GraphQL/query")]
[DataRow("/api/v1/graphql_www")]
public void EachForbiddenPathFamilyIsRefusedEvenInAnEditedCopy(string path) =>
StringAssert.Contains(Refuse(ShippedWith(Rest("lettura-vietata", path))), "rifiutata");
[TestMethod]
public void GraphQlOnlyThroughItsTwoEntryPointsAndPlainAddressesOnlyWithGet()
{
var elsewhere = GraphQl("PolarisProfilePageContentQuery2");
elsewhere["path"] = "/api/v1/graphql";
StringAssert.Contains(Refuse(ShippedWith(elsewhere)), "/api/graphql");
var post = Rest("scrittura", "/dati/ricerche-recenti");
post["method"] = "POST";
StringAssert.Contains(Refuse(Alone(post)), "GET");
var get = GraphQl("PolarisProfilePageContentQuery2");
get["method"] = "GET";
StringAssert.Contains(Refuse(ShippedWith(get)), "POST");
}
[TestMethod]
public void UnknownKeysSourcesAndNamesAreErrors()
{
var file = JsonNode.Parse(SiteMap.ReadEmbeddedText("richieste.prova.json"))!.AsObject();
file["sconosciuta"] = 1;
StringAssert.Contains(Refuse(file.ToJsonString()), "richieste.prova.json");
var unknownKey = Rest("post2", "/dati/post/{code}");
unknownKey["doc_id"] = "123";
Refuse(Alone(unknownKey));
var unknownSource = Rest("post2", "/dati/post/{code}");
unknownSource["headers"] = new JsonObject { ["accept"] = "browser:accept" };
StringAssert.Contains(Refuse(Alone(unknownSource)), "fonte");
var unknownSession = Rest("post2", "/dati/post/{code}");
unknownSession["headers"] = new JsonObject { ["x-prova"] = "session:password" };
StringAssert.Contains(Refuse(Alone(unknownSession)), "fonte");
var cookieHeader = Rest("post2", "/dati/post/{code}");
cookieHeader["headers"] = new JsonObject { ["cookie"] = "cookie:sessionid" };
StringAssert.Contains(Refuse(Alone(cookieHeader)), "cookie");
var ownAgent = Rest("post2", "/dati/post/{code}");
ownAgent["headers"] = new JsonObject { ["user-agent"] = "constant:Febe/1.0" };
StringAssert.Contains(Refuse(Alone(ownAgent)), "user-agent");
var unknownValue = Rest("post2", "/dati/post/{password}");
StringAssert.Contains(Refuse(Alone(unknownValue)), "valore del caso");
var unknownCategory = Rest("post2", "/dati/post/{code}");
unknownCategory["category"] = "scaricati";
StringAssert.Contains(Refuse(Alone(unknownCategory)), "categoria");
var noReason = Rest("post2", "/dati/post/{code}");
noReason["configured"] = false;
StringAssert.Contains(Refuse(Alone(noReason)), "reason");
StringAssert.Contains(Refuse(ShippedWith(Get(RequestCatalog.LoadTestSite(), "post"), "prova")), "due volte");
StringAssert.Contains(Refuse("{ non è json"), "non valido");
}
[TestMethod]
[DataRow("PolarisProfileStoryHighlightsTrayContentQuery")]
[DataRow("media-info")]
public void AnOperationWithPendingHeadersOrFieldsCannotBeConfigured(string name)
{
// The variables are known, but not where every header and field takes its value: sending without them, or
// with guessed values, would not be the browser's request (rules 4 and 9).
var file = JsonNode.Parse(SiteMap.ReadEmbeddedText("richieste.instagram.json"))!.AsObject();
var operation = file["operations"]!.AsArray().Single(o => o!["name"]!.GetValue<string>() == name)!.AsObject();
operation["configured"] = true;
operation.Remove("reason");
var refused = Refuse(file.ToJsonString());
StringAssert.Contains(refused, "pending");
StringAssert.Contains(refused, "regola 9");
// The removed name alone is enough.
var removed = Rest("post2", "/dati/post/{code}");
removed["headers"] = new JsonObject { [RequestCatalog.RemovedName] = "pending" };
StringAssert.Contains(Refuse(Alone(removed)), "pending");
}
[TestMethod]
public void TheSearchBudgetIsOnlyForASearch()
{
// The search budget belongs to no session (§7.4): an edited copy cannot move stories or a post there.
var stories = Rest("storie2", "/dati/storie/{username}");
stories["category"] = "ricerca";
StringAssert.Contains(Refuse(Alone(stories)), "ricerca");
var searchWithAccount = Rest("cerca2", "/dati/cerca/{username}");
searchWithAccount["category"] = "ricerca";
searchWithAccount["parameters"] = new JsonObject { ["testo"] = "{search_text}" };
StringAssert.Contains(Refuse(Alone(searchWithAccount)), "ricerca");
// And a search counts nowhere else.
var searchAsPost = Rest("cerca3", "/dati/cerca");
searchAsPost["parameters"] = new JsonObject { ["testo"] = "{search_text}" };
StringAssert.Contains(Refuse(Alone(searchAsPost)), "ricerca");
Assert.AreEqual(ActionKind.ProfileSearch, Get(RequestCatalog.LoadInstagram(), "PolarisSearchBoxRefetchableQuery").Category);
Assert.AreEqual(ActionKind.ProfileSearch, Get(RequestCatalog.LoadTestSite(), "cerca").Category);
}
[TestMethod]
public void AValueThatWouldChangeThePathIsRefusedBeforeItLeaves()
{
// A cursor may hold «/» (it is opaque), but not in a segment of the path, where it would become two.
var catalog = RequestCatalog.Parse(Alone(Rest("pagina", "/dati/pagine/{cursor}")), "richieste.prova.json");
var page = Get(catalog, "pagina");
CollectionAssert.AreEquivalent(new[] { CaseValues.Cursor }, page.PathValues.ToArray());
Assert.IsNull(page.CheckValues(SiteRequest.For("pagina", (CaseValues.Cursor, "QVFCabc"))));
foreach (var value in new[] { "a/b", "a?b", "a#b", "a%2Fb", "...", "a b" })
{
var problem = page.CheckValues(SiteRequest.For("pagina", (CaseValues.Cursor, value)));
Assert.IsNotNull(problem, value);
StringAssert.Contains(problem, "percorso");
Assert.IsFalse(problem.Contains(value, StringComparison.Ordinal), "Never the value (rule 10).");
}
}
[TestMethod]
public void AnOperationWithRemovedNamesInItsVariablesCannotBeConfigured()
{
var text = SiteMap.ReadEmbeddedText("richieste.instagram.json");
var file = JsonNode.Parse(text)!.AsObject();
var page = file["operations"]!.AsArray().Single(o => o!["name"]!.GetValue<string>() == "PolarisProfilePageContentQuery")!.AsObject();
page["configured"] = true;
page.Remove("reason");
StringAssert.Contains(Refuse(file.ToJsonString()), "regola 9");
}
[TestMethod]
public void AnEditedCopyInTheDataFolderWinsButKeepsTheRefusals()
{
var folder = Path.Combine(Path.GetTempPath(), "febe-richieste-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(folder);
try
{
var path = Path.Combine(folder, "richieste.prova.json");
var file = JsonNode.Parse(SiteMap.ReadEmbeddedText("richieste.prova.json"))!.AsObject();
file["operations"]!.AsArray().RemoveAt(0);
File.WriteAllText(path, file.ToJsonString());
var copy = RequestCatalog.LoadOrEmbedded(path, "richieste.prova.json");
Assert.AreEqual(path, copy.Source);
Assert.IsFalse(copy.TryGet("inizio", out _));
Assert.IsTrue(RequestCatalog.LoadOrEmbedded(Path.Combine(folder, "manca.json"), "richieste.prova.json").TryGet("inizio", out _));
file["operations"]!.AsArray().Add(Rest("telemetria", "/logging_client_events"));
File.WriteAllText(path, file.ToJsonString());
var refused = Assert.ThrowsExactly<InvalidDataException>(() => RequestCatalog.LoadOrEmbedded(path, "richieste.prova.json"));
StringAssert.Contains(refused.Message, path);
}
finally
{
Directory.Delete(folder, recursive: true);
}
}
private static SiteOperation Get(RequestCatalog catalog, string name) =>
catalog.TryGet(name, out var operation) ? operation : throw new AssertFailedException($"«{name}» non è nel catalogo.");
private static string Refuse(string json) =>
Assert.ThrowsExactly<InvalidDataException>(() => RequestCatalog.Parse(json, "richieste.prova.json")).Message;
/// <summary>The shipped Instagram (or test site) catalog with one more operation, as an edited copy would be.</summary>
private static string ShippedWith(JsonObject operation, string site = "instagram")
{
var file = JsonNode.Parse(SiteMap.ReadEmbeddedText($"richieste.{site}.json"))!.AsObject();
file["operations"]!.AsArray().Add(operation);
return file.ToJsonString();
}
/// <summary>The shipped catalog with the operation as JSON again (used to add it twice).</summary>
private static string ShippedWith(SiteOperation existing, string site)
{
var file = JsonNode.Parse(SiteMap.ReadEmbeddedText($"richieste.{site}.json"))!.AsObject();
var copy = file["operations"]!.AsArray().Single(o => o!["name"]!.GetValue<string>() == existing.Name)!.DeepClone();
file["operations"]!.AsArray().Add(copy);
return file.ToJsonString();
}
private static string Alone(JsonObject operation) =>
new JsonObject { ["site"] = "prova", ["operations"] = new JsonArray(operation) }.ToJsonString();
private static JsonObject Rest(string name, string path) => new()
{
["name"] = name,
["kind"] = "rest",
["method"] = "GET",
["path"] = path,
["category"] = "post",
["configured"] = true,
["rootFields"] = new JsonArray("contenuto"),
["sample"] = "000005-post-serie",
};
private static JsonObject GraphQl(string name) => new()
{
["name"] = name,
["kind"] = "graphql",
["method"] = "POST",
["path"] = "/api/graphql",
["category"] = "profilo",
["configured"] = true,
["headers"] = new JsonObject { ["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"),
["sample"] = "000009-scheda-profilo",
};
[GeneratedRegex("[0-9]{10,}")]
private static partial Regex LongNumber();
}
@@ -0,0 +1,248 @@
using System.Collections.Concurrent;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using Febe.Browser.Capture;
using Febe.Browser.Diagnostics;
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.Tests.Browser.TestSupport;
using Febe.Tests.Collection.Support;
using Febe.Tests.Support;
namespace Febe.Tests.Collection;
/// <summary>
/// The delivery of answers to the readers, shared by the response tap and the site client (issue #36, S1): a cleaned
/// real sample reaches <see cref="CaptureCollector"/> the same whether the browser captured it or the site client asked
/// for it.
/// </summary>
[TestClass]
public sealed class ResponseDeliveryTests
{
private static readonly HostClassifier Hosts = new(["127.0.0.1:5000"], ["127.0.0.1:5001"]);
[TestMethod]
[DataRow("000002-ricerca-profili")]
[DataRow("000005-post-video")]
[DataRow("000006-raccolta-in-evidenza")]
[DataRow("000007-raccolta-pagina-successiva")]
[DataRow("000009-scheda-profilo")]
[DataRow("000010-post-del-profilo")]
[DataRow("000011-reel-del-profilo")]
[DataRow("000012-con-tag")]
[DataRow("000013-raccolte-del-profilo")]
[DataRow("000014-storie-di-un-profilo")]
[DataRow("000015-vassoio-storie")]
[DataRow("000016-serie-con-video")]
public async Task ASampleReachesTheReadersAsThroughTheCapture(string sample)
{
var (mime, resource, body) = Sample(sample);
var isDocument = resource == "Document";
var text = isDocument
? $"""<!DOCTYPE html><html><head><script type="application/json">{body}</script></head><body></body></html>"""
: body;
// Through the browser: the tap fetches the body and hands it on.
var clock = new VirtualClock();
var cdp = new FakeCdpSession(clock);
cdp.Responder = (method, p) => method switch
{
"Page.getFrameTree" => new JsonObject { ["frameTree"] = new JsonObject { ["frame"] = new JsonObject { ["id"] = "F1", ["url"] = "about:blank" } } },
"Network.getResponseBody" when p!["requestId"]!.GetValue<string>() == "r1" => new JsonObject { ["body"] = text, ["base64Encoded"] = false },
"Network.getResponseBody" => new JsonObject { ["body"] = """{"fine":1}""", ["base64Encoded"] = false },
_ => null,
};
var captured = new CaptureCollector(new ShapeReader(ReaderVocabulary.LoadInstagram()), clock);
var seen = new RecordingConsumer();
await using (var tap = new ResponseTap(cdp, Hosts, clock))
{
tap.AddConsumer(captured);
tap.AddObserver(captured);
tap.AddConsumer(seen);
await tap.StartAsync();
cdp.Raise("Network.responseReceived", isDocument ? Document("r1") : Received("r1", mime));
cdp.Raise("Network.loadingFinished", new JsonObject { ["requestId"] = "r1", ["encodedDataLength"] = text.Length });
cdp.Raise("Network.responseReceived", Received("fine", "application/json"));
cdp.Raise("Network.loadingFinished", new JsonObject { ["requestId"] = "fine", ["encodedDataLength"] = 10 });
await TestWait.UntilAsync(() => seen.Items.Any(i => i.RequestId == "fine"), "risposta di chiusura");
}
// Through the delivery alone, as the site client hands its answers on, with the same descriptor.
var descriptor = seen.Items.First(i => i.RequestId == "r1");
var requested = new CaptureCollector(new ShapeReader(ReaderVocabulary.LoadInstagram()), clock);
var delivery = new ResponseDelivery("Client del sito");
var bytes = Encoding.UTF8.GetBytes(text);
var delivered = isDocument
? await delivery.DeliverDocumentAsync(descriptor, bytes, [requested], CancellationToken.None)
: await delivery.DeliverBodyAsync(descriptor, bytes, [requested], CancellationToken.None);
Assert.AreEqual(1, delivered);
Assert.AreEqual(1, delivery.JsonBodies);
Assert.AreEqual(0, delivery.ParseErrors);
Assert.IsTrue(Read(captured) > 0, $"{sample}: the readers keep nothing of it, so the comparison would prove nothing.");
Assert.AreEqual(Read(captured), Read(requested), sample);
Assert.AreEqual(Describe(captured), Describe(requested), sample);
}
[TestMethod]
public async Task AnAnswerAskedByTheSiteClientReachesTheReadersLikeTheSample()
{
var catalog = SettledCatalog.Instagram();
var requester = new ScriptedRequester(catalog);
var answer = await requester.SendAsync(
SiteRequest.For("PolarisProfileStoryHighlightsTrayContentQuery", (CaseValues.AccountId, "4815162342")),
Permit.Grant(ActionKind.ProfileOpen, 7),
CancellationToken.None);
var clock = new VirtualClock();
var collector = new CaptureCollector(new ShapeReader(ReaderVocabulary.LoadInstagram()), clock);
var descriptor = new ResponseDescriptor("richiesta-1", HostKind.Site, "https://www.instagram.com" + answer.PathShape, "www.instagram.com", answer.PathShape, answer.Status, answer.MimeType, "Fetch", false, clock.Now);
var delivered = await new ResponseDelivery("Client del sito").DeliverBodyAsync(descriptor, answer.Body, [collector], CancellationToken.None);
Assert.AreEqual(1, delivered);
var read = collector.Since(0).Single();
Assert.AreEqual(3, read.Result.Highlights.Count, "The three collections of the sample.");
using var document = JsonDocument.Parse(answer.Body);
Assert.IsTrue(catalog.Configured.Single(o => o.Name == answer.Operation).HasRootFields(document.RootElement));
}
[TestMethod]
public async Task NotJsonAndDocumentsWithoutBlocksDeliverNothing()
{
var consumer = new RecordingConsumer();
var delivery = new ResponseDelivery("Client del sito");
var descriptor = Descriptor("text/javascript");
Assert.AreEqual(0, await delivery.DeliverBodyAsync(descriptor, Encoding.UTF8.GetBytes("for (;;);{\"a\":1}"), [consumer], CancellationToken.None));
Assert.AreEqual(0, await delivery.DeliverBodyAsync(descriptor, Encoding.UTF8.GetBytes(new string('[', 300) + new string(']', 300)), [consumer], CancellationToken.None), "Deeper than 256.");
Assert.AreEqual(0, await delivery.DeliverDocumentAsync(Descriptor("text/html"), Encoding.UTF8.GetBytes("<html><body>niente</body></html>"), [consumer], CancellationToken.None));
Assert.AreEqual(2, delivery.ParseErrors, "A document without blocks is not a parse error.");
Assert.AreEqual(0, delivery.JsonBodies);
Assert.IsTrue(consumer.Items.IsEmpty);
}
[TestMethod]
public async Task AFailingReaderStopsNeitherTheOthersNorTheNextBlockAndIsWarnedWithoutContents()
{
var warnings = new ConcurrentQueue<(string Message, Exception? Error)>();
var delivery = new ResponseDelivery("Client del sito", (message, error) => warnings.Enqueue((message, error)));
var failing = new FailingConsumer();
var consumer = new RecordingConsumer();
var html = """<html><script type="application/json">{"segreto":"a"}</script><script type="application/json">{"segreto":"b"}</script></html>""";
var delivered = await delivery.DeliverDocumentAsync(Descriptor("text/html"), Encoding.UTF8.GetBytes(html), [failing, consumer], CancellationToken.None);
Assert.AreEqual(2, delivered);
Assert.AreEqual(2, consumer.Items.Count);
Assert.AreEqual(2, failing.Calls);
Assert.AreEqual(2, warnings.Count);
Assert.IsTrue(warnings.All(w => w.Message == "Client del sito: errore in un lettore (FailingConsumer)."));
Assert.IsFalse(warnings.Any(w => w.Message.Contains("segreto", StringComparison.Ordinal)));
}
[TestMethod]
public async Task TheTapKeepsItsStatsAndItsMessagesWithTheSharedDelivery()
{
var clock = new VirtualClock();
var cdp = new FakeCdpSession(clock);
cdp.Responder = (method, p) => method switch
{
"Page.getFrameTree" => new JsonObject { ["frameTree"] = new JsonObject { ["frame"] = new JsonObject { ["id"] = "F1", ["url"] = "about:blank" } } },
"Network.getResponseBody" when p!["requestId"]!.GetValue<string>() == "bad64" => new JsonObject { ["body"] = "%%%", ["base64Encoded"] = true },
"Network.getResponseBody" when p!["requestId"]!.GetValue<string>() == "nojson" => new JsonObject { ["body"] = "for (;;);", ["base64Encoded"] = false },
"Network.getResponseBody" => new JsonObject { ["body"] = """{"a":1}""", ["base64Encoded"] = false },
_ => null,
};
var messages = new ConcurrentQueue<string>();
var log = new DelegateBrowserLog((_, message, _) => messages.Enqueue(message));
var seen = new RecordingConsumer();
await using var tap = new ResponseTap(cdp, Hosts, clock, log);
tap.AddConsumer(new FailingConsumer());
tap.AddConsumer(seen);
await tap.StartAsync();
foreach (var id in new[] { "bad64", "nojson", "ok" })
{
cdp.Raise("Network.responseReceived", Received(id, "application/json"));
cdp.Raise("Network.loadingFinished", new JsonObject { ["requestId"] = id, ["encodedDataLength"] = 10 });
}
await TestWait.UntilAsync(() => seen.Items.Any(i => i.RequestId == "ok"), "risposta valida");
var stats = tap.Stats;
Assert.AreEqual(3, stats.Responses);
Assert.AreEqual(1, stats.JsonBodies);
Assert.AreEqual(2, stats.ParseErrors, "A base64 body that does not decode and a body that is not JSON, as before.");
Assert.AreEqual(0, stats.BodyErrors);
Assert.IsTrue(messages.Contains("Cattura: errore in un lettore (FailingConsumer)."), "The tap's message is unchanged.");
}
/// <summary>Reads of the sample's answer the collector kept (unrelated answers are not kept), search ones included.</summary>
private static int Read(CaptureCollector collector) =>
collector.Since(0).Count(r => r.Response.RequestId == "r1") + collector.SearchSince(default).Count(r => r.Response.RequestId == "r1");
private static string Describe(CaptureCollector collector)
{
var options = new JsonSerializerOptions { WriteIndented = false };
// Only the sample's answer: the closing answer of the capture run is not part of the comparison.
var reads = JsonSerializer.Serialize(collector.Since(0).Where(r => r.Response.RequestId == "r1").Select(r => new { r.Response, r.Result }), options);
var search = JsonSerializer.Serialize(collector.SearchSince(default).Where(r => r.Response.RequestId == "r1").Select(r => new { r.Response, r.Result }), options);
return reads + search;
}
private static (string Mime, string Resource, string Body) Sample(string name)
{
var file = Path.Combine(AppContext.BaseDirectory, "campioni", "instagram", name + ".json");
using var sample = JsonDocument.Parse(File.ReadAllText(file));
var descriptor = sample.RootElement.GetProperty("descrittore");
return (descriptor.GetProperty("tipo").GetString()!, descriptor.GetProperty("risorsa").GetString()!, sample.RootElement.GetProperty("corpo").GetRawText());
}
private static ResponseDescriptor Descriptor(string mime) =>
new("r1", HostKind.Site, "http://127.0.0.1:5000/api/graphql", "127.0.0.1:5000", "/api/graphql", 200, mime, "Fetch", false, DateTimeOffset.UnixEpoch);
private static JsonObject Received(string id, string mime) => new()
{
["requestId"] = id,
["loaderId"] = "L1",
["frameId"] = "F1",
["type"] = "XHR",
["response"] = new JsonObject { ["url"] = "http://127.0.0.1:5000/api/graphql", ["status"] = 200, ["mimeType"] = mime },
};
private static JsonObject Document(string id) => new()
{
["requestId"] = id,
["loaderId"] = id,
["frameId"] = "F1",
["type"] = "Document",
["response"] = new JsonObject { ["url"] = "http://127.0.0.1:5000/", ["status"] = 200, ["mimeType"] = "text/html; charset=utf-8" },
};
private sealed class RecordingConsumer : IResponseConsumer
{
public ConcurrentQueue<ResponseDescriptor> Items { get; } = new();
public ValueTask ConsumeAsync(ResponseDescriptor response, JsonDocument body, CancellationToken ct)
{
Items.Enqueue(response);
return ValueTask.CompletedTask;
}
}
private sealed class FailingConsumer : IResponseConsumer
{
private int _calls;
public int Calls => Volatile.Read(ref _calls);
public ValueTask ConsumeAsync(ResponseDescriptor response, JsonDocument body, CancellationToken ct)
{
Interlocked.Increment(ref _calls);
throw new InvalidOperationException("Lettore di prova che fallisce sempre.");
}
}
}
@@ -0,0 +1,228 @@
using System.Text;
using System.Text.Json;
using Febe.Core.Abstractions;
using Febe.Core.Collection.Requests;
using Febe.Tests.Collection.Support;
namespace Febe.Tests.Collection;
/// <summary>
/// The contract of the site client (issue #36, S1) on its test double: no request without a permit the Governor
/// granted for it (rule 8), only operations of the catalog, and answers that carry the stop cases of §7.6 without ever
/// showing a body, a cookie or a value in their text (rule 10).
/// </summary>
[TestClass]
public sealed class SiteRequesterTests
{
private static readonly SiteRequest Tray = SiteRequest.For("PolarisProfileStoryHighlightsTrayContentQuery", (CaseValues.AccountId, "4815162342"));
[TestMethod]
public async Task NothingLeavesWithoutAGrantedPermit()
{
var requester = new ScriptedRequester(SettledCatalog.Instagram());
var denied = Permit.Deny(ActionKind.ProfileOpen, 7, DenialReason.HourlyBudgetReached, "Tetto orario raggiunto.");
var refused = await Assert.ThrowsExactlyAsync<SiteRequestRefusedException>(() => requester.SendAsync(Tray, denied, CancellationToken.None));
StringAssert.Contains(refused.Message, "permesso");
await Assert.ThrowsExactlyAsync<SiteRequestRefusedException>(() => requester.SendAsync(Tray, null!, CancellationToken.None));
Assert.AreEqual(2, requester.Refused);
Assert.AreEqual(0, requester.Sent.Count);
}
[TestMethod]
public async Task APermitOfAnotherCategoryOrARequestOutsideTheCatalogIsRefused()
{
var requester = new ScriptedRequester(SettledCatalog.Instagram());
// A permit for one category never covers a request of another (§7.4: a permit per request, in its category).
var other = await Assert.ThrowsExactlyAsync<SiteRequestRefusedException>(() => requester.SendAsync(Tray, Permit.Grant(ActionKind.StoryView, 7), CancellationToken.None));
StringAssert.Contains(other.Message, "ProfileOpen");
await Assert.ThrowsExactlyAsync<SiteRequestRefusedException>(() =>
requester.SendAsync(new SiteRequest("PolarisStoriesV3SeenMutation"), Permit.Grant(ActionKind.StoryView, 7), CancellationToken.None));
var notConfigured = await Assert.ThrowsExactlyAsync<SiteRequestRefusedException>(() =>
requester.SendAsync(SiteRequest.For("PolarisProfilePageContentQuery", (CaseValues.AccountId, "1")), Permit.Grant(ActionKind.ProfileOpen, 7), CancellationToken.None));
StringAssert.Contains(notConfigured.Message, "non è configurata");
await Assert.ThrowsExactlyAsync<SiteRequestRefusedException>(() =>
requester.SendAsync(SiteRequest.For("PolarisProfileStoryHighlightsTrayContentQuery", (CaseValues.Username, "marta")), Permit.Grant(ActionKind.ProfileOpen, 7), CancellationToken.None));
Assert.AreEqual(4, requester.Refused);
Assert.AreEqual(0, requester.Sent.Count);
Assert.ThrowsExactly<ArgumentException>(() => SiteRequest.For("media-info", ("x-csrftoken", "valore")), "A request carries no header.");
}
[TestMethod]
public async Task AnOperationWithHeadersOrFieldsStillPendingNeverLeaves()
{
// The shipped file: the variables of the tray are known, but not where __dyn, referer, sec-ch-ua... come from.
var shipped = RequestCatalog.LoadInstagram();
Assert.IsTrue(shipped.TryGet(Tray.Operation, out var tray));
Assert.IsFalse(tray.IsConfigured);
Assert.IsTrue(tray.PendingValues.Count > 0);
var requester = new ScriptedRequester(shipped);
var refused = await Assert.ThrowsExactlyAsync<SiteRequestRefusedException>(() => requester.SendAsync(Tray, Permit.Grant(ActionKind.ProfileOpen, 7), CancellationToken.None));
StringAssert.Contains(refused.Message, "pending");
Assert.AreEqual(0, requester.Sent.Count);
}
[TestMethod]
public async Task APermitServesOneRequestOnly()
{
var requester = new ScriptedRequester(SettledCatalog.Instagram());
var permit = Permit.Grant(ActionKind.ProfileOpen, 7);
await requester.SendAsync(Tray, permit, CancellationToken.None);
var again = await Assert.ThrowsExactlyAsync<SiteRequestRefusedException>(() => requester.SendAsync(Tray, permit, CancellationToken.None));
StringAssert.Contains(again.Message, "già stato usato");
// Equal fields, another grant: a new permit (by reference, not by value).
await requester.SendAsync(Tray, Permit.Grant(ActionKind.ProfileOpen, 7), CancellationToken.None);
// A permit shown with a refused request is spent too: the Governor has already counted it.
var spent = Permit.Grant(ActionKind.ProfileOpen, 7);
await Assert.ThrowsExactlyAsync<SiteRequestRefusedException>(() =>
requester.SendAsync(SiteRequest.For(Tray.Operation, (CaseValues.Username, "marta")), spent, CancellationToken.None));
await Assert.ThrowsExactlyAsync<SiteRequestRefusedException>(() => requester.SendAsync(Tray, spent, CancellationToken.None));
Assert.AreEqual(2, requester.Sent.Count);
Assert.AreEqual(3, requester.Refused);
}
[TestMethod]
[DataRow(CaseValues.MediaId, "1/../../web/likes/2/like")]
[DataRow(CaseValues.MediaId, "12a")]
[DataRow(CaseValues.AccountId, "..")]
[DataRow(CaseValues.Username, "..")]
[DataRow(CaseValues.Username, "marta/../ajax")]
[DataRow(CaseValues.Username, "marta?x=1")]
[DataRow(CaseValues.Code, "Ab#c")]
[DataRow(CaseValues.HighlightId, "highlight:1/2")]
[DataRow(CaseValues.Cursor, "riga\nnuova")]
public void AValueWithoutItsFormCannotBeAsked(string name, string value)
{
var refused = Assert.ThrowsExactly<ArgumentException>(() => SiteRequest.For("media-info", (name, value)));
StringAssert.Contains(refused.Message, name);
Assert.IsFalse(refused.Message.Contains(value, StringComparison.Ordinal), "Never the value in the message (rule 10).");
}
[TestMethod]
public void TheFormsOfTheSitesValuesAreAccepted()
{
Assert.IsTrue(CaseValues.HasForm(CaseValues.AccountId, "4815162342"));
Assert.IsTrue(CaseValues.HasForm(CaseValues.Username, "marta.prova"));
Assert.IsTrue(CaseValues.HasForm(CaseValues.Username, "_marta_"));
Assert.IsTrue(CaseValues.HasForm(CaseValues.Code, "DAbc-12_x"));
Assert.IsTrue(CaseValues.HasForm(CaseValues.HighlightId, "highlight:17890123"));
Assert.IsTrue(CaseValues.HasForm(CaseValues.Cursor, "QVFC/cursore+=="));
Assert.IsTrue(CaseValues.HasForm(CaseValues.SearchText, "marta prova #estate"));
}
[TestMethod]
[DataRow("instagram")]
[DataRow("prova")]
public async Task EveryConfiguredOperationIsAnsweredFromItsSample(string site)
{
// Instagram as tappa S4 will leave it: the shipped file has no configured operation yet.
var catalog = site == "instagram" ? SettledCatalog.Instagram() : RequestCatalog.LoadTestSite();
var requester = new ScriptedRequester(catalog);
Assert.IsTrue(catalog.Configured.Any());
foreach (var operation in catalog.Configured)
{
var request = new SiteRequest(operation.Name, operation.RequiredValues.ToDictionary(v => v, v => v == CaseValues.AccountId || v == CaseValues.MediaId ? "31415" : "valore", StringComparer.Ordinal));
var answer = await requester.SendAsync(request, Permit.Grant(operation.Category, null), CancellationToken.None);
Assert.AreEqual(200, answer.Status, operation.Name);
Assert.IsTrue(answer.IsDeclaredData, operation.Name);
Assert.AreEqual(operation.PathShape, answer.PathShape);
using var body = JsonDocument.Parse(answer.Body);
Assert.IsTrue(operation.HasRootFields(body.RootElement), operation.Name);
}
Assert.AreEqual(catalog.Configured.Count(), requester.Sent.Count);
}
[TestMethod]
public async Task TheStopCasesOfSection76CanBeScripted()
{
var catalog = SettledCatalog.Instagram();
var tray = catalog.Configured.Single(o => o.Name == Tray.Operation);
var requester = new ScriptedRequester(catalog).Then(
ScriptedReply.TooManyRequests,
ScriptedReply.RedirectToLogin,
ScriptedReply.RedirectToChallenge,
ScriptedReply.HtmlInsteadOfJson,
ScriptedReply.MissingRootField,
ScriptedReply.SessionCookieDeleted);
// A new permit for every request (§7.4).
static Permit Granted() => Permit.Grant(ActionKind.ProfileOpen, 7);
var slow = await requester.SendAsync(Tray, Granted(), CancellationToken.None);
Assert.AreEqual(429, slow.Status);
var login = await requester.SendAsync(Tray, Granted(), CancellationToken.None);
Assert.IsTrue(login.IsRedirect);
Assert.AreEqual("/accounts/login/", login.RedirectPathShape, "Only the shape of the path: no host, no query string.");
var challenge = await requester.SendAsync(Tray, Granted(), CancellationToken.None);
Assert.AreEqual("/challenge/{testo}/", challenge.RedirectPathShape);
var html = await requester.SendAsync(Tray, Granted(), CancellationToken.None);
Assert.IsTrue(html.IsHtml);
Assert.IsFalse(html.IsDeclaredData);
Assert.AreEqual("text/html", html.MimeType);
var missing = await requester.SendAsync(Tray, Granted(), CancellationToken.None);
using (var body = JsonDocument.Parse(missing.Body))
{
Assert.IsFalse(tray.HasRootFields(body.RootElement), "JSON without the expected field: stop and warn (§6.0).");
}
var deleted = await requester.SendAsync(Tray, Granted(), CancellationToken.None);
Assert.IsTrue(deleted.Deletes("sessionid"));
var again = await requester.SendAsync(Tray, Granted(), CancellationToken.None);
Assert.AreEqual(200, again.Status, "After the script, the sample again.");
Assert.AreEqual(7, requester.Sent.Count);
}
[TestMethod]
public void TheTextOfAnswersAndRequestsShowsNoBodyCookieOrValue()
{
Assert.IsTrue(RequestCatalog.LoadInstagram().TryGet("media-info", out var media));
var answer = new SiteAnswer(
media,
302,
"application/json; charset=utf-8",
Encoding.UTF8.GetBytes("""{"segreto":"corpo-riservato"}"""),
redirectTo: "https://www.instagram.com/challenge/Ab12Cd/?next=%2Fmarta.prova%2F&token=xyz",
cookiesSet: ["csrftoken", "rur"],
cookiesDeleted: ["sessionid"],
setsClaim: true,
retryAfter: TimeSpan.FromMinutes(5));
var text = answer.ToString();
foreach (var leak in new[] { "segreto", "corpo-riservato", "csrftoken", "rur", "sessionid", "Ab12Cd", "marta", "token", "xyz", "next", "instagram.com" })
{
Assert.IsFalse(text.Contains(leak, StringComparison.OrdinalIgnoreCase), $"«{leak}» in «{text}».");
}
StringAssert.Contains(text, "media-info");
StringAssert.Contains(text, "/api/v1/media/{numero}/info/");
StringAssert.Contains(text, "302");
StringAssert.Contains(text, "/challenge/{testo}/");
// The path shown is always the catalog's shape: an answer cannot be given the path with its values.
var plain = new SiteAnswer(media, 200, "application/json", ReadOnlyMemory<byte>.Empty);
Assert.AreEqual("/api/v1/media/{numero}/info/", plain.PathShape);
Assert.AreEqual("media-info", plain.Operation);
var request = SiteRequest.For("PolarisProfilePostsQuery", (CaseValues.Username, "marta.prova"), (CaseValues.Cursor, "QVFCcursore"));
Assert.IsFalse(request.ToString().Contains("marta", StringComparison.Ordinal));
Assert.IsFalse(request.ToString().Contains("QVFC", StringComparison.Ordinal));
StringAssert.Contains(request.ToString(), "username");
Assert.ThrowsExactly<ArgumentException>(() => new SiteAnswer(media, 200, "text/html", ReadOnlyMemory<byte>.Empty, cookiesSet: ["sessionid=abc"]));
}
}
@@ -0,0 +1,166 @@
using System.Collections.Concurrent;
using System.Text;
using System.Text.Json.Nodes;
using Febe.Core.Abstractions;
using Febe.Core.Collection.Requests;
namespace Febe.Tests.Collection.Support;
/// <summary>What <see cref="ScriptedRequester"/> answers to the next request, instead of the sample.</summary>
public enum ScriptedReply
{
/// <summary>The cleaned sample of the operation (<see cref="SiteOperation.Sample"/>).</summary>
Sample,
/// <summary>A 429 without body (§7.6, Rallentamento).</summary>
TooManyRequests,
/// <summary>A 302 to the login page of the site, never followed.</summary>
RedirectToLogin,
/// <summary>A 302 to the challenge page of the site, never followed.</summary>
RedirectToChallenge,
/// <summary>A 200 with an HTML page where the catalog expects JSON.</summary>
HtmlInsteadOfJson,
/// <summary>The sample without its expected root field (the last one of <see cref="SiteOperation.RootFields"/>).</summary>
MissingRootField,
/// <summary>The sample, with the session cookie deleted by the site.</summary>
SessionCookieDeleted,
}
/// <summary>
/// The site client of the tests (issue #36): answers the requests of the catalog from the cleaned samples of
/// <c>tests/Febe.Tests/campioni/&lt;sito&gt;</c>, by operation name, and can be scripted to answer the stop cases of
/// §7.6. It honours the <see cref="ISiteRequester"/> contract: <see cref="SiteRequestGuard"/> before anything (a permit
/// used once is spent, <see cref="SpentPermits"/>), and one request at a time. Nothing leaves the process.
/// </summary>
public sealed class ScriptedRequester : ISiteRequester
{
private readonly RequestCatalog _catalog;
private readonly string _samples;
private readonly ConcurrentQueue<ScriptedReply> _script = new();
private readonly ConcurrentQueue<SiteRequest> _sent = new();
private readonly SpentPermits _spent = new();
private int _busy;
private int _refused;
/// <param name="catalog">The catalog the requests are checked against.</param>
/// <param name="sampleFolder">Folder of the cleaned samples; by default <c>campioni/&lt;site of the catalog&gt;</c> next to the tests.</param>
public ScriptedRequester(RequestCatalog catalog, string? sampleFolder = null)
{
_catalog = catalog ?? throw new ArgumentNullException(nameof(catalog));
_samples = sampleFolder ?? Path.Combine(AppContext.BaseDirectory, "campioni", catalog.Site);
}
/// <summary>Path of the login page a redirect points to.</summary>
public string LoginLocation { get; init; } = "https://www.instagram.com/accounts/login/?next=%2F";
/// <summary>Path of the challenge page a redirect points to.</summary>
public string ChallengeLocation { get; init; } = "/challenge/AbCdEf123/?next=%2F";
/// <summary>Name of the session cookie (<see cref="ScriptedReply.SessionCookieDeleted"/>).</summary>
public string SessionCookie { get; init; } = "sessionid";
/// <summary>Requests that passed the guard, in order.</summary>
public IReadOnlyList<SiteRequest> Sent => [.. _sent];
/// <summary>Requests refused before anything was answered.</summary>
public int Refused => Volatile.Read(ref _refused);
/// <summary>The replies of the next requests, in order; after them, the samples again.</summary>
public ScriptedRequester Then(params ScriptedReply[] replies)
{
foreach (var reply in replies)
{
_script.Enqueue(reply);
}
return this;
}
public async Task<SiteAnswer> SendAsync(SiteRequest request, Permit permit, CancellationToken ct)
{
SiteOperation operation;
try
{
operation = SiteRequestGuard.Check(_catalog, request, permit, _spent);
}
catch (SiteRequestRefusedException)
{
Interlocked.Increment(ref _refused);
throw;
}
if (Interlocked.Exchange(ref _busy, 1) == 1)
{
Interlocked.Increment(ref _refused);
throw new SiteRequestRefusedException($"Richiesta «{request.Operation}» non inviata: un'altra richiesta è ancora in corso (una per volta).");
}
try
{
ct.ThrowIfCancellationRequested();
await Task.Yield();
_sent.Enqueue(request);
var reply = _script.TryDequeue(out var next) ? next : ScriptedReply.Sample;
return Answer(operation, reply);
}
finally
{
Volatile.Write(ref _busy, 0);
}
}
/// <summary>The descriptor and the body of the sample of <paramref name="operation"/>.</summary>
public (string MimeType, JsonNode Body) Sample(SiteOperation operation)
{
ArgumentNullException.ThrowIfNull(operation);
if (operation.Sample is not { } name)
{
throw new InvalidOperationException($"«{operation.Name}» non ha un campione.");
}
var file = Directory.EnumerateFiles(_samples, $"{name}.json").Single();
var sample = JsonNode.Parse(File.ReadAllText(file))!;
return (sample["descrittore"]!["tipo"]!.GetValue<string>(), sample["corpo"]!.DeepClone());
}
private SiteAnswer Answer(SiteOperation operation, ScriptedReply reply)
{
switch (reply)
{
case ScriptedReply.TooManyRequests:
return new SiteAnswer(operation, 429, "text/plain", ReadOnlyMemory<byte>.Empty);
case ScriptedReply.RedirectToLogin:
return new SiteAnswer(operation, 302, "text/html", ReadOnlyMemory<byte>.Empty, redirectTo: LoginLocation);
case ScriptedReply.RedirectToChallenge:
return new SiteAnswer(operation, 302, "text/html", ReadOnlyMemory<byte>.Empty, redirectTo: ChallengeLocation);
case ScriptedReply.HtmlInsteadOfJson:
return new SiteAnswer(operation, 200, "text/html; charset=utf-8", Encoding.UTF8.GetBytes("<!DOCTYPE html><html><head><title>Pagina</title></head><body></body></html>"));
}
var (mime, body) = Sample(operation);
if (reply == ScriptedReply.MissingRootField)
{
var parts = operation.RootFields[^1].Split('.');
var parent = body;
foreach (var part in parts[..^1])
{
parent = parent[part]!;
}
parent.AsObject().Remove(parts[^1]);
}
var bytes = Encoding.UTF8.GetBytes(body.ToJsonString());
return new SiteAnswer(
operation,
200,
mime,
bytes,
cookiesDeleted: reply == ScriptedReply.SessionCookieDeleted ? [SessionCookie] : null);
}
}
@@ -0,0 +1,50 @@
using System.Text.Json.Nodes;
using Febe.Core.Collection;
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).
/// </summary>
public static class SettledCatalog
{
/// <summary>The operations whose variables the shapes show whole (only the headers and fields wait for S4).</summary>
public static IReadOnlyList<string> KnownVariables { get; } =
[
"PolarisProfileReelsTabContentQuery", "PolarisProfileTaggedTabContentQuery",
"PolarisProfileStoryHighlightsTrayContentQuery", "media-info",
];
/// <summary>The Instagram catalog with <paramref name="names"/> (by default <see cref="KnownVariables"/>) settled.</summary>
public static RequestCatalog Instagram(params string[] names)
{
var settle = names.Length == 0 ? KnownVariables : names;
var file = JsonNode.Parse(SiteMap.ReadEmbeddedText("richieste.instagram.json"))!.AsObject();
foreach (var operation in file["operations"]!.AsArray().Select(o => o!.AsObject()))
{
if (!settle.Contains(operation["name"]!.GetValue<string>()))
{
continue;
}
foreach (var part in new[] { "headers", "body" })
{
if (operation[part] is JsonObject sources)
{
foreach (var key in sources.Where(s => s.Value?.GetValue<string>() == "pending").Select(s => s.Key).ToList())
{
sources.Remove(key);
}
}
}
operation["configured"] = true;
operation.Remove("reason");
}
return RequestCatalog.Parse(file.ToJsonString(), "richieste.instagram.json (sistemato per le prove)");
}
}