Client del sito contro il sito di prova (#36, S2)
verifica / controlli (push) Successful in 17s
verifica / prove (push) Successful in 15m4s
verifica / installatore (push) Successful in 4m22s
verifica / immagine (push) Successful in 15m55s

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:
Alby96andClaude Opus 5.5 committed 2026-11-16 18:34:12 +01:00
1 parent e10c25d12d
commit ce9691fe1c
19 files changed
+3563 -51

No files matched your search

+285
View File
@@ -0,0 +1,285 @@
using System.Collections.Frozen;
using System.Text.Json;
using System.Text.Json.Nodes;
using Microsoft.AspNetCore.Http;
namespace Febe.SitoDiProva;
/// <summary>
/// The answers to the site client of Febe (issue #36, spec §6.0, §14.2): the operations of <c>richieste.prova.json</c>,
/// served under <c>/api/</c> in the request shape the catalog describes, with the same JSON the pages fetch from
/// <c>/dati/</c>. Here the site checks what a real site checks: the session cookie, <c>x-csrftoken</c> equal to the
/// cookie <c>csrftoken</c>, the headers and fields of the catalog. The pages keep their <c>/dati/</c>, which checks
/// nothing, so the browser tests do not change.
/// </summary>
/// <remarks>
/// What a refused request gets is generic and marked H16: the true answers of Instagram to an expired session, a wrong
/// token or a malformed request are not known from samples. A missing or ended session: a plain address gets 302 to
/// <c>/accesso/</c>, a GraphQL query 401 with a short JSON. A wrong or missing <c>x-csrftoken</c>: 403 with an HTML page.
/// A missing header, an unknown <c>doc_id</c>, a field or variables that do not match: 400 with a short JSON.
/// </remarks>
public sealed partial class TestSite
{
/// <summary>Name of the cookie whose value goes in <c>x-csrftoken</c>.</summary>
public const string CsrfCookie = "csrftoken";
/// <summary>The value of <c>x-app-id</c> the pages of the site would send (a value of the page, session:app_id).</summary>
public const string AppId = "prova-applicazione-1";
/// <summary>The token <c>lsd</c> the pages of the site would hold (session:lsd).</summary>
public const string Lsd = "lsd-di-prova";
/// <summary>The token <c>fb_dtsg</c> the pages of the site would hold (session:fb_dtsg).</summary>
public const string Dtsg = "dtsg-di-prova";
/// <summary>The GraphQL query of the site: a profile page, with the JSON of <c>/dati/profilo/{nome}</c>.</summary>
public const string ProfileQuery = "ProvaProfiloQuery";
/// <summary>The <c>doc_id</c> of each GraphQL query, as the modules of the pages would hold them (session:doc_id).</summary>
public static IReadOnlyDictionary<string, string> DocIds { get; } =
new Dictionary<string, string> { [ProfileQuery] = "8000000000000001" }.ToFrozenDictionary(StringComparer.Ordinal);
private const string Html = "<!DOCTYPE html><html lang=\"it\"><head><meta charset=\"utf-8\"><title>Sito di prova</title></head><body><p>Una pagina, non dati.</p></body></html>";
private async Task DirectAsync(HttpContext context, string path)
{
var request = context.Request;
var (reply, mode) = Control.OnDirectRequest($"{request.Method} {path}{request.QueryString.Value}");
try
{
if (Control.DirectDelay > TimeSpan.Zero)
{
await Task.Delay(Control.DirectDelay, context.RequestAborted).ConfigureAwait(false);
}
if (await StopAsync(context, path, reply, mode).ConfigureAwait(false))
{
return;
}
var isGraphQl = path == "/api/graphql";
var segments = path.Split('/', StringSplitOptions.RemoveEmptyEntries).Select(Uri.UnescapeDataString).ToArray();
if (!isGraphQl && segments is not ["api", "dati", ..])
{
await JsonAsync(context, 404, new JsonObject { ["errore"] = "non-trovato" }).ConfigureAwait(false);
return;
}
if (isGraphQl ? !HttpMethods.IsPost(request.Method) : !HttpMethods.IsGet(request.Method))
{
// A write (POST of a plain address) or a GET of the GraphQL entry: no site answers it with data.
await JsonAsync(context, 405, new JsonObject { ["errore"] = "metodo" }).ConfigureAwait(false);
return;
}
var session = request.Cookies[SessionCookie];
if (!Control.IsSession(session))
{
// H16-generic: what Instagram answers to a missing or ended session is not known from samples.
if (isGraphQl)
{
await JsonAsync(context, 401, new JsonObject { ["errore"] = "sessione", ["accesso_richiesto"] = true }).ConfigureAwait(false);
}
else
{
context.Response.Redirect("/accesso/?next=" + Uri.EscapeDataString(path));
}
return;
}
var csrf = request.Cookies[CsrfCookie];
if (string.IsNullOrEmpty(csrf) || request.Headers["x-csrftoken"].ToString() != csrf)
{
// H16-generic: a token missing or different from its cookie.
await HtmlAsync(context, 403, "<!DOCTYPE html><html lang=\"it\"><head><meta charset=\"utf-8\"><title>Vietato</title></head><body><h1>Verifica del gettone non riuscita</h1></body></html>").ConfigureAwait(false);
return;
}
if (string.IsNullOrWhiteSpace(request.Headers.UserAgent.ToString())
|| request.Headers.Accept.Count == 0
|| request.Headers["x-app-id"].ToString() != AppId)
{
await BadRequestAsync(context, "intestazioni").ConfigureAwait(false);
return;
}
JsonObject? data;
if (isGraphQl)
{
var (problem, answer) = await GraphQlAsync(request).ConfigureAwait(false);
if (problem is not null)
{
await BadRequestAsync(context, problem).ConfigureAwait(false);
return;
}
data = answer;
}
else if (segments is ["api", "dati", "cerca"])
{
lock (World.Gate)
{
data = Api.Search(request.Query["testo"].ToString());
}
}
else if (segments is ["api", "dati", "ricerche-recenti"])
{
// Read only: the site client never writes (a POST was refused above).
lock (World.Gate)
{
data = Api.RecentSearches([.. World.Following.Take(3).Select(a => a.Username)]);
}
}
else
{
data = Lookup(segments[1..], request.Query);
}
if (data is null)
{
await JsonAsync(context, 404, new JsonObject { ["errore"] = "non-trovato" }).ConfigureAwait(false);
return;
}
Decorate(context, reply, session!);
await JsonAsync(context, 200, data).ConfigureAwait(false);
}
finally
{
Control.OnDirectFinished();
}
}
/// <summary>The stop cases, before any check: the reply the tests asked for, or the mode of the whole site.</summary>
private async Task<bool> StopAsync(HttpContext context, string path, DirectReply reply, StopMode mode)
{
if (reply == DirectReply.TooManyRequests || (reply == DirectReply.Normal && mode == StopMode.TooManyRequests))
{
context.Response.Headers.RetryAfter = "60";
await JsonAsync(context, 429, new JsonObject { ["errore"] = "troppe-richieste", ["messaggio"] = "Troppe richieste: riprova più tardi." }).ConfigureAwait(false);
return true;
}
if (reply == DirectReply.RedirectToChallenge || (reply == DirectReply.Normal && mode == StopMode.Challenge))
{
context.Response.Redirect("/verifica?motivo=prova&next=" + Uri.EscapeDataString(path));
return true;
}
if (reply == DirectReply.RedirectToLogin || (reply == DirectReply.Normal && mode == StopMode.SessionEnded))
{
if (mode == StopMode.SessionEnded)
{
// The session ends on the site too: a client that kept the cookie gets the login page after it.
EndSession(context);
}
context.Response.Redirect("/accesso/?next=" + Uri.EscapeDataString(path));
return true;
}
if (reply == DirectReply.HtmlInsteadOfJson)
{
await HtmlAsync(context, 200, Html).ConfigureAwait(false);
return true;
}
if (reply == DirectReply.MissingRootField || (reply == DirectReply.Normal && mode == StopMode.UnknownFormat))
{
await JsonAsync(context, 200, DataApi.UnknownShape()).ConfigureAwait(false);
return true;
}
if (reply == DirectReply.Normal && mode == StopMode.EmptyPages)
{
await JsonAsync(context, 200, DataApi.EmptyPage()).ConfigureAwait(false);
return true;
}
return false;
}
/// <summary>
/// The GraphQL query: form fields, <c>doc_id</c>, friendly name, tokens and variables as the pages would send them.
/// Returns why it is refused, or the data.
/// </summary>
private async Task<(string? Problem, JsonObject? Data)> GraphQlAsync(HttpRequest request)
{
if (!request.HasFormContentType || request.ContentType?.StartsWith("application/x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase) != true)
{
return ("tipo", null);
}
var form = await request.ReadFormAsync().ConfigureAwait(false);
var docId = form["doc_id"].ToString();
var name = form["fb_api_req_friendly_name"].ToString();
if (!DocIds.TryGetValue(name, out var expected) || expected != docId || request.Headers["x-fb-friendly-name"].ToString() != name)
{
return ("doc_id", null);
}
if (form["lsd"].ToString() != Lsd || form["fb_dtsg"].ToString() != Dtsg || form["__a"].ToString() != "1"
|| string.IsNullOrEmpty(request.Headers["x-ig-www-claim"].ToString()))
{
return ("campi", null);
}
JsonObject variables;
try
{
variables = JsonNode.Parse(form["variables"].ToString()) as JsonObject ?? throw new JsonException();
}
catch (JsonException)
{
return ("variabili", null);
}
// ProvaProfiloQuery: {"username": text, "scheda": "post" | "reel" | "taggati", "primi": 12, "raccolte": true | false}.
if (variables.Count != 4
|| variables["username"] is not JsonValue user || user.GetValueKind() != JsonValueKind.String
|| variables["scheda"] is not JsonValue tab || tab.GetValueKind() != JsonValueKind.String
|| variables["primi"] is not JsonValue first || first.GetValueKind() != JsonValueKind.Number || first.ToJsonString() != "12"
|| variables["raccolte"] is not JsonValue highlights || highlights.GetValueKind() is not (JsonValueKind.True or JsonValueKind.False))
{
return ("variabili", null);
}
var profileTab = tab.GetValue<string>() switch
{
"post" => ProfileTab.Posts,
"reel" => ProfileTab.Reels,
"taggati" => ProfileTab.Tagged,
_ => (ProfileTab?)null,
};
if (profileTab is null)
{
return ("variabili", null);
}
lock (World.Gate)
{
return (null, Api.Profile(user.GetValue<string>(), profileTab.Value, null));
}
}
/// <summary>What a normal answer carries besides the data, when the tests asked for it.</summary>
private void Decorate(HttpContext context, DirectReply reply, string session)
{
switch (reply)
{
case DirectReply.RenewSessionCookie:
context.Response.Cookies.Append(SessionCookie, Control.RenewSession(session), new CookieOptions { Path = "/", MaxAge = TimeSpan.FromDays(1), SameSite = SameSiteMode.Lax, HttpOnly = true });
break;
case DirectReply.DeleteSessionCookie:
EndSession(context);
break;
case DirectReply.SetClaim:
context.Response.Headers["x-ig-set-www-claim"] = Control.NextClaim();
break;
}
}
private static Task BadRequestAsync(HttpContext context, string what) =>
JsonAsync(context, 400, new JsonObject { ["errore"] = "richiesta-non-valida", ["dove"] = what });
}
+55 -3
View File
@@ -101,6 +101,53 @@ pagina { altro, dopo }
chiave, stessa immagine a ogni dimensione); i video sono due MP4 minuscoli generati una volta con ffmpeg
(`Risorse/filmato-con-audio.mp4`, `Risorse/filmato-muto.mp4`), resi unici aggiungendo in coda un riquadro `free`.
## Richieste dirette del client del sito (issue #36)
Dalla tappa S2 il sito risponde anche al **client del sito** di Febe (`HttpSiteRequester`, specifica §6.0), che chiede i
dati senza browser con la sessione copiata. Le operazioni sono quelle di `src/Febe.Core/Config/richieste.prova.json`,
servite sotto `/api/` con lo **stesso JSON** che le pagine leggono da `/dati/`. Le pagine continuano a chiedere `/dati/`,
che non controlla nulla: per il browser non cambia niente.
| Richiesta | Risposta |
|---|---|
| `GET /api/dati/...` | lo stesso indirizzo e la stessa risposta di `/dati/...` (tabella sopra) |
| `POST /api/graphql` | la richiesta GraphQL `ProvaProfiloQuery`: modulo `application/x-www-form-urlencoded` con `doc_id`, `fb_api_req_friendly_name`, `variables`, `lsd`, `fb_dtsg`, `__a=1`, `av`; risponde con il JSON di `/dati/profilo/{nome}?scheda=...` |
| un'altra richiesta sotto `/api/` | 404; un `POST` di un indirizzo semplice o un `GET` di `/api/graphql`: 405 (il client non scrive mai) |
Su `/api/` il sito controlla quello che controlla un sito vero, nell'ordine:
1. il cookie `sessione_prova` con un valore che il sito ha dato e non ha chiuso: quello che le pagine danno a una visita
senza sessione viva (`aperta-1`, `aperta-2`…), un valore rinnovato (`rinnovata-1`…), oppure `attiva`
(`SiteControl.InitialSession`), una sessione già aperta all'avvio e dopo `/_controllo/reimposta`, che le pagine non
danno mai e che usano le prove che preparano una sessione salvata senza il browser;
2. l'intestazione `x-csrftoken` uguale al cookie `csrftoken`;
3. `user-agent` non vuoto, `accept` presente, `x-app-id` uguale a `prova-applicazione-1`;
4. per `/api/graphql`: `content-type`, il `doc_id` della query (`ProvaProfiloQuery` = `8000000000000001`) con lo stesso
nome in `fb_api_req_friendly_name` e in `x-fb-friendly-name`, `lsd` = `lsd-di-prova`, `fb_dtsg` = `dtsg-di-prova`,
`x-ig-www-claim` presente (il client manda `0`, come la pagina, finché il sito non ne dà uno), e le variabili con i
loro tipi: `{"username": testo, "scheda": "post"|"reel"|"taggati", "primi": 12 (numero), "raccolte": vero/falso}`.
I valori sono costanti di `TestSite` (`AppId`, `Lsd`, `Dtsg`, `DocIds`, `CsrfCookie`). Le pagine del sito **non danno
ancora** nessuno di questi valori: né il cookie `csrftoken`, né `app_id`, `lsd`, `fb_dtsg`, il `doc_id` della query o un
claim. Per ora li mettono le prove nella sessione salvata (`InMemorySiteSession`); perché una sessione copiata dal
browser di prova passi i controlli, la tappa S4 deve farli esporre alle pagine (un cookie e i moduli, come su
Instagram). Le risposte a una richiesta che non passa i controlli sono **generiche e marcate H16**: non si sa ancora
che cosa risponde Instagram a una sessione scaduta, a un gettone sbagliato o a una richiesta malformata.
| Controllo non passato | Risposta (H16, generica) |
|---|---|
| sessione mancante o chiusa | indirizzo semplice: `302` a `/accesso/?next=...`; GraphQL: `401` con `{"errore":"sessione","accesso_richiesto":true}` |
| `x-csrftoken` mancante o diverso dal cookie | `403` con una pagina HTML |
| intestazione, `doc_id`, campo o variabili che non tornano | `400` con `{"errore":"richiesta-non-valida","dove":...}` |
I modi di tutto il sito (`/_controllo/modo`) valgono anche qui: `troppe-richieste` dà 429, `verifica` un rinvio a
`/verifica`, `sessione-scaduta` chiude la sessione anche sul sito, cancella il cookie e rinvia a `/accesso/`, `vuoto` e
`formato-sconosciuto` come per `/dati/`. Un modo armato «dopo N richieste di dati» (`/_controllo/modo?dopo=N`,
`Control.Set(modo, afterDataRequests: N)`) conta anche le richieste del client del sito, come quelle delle pagine. Le
richieste del client si elencano a parte (`DirectRequests`), non fra quelle delle pagine (`DataRequests`).
Le visite di `/accesso…` e `/verifica…` si contano (`LoginPageVisits`, `ChallengePageVisits`): un rinvio seguito
lascerebbe il segno. `/accesso` resta una pagina che non esiste (404): il sito non ha moduli d'accesso.
## Casi di arresto e comandi per le prove
Dentro il processo: `site.Control` (`SiteControl`). Da fuori: `/_controllo/...` sul sito.
@@ -109,7 +156,7 @@ Dentro il processo: `site.Control` (`SiteControl`). Da fuori: `/_controllo/...`
|---|---|
| `/_controllo/modo?valore=troppe-richieste[&dopo=N]` | le richieste di dati ricevono 429 (dopo N richieste) |
| `/_controllo/modo?valore=verifica` | le pagine rimandano a `/verifica`; i dati rispondono 403 e la pagina ci va da sola |
| `/_controllo/modo?valore=sessione-scaduta` | il cookie `sessione_prova` si cancella e le pagine vanno a `/sessione-scaduta` |
| `/_controllo/modo?valore=sessione-scaduta` | il cookie `sessione_prova` si cancella e le pagine vanno a `/sessione-scaduta`; la sessione si chiude anche sul sito, così lo stesso valore copiato nel client del sito non vale più |
| `/_controllo/modo?valore=vuoto` | le pagine di dati arrivano vuote |
| `/_controllo/modo?valore=formato-sconosciuto` | i dati arrivano in una forma che nessun lettore conosce |
| `/_controllo/modo?valore=normale`, `/_controllo/reimposta` | tutto torna normale |
@@ -123,6 +170,11 @@ Dentro il processo: `site.Control` (`SiteControl`). Da fuori: `/_controllo/...`
| `/_controllo/ricerca/disordine?valore=si\|no` | le risposte ai testi più corti arrivano più tardi (fuori ordine) |
| `/_controllo/ricerca/memoria?valore=si\|no` | il pannello ricorda il testo quando si richiude, come Instagram |
| `/_controllo/ricerca/recenti` | quante ricerche recenti sono state scritte |
| `/_controllo/stato` | modo attuale e numero di richieste di dati |
| `/_controllo/diretto?valore=troppe-richieste\|accesso\|verifica\|html\|senza-campi\|rinnova-cookie\|cancella-cookie\|claim\|normale[&sempre=si]` | la prossima richiesta del client del sito (con `sempre=si` tutte) riceve: 429 con `Retry-After: 60`; 302 a `/accesso/`; 302 a `/verifica`; una pagina HTML al posto del JSON; un JSON senza i campi attesi; i dati con un `Set-Cookie` che rinnova `sessione_prova` (il valore vecchio smette di valere); i dati con un `Set-Cookie` che lo cancella (la sessione finisce); i dati con un nuovo `x-ig-set-www-claim`. Dentro il processo: `site.Control.ReplyToDirect(DirectReply...)` |
| `/_controllo/diretto/ritardo?ms=` | ritardo di ogni risposta al client del sito (`Control.DirectDelay`); `Control.MaxDirectInFlight` dice quante ne ha servite insieme al massimo |
| `/_controllo/stato` | modo attuale, numero di richieste di dati delle pagine e del client del sito, visite delle pagine di accesso e di verifica |
Il sito non ha pagine di accesso: la sessione (cookie `sessione_prova`) nasce alla prima visita di una pagina.
Il sito non ha pagine di accesso: la sessione (cookie `sessione_prova`) nasce alla visita di una pagina senza una
sessione viva, cioè senza cookie o con un valore che il sito ha chiuso (sessione scaduta, cookie cancellato dal client
del sito, reimpostazione). Ogni visita così è un nuovo accesso, con un valore nuovo che vale anche per `/api/`: dopo
`sessione-scaduta` e poi `normale`, rivisitare una pagina riapre la sessione.
+192
View File
@@ -24,11 +24,56 @@ public enum StopMode
UnknownFormat,
}
/// <summary>
/// What the site answers to the next request of the site client (<c>/api/…</c>, issue #36) instead of the data: the stop
/// cases of spec §7.6 and the renewals the client must keep. The shapes not known from samples are generic (H16).
/// </summary>
public enum DirectReply
{
/// <summary>The data, after the checks of a real site.</summary>
Normal,
/// <summary>429 with a short JSON and <c>Retry-After: 60</c> (Rallentamento).</summary>
TooManyRequests,
/// <summary>302 to the login page <c>/accesso/</c> (H16-generic).</summary>
RedirectToLogin,
/// <summary>302 to the challenge page <c>/verifica</c> (H16-generic).</summary>
RedirectToChallenge,
/// <summary>200 with an HTML document where JSON is expected (H16-generic).</summary>
HtmlInsteadOfJson,
/// <summary>200 with a JSON that has none of the expected root fields (H16-generic).</summary>
MissingRootField,
/// <summary>The data, with a <c>Set-Cookie</c> that renews the session cookie (new value, the old one stops working).</summary>
RenewSessionCookie,
/// <summary>The data, with a <c>Set-Cookie</c> that deletes the session cookie (the session ends).</summary>
DeleteSessionCookie,
/// <summary>The data, with a new <c>x-ig-set-www-claim</c>.</summary>
SetClaim,
}
/// <summary>Switches and counters of the test site. Thread-safe.</summary>
public sealed class SiteControl
{
private readonly Lock _gate = new();
private readonly ConcurrentQueue<string> _dataRequests = new();
private readonly ConcurrentQueue<string> _directRequests = new();
private readonly ConcurrentQueue<DirectReply> _directReplies = new();
private readonly HashSet<string> _sessions = new(StringComparer.Ordinal) { InitialSession };
private DirectReply _directAlways = DirectReply.Normal;
private int _directInFlight;
private int _maxDirectInFlight;
private int _loginVisits;
private int _challengeVisits;
private int _renewals;
private int _logins;
private int _claims;
private StopMode _mode = StopMode.Normal;
private int _armAfter;
@@ -76,6 +121,140 @@ public sealed class SiteControl
/// </summary>
public int RecentSearchWrites => _recentSearchWrites;
/// <summary>
/// A session already open when the site starts and after <see cref="Reset"/>, as one opened before the test: the
/// tests that build a saved session without the browser use it. The pages never hand it out: a visit without a live
/// session gets a new value (<see cref="OpenSession"/>).
/// </summary>
public const string InitialSession = "attiva";
/// <summary>Method, path and query of every request of the site client (<c>/api/…</c>), in arrival order.</summary>
public IReadOnlyList<string> DirectRequests => [.. _directRequests];
/// <summary>The most requests of the site client the site was answering at the same time.</summary>
public int MaxDirectInFlight => Volatile.Read(ref _maxDirectInFlight);
/// <summary>Extra wait before every answer to the site client (slow answers).</summary>
public TimeSpan DirectDelay { get; set; }
/// <summary>Requests of the login page <c>/accesso…</c> (a redirect followed would land there).</summary>
public int LoginPageVisits => Volatile.Read(ref _loginVisits);
/// <summary>Requests of the challenge page <c>/verifica…</c>.</summary>
public int ChallengePageVisits => Volatile.Read(ref _challengeVisits);
/// <summary>The site client answers to the next request (or, with <paramref name="always"/>, to every one) with <paramref name="reply"/>.</summary>
public void ReplyToDirect(DirectReply reply, bool always = false)
{
if (always)
{
lock (_gate)
{
_directAlways = reply;
}
_directReplies.Clear();
return;
}
_directReplies.Enqueue(reply);
}
/// <summary>True when <paramref name="value"/> is a session cookie the site handed out and did not end.</summary>
public bool IsSession(string? value)
{
lock (_gate)
{
return value is { Length: > 0 } && _sessions.Contains(value);
}
}
/// <summary>A new session, as a new login opens: its value works for the pages and for the site client.</summary>
internal string OpenSession()
{
var opened = "aperta-" + Interlocked.Increment(ref _logins).ToString(System.Globalization.CultureInfo.InvariantCulture);
lock (_gate)
{
_sessions.Add(opened);
}
return opened;
}
/// <summary>A new value of the session cookie in place of <paramref name="old"/>, which stops working.</summary>
internal string RenewSession(string old)
{
var renewed = "rinnovata-" + Interlocked.Increment(ref _renewals).ToString(System.Globalization.CultureInfo.InvariantCulture);
lock (_gate)
{
_sessions.Remove(old);
_sessions.Add(renewed);
}
return renewed;
}
/// <summary>Ends the session <paramref name="value"/>.</summary>
internal void EndSession(string value)
{
lock (_gate)
{
_sessions.Remove(value);
}
}
/// <summary>A new claim value.</summary>
internal string NextClaim() => "claim-prova-" + Interlocked.Increment(ref _claims).ToString(System.Globalization.CultureInfo.InvariantCulture);
/// <summary>
/// Records a request of the site client and returns the reply it gets and the mode of the site that applies to it:
/// a request of the site client counts as a data request for <see cref="Set"/> with <c>afterDataRequests</c>, as a
/// page's <c>/dati/</c> does. Pair with <see cref="OnDirectFinished"/>.
/// </summary>
internal (DirectReply Reply, StopMode Mode) OnDirectRequest(string methodPathAndQuery)
{
_directRequests.Enqueue(methodPathAndQuery);
var now = Interlocked.Increment(ref _directInFlight);
int max;
while (now > (max = Volatile.Read(ref _maxDirectInFlight)) && Interlocked.CompareExchange(ref _maxDirectInFlight, now, max) != max)
{
}
StopMode mode;
DirectReply always;
lock (_gate)
{
if (_armAfter > 0)
{
_armAfter--;
mode = StopMode.Normal;
}
else
{
mode = _mode;
}
always = _directAlways;
}
return (_directReplies.TryDequeue(out var next) ? next : always, mode);
}
internal void OnDirectFinished() => Interlocked.Decrement(ref _directInFlight);
/// <summary>Counts the visits of the login and challenge pages.</summary>
internal void OnPageVisit(string path)
{
if (path.StartsWith("/accesso", StringComparison.Ordinal))
{
Interlocked.Increment(ref _loginVisits);
}
else if (path.StartsWith("/verifica", StringComparison.Ordinal))
{
Interlocked.Increment(ref _challengeVisits);
}
}
public StopMode Mode
{
get
@@ -107,6 +286,19 @@ public sealed class SiteControl
}
_dataRequests.Clear();
_directRequests.Clear();
_directReplies.Clear();
lock (_gate)
{
_directAlways = DirectReply.Normal;
_sessions.Clear();
_sessions.Add(InitialSession);
}
DirectDelay = TimeSpan.Zero;
Interlocked.Exchange(ref _maxDirectInFlight, 0);
Interlocked.Exchange(ref _loginVisits, 0);
Interlocked.Exchange(ref _challengeVisits, 0);
StoryDuration = TimeSpan.FromSeconds(5);
AddressLifetime = TimeSpan.FromHours(6);
CdnTooManyRequests = false;
+65 -16
View File
@@ -38,7 +38,7 @@ public sealed record TestSiteOptions
/// fetch JSON in a synthetic format of our own; stop cases are switched through <see cref="Control"/> or the
/// <c>/_controllo</c> endpoints. Never Instagram, never anything that looks like it.
/// </summary>
public sealed class TestSite : IAsyncDisposable
public sealed partial class TestSite : IAsyncDisposable
{
/// <summary>Name of the session cookie of the site.</summary>
public const string SessionCookie = "sessione_prova";
@@ -165,12 +165,19 @@ public sealed class TestSite : IAsyncDisposable
return;
}
if (path.StartsWith("/api/", StringComparison.Ordinal))
{
await DirectAsync(context, path).ConfigureAwait(false);
return;
}
await PageAsync(context, path).ConfigureAwait(false);
}
private async Task PageAsync(HttpContext context, string path)
{
var mode = Control.Mode;
Control.OnPageVisit(path);
if (path is "/verifica" or "/verifica/")
{
await HtmlAsync(context, 200, Pages.Challenge()).ConfigureAwait(false);
@@ -195,14 +202,16 @@ public sealed class TestSite : IAsyncDisposable
context.Response.Redirect("/verifica?motivo=prova");
return;
case StopMode.SessionEnded:
ExpireSession(context);
EndSession(context);
context.Response.Redirect("/sessione-scaduta");
return;
}
if (!context.Request.Cookies.ContainsKey(SessionCookie))
if (!Control.IsSession(context.Request.Cookies[SessionCookie]))
{
context.Response.Cookies.Append(SessionCookie, "attiva", new CookieOptions { Path = "/", MaxAge = TimeSpan.FromDays(1), SameSite = SameSiteMode.Lax, HttpOnly = true });
// No cookie, or one the site ended (a session that expired, a reset): the visit is a new login, with a new
// value that the site client accepts too once copied.
context.Response.Cookies.Append(SessionCookie, Control.OpenSession(), new CookieOptions { Path = "/", MaxAge = TimeSpan.FromDays(1), SameSite = SameSiteMode.Lax, HttpOnly = true });
}
var segments = path.Split('/', StringSplitOptions.RemoveEmptyEntries).Select(Uri.UnescapeDataString).ToArray();
@@ -272,7 +281,7 @@ public sealed class TestSite : IAsyncDisposable
await JsonAsync(context, 403, new JsonObject { ["errore"] = "verifica" }).ConfigureAwait(false);
return;
case StopMode.SessionEnded:
ExpireSession(context);
EndSession(context);
await JsonAsync(context, 401, new JsonObject { ["errore"] = "sessione" }).ConfigureAwait(false);
return;
case StopMode.EmptyPages:
@@ -310,13 +319,28 @@ public sealed class TestSite : IAsyncDisposable
return;
}
var result = Lookup(segments, query);
if (result is null)
{
await JsonAsync(context, 404, new JsonObject { ["errore"] = "non-trovato" }).ConfigureAwait(false);
return;
}
await JsonAsync(context, 200, result).ConfigureAwait(false);
}
/// <summary>
/// The JSON of a data address (<c>/dati/…</c> for the pages, the same under <c>/api/dati/…</c> for the site client),
/// by its segments from «dati» on; null when there is nothing there.
/// </summary>
private JsonObject? Lookup(string[] segments, IQueryCollection query)
{
var tab = query["scheda"].ToString() switch { "reel" => ProfileTab.Reels, "taggati" => ProfileTab.Tagged, _ => ProfileTab.Posts };
var after = query["dopo"].ToString();
JsonObject? result;
lock (World.Gate)
{
var api = Api;
result = segments switch
return segments switch
{
["dati", "inizio"] => api.Home(),
["dati", "inizio", "altri"] => api.HomeMore(after),
@@ -329,14 +353,6 @@ public sealed class TestSite : IAsyncDisposable
_ => null,
};
}
if (result is null)
{
await JsonAsync(context, 404, new JsonObject { ["errore"] = "non-trovato" }).ConfigureAwait(false);
return;
}
await JsonAsync(context, 200, result).ConfigureAwait(false);
}
/// <summary>The answer of the search box, after the waits the control asks for (slow, out of order).</summary>
@@ -415,6 +431,28 @@ public sealed class TestSite : IAsyncDisposable
case "stato":
answer["modo"] = Control.Mode.ToString();
answer["richieste"] = Control.DataRequests.Count;
answer["dirette"] = Control.DirectRequests.Count;
answer["accesso"] = Control.LoginPageVisits;
answer["verifica"] = Control.ChallengePageVisits;
break;
case "diretto":
var reply = q["valore"].ToString() switch
{
"troppe-richieste" => DirectReply.TooManyRequests,
"accesso" => DirectReply.RedirectToLogin,
"verifica" => DirectReply.RedirectToChallenge,
"html" => DirectReply.HtmlInsteadOfJson,
"senza-campi" => DirectReply.MissingRootField,
"rinnova-cookie" => DirectReply.RenewSessionCookie,
"cancella-cookie" => DirectReply.DeleteSessionCookie,
"claim" => DirectReply.SetClaim,
_ => DirectReply.Normal,
};
Control.ReplyToDirect(reply, always: q["sempre"].ToString() is "si" or "sì" or "true");
answer["risposta"] = reply.ToString();
break;
case "diretto/ritardo":
Control.DirectDelay = TimeSpan.FromMilliseconds(int.Parse(q["ms"].ToString(), CultureInfo.InvariantCulture));
break;
case "modo":
var mode = q["valore"].ToString() switch
@@ -509,8 +547,19 @@ public sealed class TestSite : IAsyncDisposable
await stream.CopyToAsync(context.Response.Body).ConfigureAwait(false);
}
private static void ExpireSession(HttpContext context) =>
/// <summary>
/// The session of the request ends on the site (pages and site client alike) and its cookie is deleted: a copy of
/// the same value held elsewhere stops working too.
/// </summary>
private void EndSession(HttpContext context)
{
if (context.Request.Cookies[SessionCookie] is { Length: > 0 } ended)
{
Control.EndSession(ended);
}
context.Response.Cookies.Delete(SessionCookie, new CookieOptions { Path = "/" });
}
private static Task HtmlAsync(HttpContext context, int status, string html)
{