Skip to content
This repository was archived by the owner on Jan 23, 2023. It is now read-only.

SocketsHttpHandler: Fix some issues with cookie handling, and add cookie tests - #26989

Merged
geoffkizer merged 5 commits into
dotnet:masterfrom
geoffkizer:fixcookiehandling
Feb 12, 2018
Merged

geoffkizer merged 5 commits into
dotnet:masterfrom
geoffkizer:fixcookiehandling

Conversation

@geoffkizer

Copy link
Copy Markdown

Remove CookieHandler and integrate the cookie handling logic into HttpConnection, which fixes some issues with how cookies were handled.

Add a bunch of protocol tests for cookie handling. Issues filed for failures in CurlHandler and WinHttpHandler.

Fixes #26984
Fixes #26985

@geoffkizer

Copy link
Copy Markdown
Author

@stephentoub @davidsh @dotnet/ncl

public static void ProcessReceivedCookies(HttpResponseMessage response, CookieContainer cookieContainer)
{
IEnumerable<string> setCookies;
if (response.Headers.TryGetValues(HttpKnownHeaderNames.SetCookie, out setCookies))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: based on internal knowledge, do we know anything about what the actual type of setCookies will be? I'm wondering if, for example, it's always an array, we could cast to the array and avoid the enumerator allocation.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, it's always a string[]. I'm a little queasy about doing the cast; seems like it would be better to have an internal API that exposes it as string[]. That said, we are doing this in other places already.

await WriteStringAsync(cookies, cancellationToken).ConfigureAwait(false);

cookies = null;
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Will a Cookie header never have multiple values? I'm wondering about the loop below this... seems like if it did have multiple values, they'll end up getting appended with commas.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A 'Cookie' request header can have multiple cookies on the single 'Cookie' request header.

There has been confusion on this over the years. The latest RFC 6265 states:
https://tools.ietf.org/html/rfc6265#section-5.4

"5.4 When the user agent generates an HTTP request, the user agent MUST NOT attach more than one Cookie header field."

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The various HTTP APIs we have allow for multiple Cookie request headers to be set. But the end result of the HTTP stack is supposed to only send a single 'Cookie' header on the wire for the request.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, basically the Cookie header is weird because Netscape designed it poorly.

If the user sets multiple Cookie headers, that's arguably an error on their part. We could handle this by appending with ";" instead of "," -- this should be easy to do since we're already doing special handling here. Or we could just leave as-is and tell them not to do this.

I'm not sure what the other handlers do here; I'll investigate.

Note there's no strongly-typed Cookie property on the HttpRequestHeaders. Presumably this is intentional...

@stephentoub stephentoub Feb 9, 2018 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To be clear, though, I wasn't meaning to suggest multiple cookie headers, but rather multiple values for the single header, e.g.

using System;
using System.Net.Http;
using System.Threading.Tasks;

class Program
{
    static void Main()
    {
        var m = new HttpRequestMessage();
        m.Headers.Add("Cookie", new[] { "CustomCookie=456", "AnotherCustomCookie=789" });
        Console.WriteLine(m.Headers.ToString());
        foreach (var c in m.Headers.GetValues("Cookie"))
        {
            Console.WriteLine(c);
        }
    }
}

outputs:

Cookie: CustomCookie=456, AnotherCustomCookie=789

CustomCookie=456
AnotherCustomCookie=789

Am I misunderstanding?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, I meant multiple values.

If the user sets multiple values for a Cookie header, that's arguably an error on their part. We could handle this by appending with ";" instead of "," -- this should be easy to do since we're already doing special handling here. Or we could just leave as-is and tell them not to do this.

I'll investigate what other handlers do here.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok, thanks.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note there's no strongly-typed Cookie property on the HttpRequestHeaders. Presumably this is intentional...

Yes. It is intentional. The HttpWebRequest and HttpClient/HttpClientHandler APIs encouraged the use of the CookieContainer. Overall having devs manually add 'Cookie' request headers is discouraged.

@geoffkizer geoffkizer Feb 9, 2018 •

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WinHttpHandler behaves essentially the same as current SocketsHttpHandler here. That is, if you specify multiple Cookie header values, they get appended using a comma, e.g. "A=1, B=2". If you also have a cookie from the container, you get something like "ContainerCookie=Foo; A=1, B=2" -- that is, the container cookie is added to one of the cookie header values.

I'm fine with this behavior, as it matches header handling generally. I suppose we could special-case manual cookie header handling, but I don't think there's any real value here. Thoughts?

(edited for clarity to be consistent about "header values")

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sounds fine then.

if (cookies != null)
{
await WriteAsciiStringAsync(HttpKnownHeaderNames.Cookie, cancellationToken).ConfigureAwait(false);
await WriteTwoBytesAsync((byte)':', (byte)' ', cancellationToken).ConfigureAwait(false);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we use a cached byte[] representation of "Cookie: " and just blit that out with WriteBytesAsync?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

At some point I'd like to do this for all headers. We have already resolved them to well-known header values internally, it's just a matter of exposing an enumerator of KVP<HeaderDescriptor, IEnumerable> instead of KVP<string, IEnumerable>. Given this I don't think we should special case Cookie now.

public DateTimeOffset CreationTime { get; } = DateTimeOffset.UtcNow;

private async Task WriteHeadersAsync(HttpHeaders headers, CancellationToken cancellationToken)
private async Task WriteHeadersAsync(HttpHeaders headers, string cookies, CancellationToken cancellationToken)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: could we name the parameter something like "cookiesFromContainer"? Before reading the rest of the code, I was left wondering whether this was meant to be instead of or in addition to anything in the headers.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Will do


namespace System.Net.Http.Functional.Tests
{
public class HttpCookieProtocolTests : HttpClientTestBase

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There are already some cookie tests here:

[OuterLoop] // TODO: Issue #11345
[Fact]
public async Task GetAsync_DefaultCoookieContainer_NoCookieSent()
{
using (HttpClient client = CreateHttpClient())
{
using (HttpResponseMessage httpResponse = await client.GetAsync(Configuration.Http.RemoteEchoServer))
{
string responseText = await httpResponse.Content.ReadAsStringAsync();
_output.WriteLine(responseText);
Assert.False(TestHelper.JsonMessageContainsKey(responseText, "Cookie"));
}
}
}
[OuterLoop] // TODO: Issue #11345
[Theory]
[InlineData("cookieName1", "cookieValue1")]
public async Task GetAsync_SetCookieContainer_CookieSent(string cookieName, string cookieValue)
{
HttpClientHandler handler = CreateHttpClientHandler();
var cookieContainer = new CookieContainer();
cookieContainer.Add(Configuration.Http.RemoteEchoServer, new Cookie(cookieName, cookieValue));
handler.CookieContainer = cookieContainer;
using (var client = new HttpClient(handler))
{
using (HttpResponseMessage httpResponse = await client.GetAsync(Configuration.Http.RemoteEchoServer))
{
Assert.Equal(HttpStatusCode.OK, httpResponse.StatusCode);
string responseText = await httpResponse.Content.ReadAsStringAsync();
_output.WriteLine(responseText);
Assert.True(TestHelper.JsonMessageContainsKeyValue(responseText, cookieName, cookieValue));
}
}
}
[OuterLoop] // TODO: Issue #11345
[Theory]
[InlineData("cookieName1", "cookieValue1")]
public async Task GetAsync_RedirectResponseHasCookie_CookieSentToFinalUri(string cookieName, string cookieValue)
{
Uri uri = Configuration.Http.RedirectUriForDestinationUri(
secure: false,
statusCode: 302,
destinationUri: Configuration.Http.RemoteEchoServer,
hops: 1);
using (HttpClient client = CreateHttpClient())
{
client.DefaultRequestHeaders.Add(
"X-SetCookie",
string.Format("{0}={1};Path=/", cookieName, cookieValue));
using (HttpResponseMessage httpResponse = await client.GetAsync(uri))
{
string responseText = await httpResponse.Content.ReadAsStringAsync();
_output.WriteLine(responseText);
Assert.True(TestHelper.JsonMessageContainsKeyValue(responseText, cookieName, cookieValue));
}
}
}

and here:
private static KeyValuePair<string, string> GenerateCookie(string name, char repeat, int overallHeaderValueLength)
{
string emptyHeaderValue = $"{name}=; Path=/";
Debug.Assert(overallHeaderValueLength > emptyHeaderValue.Length);
int valueCount = overallHeaderValueLength - emptyHeaderValue.Length;
string value = new string(repeat, valueCount);
return new KeyValuePair<string, string>(name, value);
}
public static IEnumerable<object[]> CookieNameValuesAndUseCookies()
{
foreach (bool useCookies in new[] { true, false })
{
// WinHttpHandler calls WinHttpQueryHeaders to iterate through multiple Set-Cookie header values,
// using an initial buffer size of 128 chars. If the buffer is not large enough, WinHttpQueryHeaders
// returns an insufficient buffer error, allowing WinHttpHandler to try again with a larger buffer.
// Sometimes when WinHttpQueryHeaders fails due to insufficient buffer, it still advances the
// iteration index, which would cause header values to be missed if not handled correctly.
//
// In particular, WinHttpQueryHeader behaves as follows for the following header value lengths:
// * 0-127 chars: succeeds, index advances from 0 to 1.
// * 128-255 chars: fails due to insufficient buffer, index advances from 0 to 1.
// * 256+ chars: fails due to insufficient buffer, index stays at 0.
//
// The below overall header value lengths were chosen to exercise reading header values at these
// edges, to ensure WinHttpHandler does not miss multiple Set-Cookie headers.
yield return new object[] { GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 126), useCookies };
yield return new object[] { GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 127), useCookies };
yield return new object[] { GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 128), useCookies };
yield return new object[] { GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 129), useCookies };
yield return new object[] { GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 254), useCookies };
yield return new object[] { GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 255), useCookies };
yield return new object[] { GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 256), useCookies };
yield return new object[] { GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 257), useCookies };
yield return new object[]
{
new KeyValuePair<string, string>(
".AspNetCore.Antiforgery.Xam7_OeLcN4",
"CfDJ8NGNxAt7CbdClq3UJ8_6w_4661wRQZT1aDtUOIUKshbcV4P0NdS8klCL5qGSN-PNBBV7w23G6MYpQ81t0PMmzIN4O04fqhZ0u1YPv66mixtkX3iTi291DgwT3o5kozfQhe08-RAExEmXpoCbueP_QYM"),
useCookies
};
}
}
[OuterLoop] // TODO: Issue #11345
[Theory]
[MemberData(nameof(CookieNameValuesAndUseCookies))]
public async Task GetAsync_ResponseWithSetCookieHeaders_AllCookiesRead(KeyValuePair<string, string> cookie1, bool useCookies)
{
var cookie2 = new KeyValuePair<string, string>(".AspNetCore.Session", "RAExEmXpoCbueP_QYM");
var cookie3 = new KeyValuePair<string, string>("name", "value");
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
using (HttpClientHandler handler = CreateHttpClientHandler())
{
handler.UseCookies = useCookies;
using (var client = new HttpClient(handler))
{
Task<HttpResponseMessage> getResponseTask = client.GetAsync(url);
await TestHelper.WhenAllCompletedOrAnyFailed(
getResponseTask,
LoopbackServer.ReadRequestAndSendResponseAsync(server,
$"HTTP/1.1 200 OK\r\n" +
$"Date: {DateTimeOffset.UtcNow:R}\r\n" +
$"Set-Cookie: {cookie1.Key}={cookie1.Value}; Path=/\r\n" +
$"Set-Cookie : {cookie2.Key}={cookie2.Value}; Path=/\r\n" + // space before colon to verify header is trimmed and recognized
$"Set-Cookie: {cookie3.Key}={cookie3.Value}; Path=/\r\n" +
"\r\n"));
using (HttpResponseMessage response = await getResponseTask)
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
CookieCollection cookies = handler.CookieContainer.GetCookies(url);
if (useCookies)
{
Assert.Equal(3, cookies.Count);
Assert.Equal(cookie1.Value, cookies[cookie1.Key].Value);
Assert.Equal(cookie2.Value, cookies[cookie2.Key].Value);
Assert.Equal(cookie3.Value, cookies[cookie3.Key].Value);
}
else
{
Assert.Equal(0, cookies.Count);
}
}
}
}
});
}

If we're creating a new test class for cookies, can we consolidate them to the same place?

Pre-existing your PR, but exacerbated every time we add tests to new places, our scheme for where we put tests in this suite is unwieldy.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I will consolidate them into this file.

Uri requestUri = response.RequestMessage.RequestUri;
foreach (string setCookie in setCookies)
{
cookieContainer.SetCookies(requestUri, setCookie);

@stephentoub stephentoub Feb 9, 2018 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I must be missing something, but... how is this thread-safe? Does SetCookies internally lock? Same for getting the cookie values.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, CookieContainer is thread-safe and locks internally.

using (HttpClient client = new HttpClient(handler))
{
HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Get, url);
requestMessage.Headers.Add("Cookie", s_customCookieHeaderValue);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you add a variation for multiple values/cookies set?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure

@geoffkizer

Copy link
Copy Markdown
Author

@dotnet-bot test outerloop Windows x64 Debug Build
@dotnet-bot test outerloop OSX x64 Debug Build
@dotnet-bot test outerloop Linux x64 Debug Build

@geoffkizer

Copy link
Copy Markdown
Author

@dotnet-bot test outerloop Windows x64 Debug Build

@geoffkizer
geoffkizer merged commit 8cee267 into dotnet:master Feb 12, 2018
@karelz karelz added this to the 2.1.0 milestone Mar 10, 2018
picenka21 pushed a commit to picenka21/runtime that referenced this pull request Feb 18, 2022
SocketsHttpHandler: Fix some issues with cookie handling, and add cookie tests

Commit migrated from dotnet/corefx@8cee267
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

4 participants