Skip to content

Commit

Permalink
Start the process of testing the new RedirectOptions..
Browse files Browse the repository at this point in the history
  • Loading branch information
rassilon committed Feb 28, 2024
1 parent 9d8baf5 commit 6764396
Show file tree
Hide file tree
Showing 5 changed files with 115 additions and 11 deletions.
4 changes: 2 additions & 2 deletions src/RestSharp/Options/RestClientRedirectionOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,13 +36,13 @@ public class RestClientRedirectionOptions {

/// <summary>
/// Set to true (default), when you want to include cookies from the
/// CookieContainer on the redirected URL.
/// <see cref="CookieContainer"/> on the redirected URL.
/// </summary>
/// <remarks>
/// NOTE: The exact cookies sent to the redirected url DEPENDS directly
/// on the redirected url. A redirection to a completly differnet FQDN
/// for example is unlikely to actually propagate any cookies from the
/// CookieContqainer.
/// <see cref="CookieContainer"/>.
/// </remarks>
public bool ForwardCookies { get; set; } = true;

Expand Down
23 changes: 17 additions & 6 deletions src/RestSharp/RestClient.Async.cs
Original file line number Diff line number Diff line change
Expand Up @@ -210,13 +210,24 @@ async Task<HttpResponse> ExecuteRequestAsync(RestRequest request, CancellationTo

url = location;

if (responseMessage.Headers.TryGetValues(KnownHeaders.SetCookie, out var cookiesHeader1)) {
foundCookies = true;
// ReSharper disable once PossibleMultipleEnumeration
cookieContainer.AddCookies(url, cookiesHeader1);
// ReSharper disable once PossibleMultipleEnumeration
Options.CookieContainer?.AddCookies(url, cookiesHeader1);
if (Options.RedirectOptions.ForwardHeaders) {
if (!Options.RedirectOptions.ForwardAuthorization) {
headers.Parameters.RemoveParameter("Authorization");
}
if (!Options.RedirectOptions.ForwardCookies) {
headers.Parameters.RemoveParameter("Cookie");
}
else {
if (responseMessage.Headers.TryGetValues(KnownHeaders.SetCookie, out var cookiesHeader1)) {
foundCookies = true;
// ReSharper disable once PossibleMultipleEnumeration
cookieContainer.AddCookies(url, cookiesHeader1);
// ReSharper disable once PossibleMultipleEnumeration
Options.CookieContainer?.AddCookies(url, cookiesHeader1);
}
}
}

} while (true);

// Parse all the cookies from the response and update the cookie jar with cookies
Expand Down
52 changes: 52 additions & 0 deletions test/RestSharp.Tests.Integrated/RedirectOptionsTest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
using RestSharp.Tests.Integrated.Server;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RestSharp.Tests.Integrated {
[Collection(nameof(TestServerCollection))]
public class RedirectOptionsTest {
readonly string _host;
readonly Uri _baseUri;

public RedirectOptionsTest(TestServerFixture fixture) {
_baseUri = fixture.Server.Url;
_host = _baseUri.Host;
}

RestClientOptions NewOptions() {
return new RestClientOptions(_baseUri);
}

[Fact]
public async Task Can_RedirectForwardHeadersFalse_DropHeaders() {
var options = NewOptions();
options.RedirectOptions.ForwardHeaders = false;
var client = new RestClient(options);

// This request sets cookies and redirects to url param value
// if supplied, otherwise redirects to /get-cookies
var request = new RestRequest("/get-cookies-redirect") {
Method = Method.Get,
};
request.AddQueryParameter("url", "/dump-headers");

var response = await client.ExecuteAsync(request);
response.ResponseUri.Should().Be($"{_baseUri}dump-headers");
var content = response.Content;
content.Should().NotContain("'Accept':");
content.Should().NotContain("'Host': ");
content.Should().NotContain("'User-Agent':");
content.Should().NotContain("'Accept-Encoding':");
content.Should().NotContain("'Cookie':");

// Verify the cookie exists from the redirected get:
response.Cookies.Count.Should().BeGreaterThan(0).And.Be(1);
response.Cookies[0].Name.Should().Be("redirectCookie");
response.Cookies[0].Value.Should().Be("value1");
}

}
}
27 changes: 26 additions & 1 deletion test/RestSharp.Tests.Integrated/RedirectTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
//

using System.Net;
using RestSharp.Extensions;
using RestSharp.Tests.Integrated.Server;

namespace RestSharp.Tests.Integrated;
Expand Down Expand Up @@ -99,6 +100,30 @@ public async Task Can_Perform_PUT_Async_With_RedirectionResponse_Cookies() {
response.StatusCode.Should().Be(HttpStatusCode.MethodNotAllowed);
}

[Fact]
public async Task Can_ForwardHeadersTrue_OnRedirect() {
// This request sets cookies and redirects to url param value
// if supplied, otherwise redirects to /get-cookies
var request = new RestRequest("/get-cookies-redirect") {
Method = Method.Get,
};
request.AddQueryParameter("url", "/dump-headers");

var response = await _client.ExecuteAsync(request);
response.ResponseUri.Should().Be($"{_client.Options.BaseUrl}dump-headers");
var content = response.Content;
content.Should().Contain("'Accept':");
content.Should().Contain($"'Host': {_client.Options.BaseHost}");
content.Should().Contain("'User-Agent':");
content.Should().Contain("'Accept-Encoding':");
content.Should().Contain("'Cookie':");

// Verify the cookie exists from the redirected get:
response.Cookies.Count.Should().BeGreaterThan(0).And.Be(1);
response.Cookies[0].Name.Should().Be("redirectCookie");
response.Cookies[0].Value.Should().Be("value1");
}

// Needed tests:
//Test: ForwardHeaders = false
//Test: ForwardHeaders = true (default) might not need separate test
Expand All @@ -112,7 +137,7 @@ public async Task Can_Perform_PUT_Async_With_RedirectionResponse_Cookies() {
//Test: ForwardQuery = true (default, might not need test)
//Test: ForwardQuery = false
//Test: MaxRedirects
//Test: ForwardFragment = true
//Test: ForwardFragment = true (default)
//Test: ForwardFragment = false
//Test: AllowRedirectMethodStatusCodeToAlterVerb = true (default, might not need test)
//Test: AllowRedirectMethodStatusCodeToAlterVerb = false
Expand Down
20 changes: 18 additions & 2 deletions test/RestSharp.Tests.Integrated/Server/TestServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
using RestSharp.Tests.Integrated.Server.Handlers;
using RestSharp.Tests.Shared.Extensions;
using System.Net;
using System.Text;
using System.Web;

// ReSharper disable ConvertClosureToMethodGroup

Expand Down Expand Up @@ -38,6 +40,15 @@ public HttpServer(ITestOutputHelper? output = null) {
_app.MapGet("headers", HeaderHandlers.HandleHeaders);
_app.MapGet("request-echo", async context => await context.Request.BodyReader.AsStream().CopyToAsync(context.Response.BodyWriter.AsStream()));
_app.MapDelete("delete", () => new TestResponse { Message = "Works!" });
_app.MapGet("dump-headers",
(HttpContext ctx) => {
var headers = ctx.Request.Headers;
StringBuilder sb = new StringBuilder();
foreach (var kvp in headers) {
sb.Append($"'{kvp.Key}': '{kvp.Value}',");
}
return new TestResponse { Message = sb.ToString() };
});

// Cookies
_app.MapGet("get-cookies", CookieHandlers.HandleCookies);
Expand All @@ -48,12 +59,17 @@ public HttpServer(ITestOutputHelper? output = null) {
});
_app.MapGet("set-cookies", CookieHandlers.HandleSetCookies);
_app.MapGet("redirect", () => Results.Redirect("/success", false, true));

_app.MapGet(
"get-cookies-redirect",
(HttpContext ctx) => {
ctx.Response.Cookies.Append("redirectCookie", "value1");
return Results.Redirect("/get-cookies", false, true);
string redirectDestination = "/get-cookies";
var queryString = HttpUtility.ParseQueryString(ctx.Request.QueryString.Value);
var urlParameter = queryString.Get("url");
if (!string.IsNullOrEmpty(urlParameter)) {
redirectDestination = urlParameter;
}
return Results.Redirect(redirectDestination, false, true);
}
);

Expand Down

0 comments on commit 6764396

Please sign in to comment.