From 61293de8a50e0875e59d8636e3693a02448835fc Mon Sep 17 00:00:00 2001 From: Francesc Castells Date: Sat, 4 Mar 2023 11:49:57 +0000 Subject: [PATCH] Ignore exceptions parsing response cookies --- src/RestSharp/RestClient.Async.cs | 7 ++++++- test/RestSharp.Tests.Integrated/CookieTests.cs | 17 +++++++++++++++++ .../Server/Handlers/CookieHandlers.cs | 10 ++++++++++ 3 files changed, 33 insertions(+), 1 deletion(-) diff --git a/src/RestSharp/RestClient.Async.cs b/src/RestSharp/RestClient.Async.cs index f73555088..1eeed1106 100644 --- a/src/RestSharp/RestClient.Async.cs +++ b/src/RestSharp/RestClient.Async.cs @@ -119,7 +119,12 @@ async Task ExecuteRequestAsync(RestRequest request, CancellationTo // Parse all the cookies from the response and update the cookie jar with cookies if (responseMessage.Headers.TryGetValues(KnownHeaders.SetCookie, out var cookiesHeader)) { foreach (var header in cookiesHeader) { - cookieContainer.SetCookies(url, header); + try { + cookieContainer.SetCookies(url, header); + } + catch (CookieException) { + // Do not fail request if we cannot parse a cookie + } } } diff --git a/test/RestSharp.Tests.Integrated/CookieTests.cs b/test/RestSharp.Tests.Integrated/CookieTests.cs index d8071c664..fdbcb4013 100644 --- a/test/RestSharp.Tests.Integrated/CookieTests.cs +++ b/test/RestSharp.Tests.Integrated/CookieTests.cs @@ -48,4 +48,21 @@ void AssertCookie(string name, string value, Func checkExpiratio c.HttpOnly.Should().Be(httpOnly); } } + + [Fact] + public async Task GET_Async_With_Response_Cookies_Should_Not_Fail_With_Cookie_With_Empty_Domain() { + var request = new RestRequest("set-cookies"); + var response = await _client.ExecuteAsync(request); + response.Content.Should().Be("success"); + + Cookie? notFoundCookie = FindCookie("cookie_empty_domain"); + notFoundCookie.Should().BeNull(); + + HeaderParameter? emptyDomainCookieHeader = response.Headers! + .SingleOrDefault(h => h.Name == KnownHeaders.SetCookie && ((string)h.Value!).StartsWith("cookie_empty_domain")); + emptyDomainCookieHeader.Should().NotBeNull(); + ((string)emptyDomainCookieHeader!.Value!).Should().Contain("domain=;"); + + Cookie? FindCookie(string name) => response!.Cookies!.FirstOrDefault(p => p.Name == name); + } } diff --git a/test/RestSharp.Tests.Integrated/Server/Handlers/CookieHandlers.cs b/test/RestSharp.Tests.Integrated/Server/Handlers/CookieHandlers.cs index 4fcdd904a..8dd64962a 100644 --- a/test/RestSharp.Tests.Integrated/Server/Handlers/CookieHandlers.cs +++ b/test/RestSharp.Tests.Integrated/Server/Handlers/CookieHandlers.cs @@ -55,6 +55,16 @@ public static IResult HandleSetCookies(HttpContext ctx) { HttpOnly = true } ); + + ctx.Response.Cookies.Append( + "cookie_empty_domain", + "value_empty_domain", + new CookieOptions { + HttpOnly = true, + Domain = string.Empty + } + ); + return Results.Content("success"); } }