CookieContainer: when a Set-Cookie has both Expires and Max-Age, the first one wins instead of Max-Age

Aperta Adatta ai principianti
#138,251 1 commento 0 reazioni 0 assegnatari Vedi su GitHub

I maintainer di solito rispondono entro 1 giorno

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
2/5
Tempo stimato
1-3 ore
Idoneità per principianti
74/100
Tipo di issue
Bug
Chiarezza
Specificata chiaramente
Stato di attività
Attiva
Stack tecnologico
csharp
Ambito
networking

Direzione di ricerca

Inizia da src/libraries/Common/src/System/Net/CookieParser.cs, nei casi CookieToken.Expires e CookieToken.MaxAge, che condividono l'unico flag expiresSet. Tieni traccia dei due attributi separatamente, così che un Max-Age analizzato correttamente prevalga in entrambi gli ordini. Riproduci prima il problema con lo snippet dell'issue per confermare l'header con Expires per primo e il caso di cancellazione con Max-Age=0. Aggiungi test di regressione per entrambi gli ordini degli attributi, con un Max-Age positivo e con Max-Age=0. Il lavoro è completato quando entrambi gli ordini producono la stessa scadenza e il caso di cancellazione non lascia alcun cookie.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

area-System.Net untriaged
Problem

When a Set-Cookie header contains valid Expires and Max-Age attributes, CookieContainer.SetCookies uses whichever appears first. This also affects HttpClient when its handler uses the cookie container. PHP's setcookie() emits Expires before Max-Age when it sends both.

A short-lived cookie can be dropped on receipt if the server's clock is far enough behind the client's that Expires is already in the past. In the synthetic deletion example below, a future Expires causes the container to keep a cookie with an empty value even though Max-Age=0 asks it to remove the cookie.

using System.Net;

var uri = new Uri("https://example.com/");
string expires = DateTime.UtcNow.AddMinutes(-10 + 5).ToString("R");

foreach (var header in new[] {
    $"state=xyz; expires={expires}; Max-Age=300; path=/",   // Expires first (PHP's order)
    $"state=xyz; Max-Age=300; expires={expires}; path=/" }) // Max-Age first
{
    var jar = new CookieContainer();
    jar.SetCookies(uri, header);
    Console.WriteLine($"{jar.GetCookies(uri).Count} cookie(s) kept for: {header}");
}

var jar2 = new CookieContainer();
jar2.SetCookies(uri, "session=abc; path=/");
jar2.SetCookies(uri, $"session=; expires={DateTime.UtcNow.AddDays(1):R}; Max-Age=0; path=/");
Console.WriteLine($"after Max-Age=0: {jar2.GetCookies(uri).Count} cookie(s)");

Output on .NET 8.0.31 and .NET 10.0.12:

0 cookie(s) kept for: state=xyz; expires=Wed, 25 Nov 2026 00:03:49 GMT; Max-Age=300; path=/
1 cookie(s) kept for: state=xyz; Max-Age=300; expires=Wed, 25 Nov 2026 00:03:49 GMT; path=/
after Max-Age=0: 1 cookie(s)

The first two headers differ only in attribute order. CookieContainer drops the Expires-first cookie and keeps the Max-Age-first cookie. The precedence rule was raised in a comment on #74794. That issue was closed after #76848 addressed the two-digit-year parsing problem in the Baidu repro.

Expected

RFC 6265, section 4.1.2.2:

If a cookie has both the Max-Age and the Expires attribute, the Max-Age attribute has precedence and controls the expiration date of the cookie.

Section 5.3, step 3, gives the same rule for user agents, whatever the order:

If the cookie-attribute-list contains an attribute with an attribute-name of "Max-Age": [...] Set the cookie's expiry-time to attribute-value of the last attribute in the cookie-attribute-list with an attribute-name of "Max-Age".

Otherwise, if the cookie-attribute-list contains an attribute with an attribute-name of "Expires" (and does not contain an attribute with an attribute-name of "Max-Age"): [...]

The first two headers should both set an expiration 300 seconds after receipt. The third should remove the existing session cookie.

Cause

In src/libraries/Common/src/System/Net/CookieParser.cs, Expires and Max-Age share one expiresSet flag, so the first one seen sets cookie.Expires and the second is skipped:

case CookieToken.Expires:
    if (!expiresSet)
    {
        expiresSet = true;
        ...
case CookieToken.MaxAge:
    if (!expiresSet)
    {
        expiresSet = true;
        if (int.TryParse(CheckQuotedSpan(_tokenizer.Value), out int parsed))
        {
            cookie!.Expires = DateTime.UtcNow.AddSeconds(parsed);
Suggested fix
Suggested behavior

Use a successfully parsed Max-Age in preference to Expires in either attribute order. Add regression tests for both orders with a positive Max-Age and with Max-Age=0.

Tested with
  • .NET 8.0.31 and .NET 10.0.12 on macOS arm64. The same code is on main (0a4458e8e9, 30 Oct 2026): CookieParser shares one expiresSet flag between the two attributes.
  • In a separate .NET 10.0.12 run, I tested all 154 orders of zero or one Expires value (one hour ahead, one year ahead, 1970, or 9999), zero or one Max-Age value (3600, 31536000, 0, or -1), and optional HttpOnly, with Path=/ fixed. The retained-cookie count or expiration differed from the RFC expectation in 48 cases, all with Expires before Max-Age.

Found with a new AI-assisted methodology from a Pullboard discovery. A paper describing it will follow.

Links

Lingua principale
C#
Stelle
18.5k
Fork
5.8k
Merge medio
2g 16h
PR unite (30g)
611

Preparare l'ambiente

Apri in Codespaces

Avvia il container di sviluppo del progetto nel browser, con il tuo account GitHub.

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di dotnet/runtime

Tutte le issue di dotnet/runtime

Issue simili

Altre issue su C#

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.